Re: auto escaping "NULL"

Federico Di Gregorio <fog-NGVKUo/i/[email protected]>
Newsgroups gmane.comp.python.db.psycopg.devel
Organization initd.org
Message-ID <1259917011.3263.4.camel@mila>
Il giorno gio, 03/12/2009 alle 18.24 -0500, Jacob Joseph ha scritto:
> Hi.
> Upon trying to insert NULL values into a double precision field, I
> receive the error:
> 
> DataError: invalid input syntax for type double precision: "NULL"
> LINE 4:         (2, -1, E'NULL', 1.11,
> 
> I'm using a statement like:
> curs.execute("INSERT INTO foo (distance) VALUES (%(dist)s)", {'dist':
> None})

That's the correct way and should work. The code you show us is not the
code you're actually executing? ;)

> As a related question, what is the correct way to use the execute(s,
> args) syntax, but *not* escape a particular variable?  Not so
> infrequently, I'd like to use an argument to add an SQL command, such
> as adding to a WHERE or specifying a field.

You should use the normal % operator to build a query string and then
pass it to execute. If you really want to avoid quoting of a bound
variable you can import psycopg2.extras and then wrap the variable in
AsIs() (AsIs just call wrapped object's str() method):

curs.execute("INSERT INTO foo (distance) VALUES (%(dist)s)",
             {'dist': AsIs("NULL")})

But note that this example is a bad use case bacause psycopg knows how
to parse None and you should use AsIs only in very special cases (and
then be ashamed of it.)

federico

-- 
Federico Di Gregorio                         http://people.initd.org/fog
Debian GNU/Linux Developer                                [email protected]
INIT.D Developer                                           fog-NGVKUo/i/[email protected]
 Questo autista me l'ha fatta a cotone!
                                     -- sedicenne palermitana in autobus

_______________________________________________
Psycopg mailing list
Psycopg-IAPFreCvJWPBWskQ1e/[email protected]
http://lists.initd.org/mailman/listinfo/psycopg
signature.asc (application/pgp-signature, 198 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (GNU/Linux)

iEYEABECAAYFAksYztIACgkQvcCgrgZGjeuiegCfV/+LxLyXYMHS1aaVqfXaiMbc
XiEAoKrsk9avg9FxJd3H4OOTXl1hWseY
=Uvut
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.