[DB-SIG] PyGreSQL and NULLs

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Feb 10 17:17:55 EST 2004



On Tue, 10 Feb 2004, Marc Colosimo wrote:

> oops, I forgot to add that in my pseudo code. Here is a real example.
> As you see it puts in None, instead of Null. If I change "pet":None to
> "pet":"Null" it works.
>
> %psql test
> test=# CREATE TABLE myTable (
> test(# my_id INTEGER,
> test(# my_name TEXT,
> test(# my_pet_id INTEGER);
> CREATE TABLE
>
> Now for my_test.py
> !#/usr/bin/env python
>
> import pgdb
>
> db = pgdb.connect(database="test")
> cursor = db.cursor()
>
> my_user = {"id":10,"name":"Marc","pet":None}
>
> cursor.execute("INSERT into myTable (my_id, my_name, my_pet_id) values
> " +
>              "(%(id)s,'%(name)s',%(pet)s)" % my_user)
                                             ^^^^^^^^^


Hi Marc,


Don't do that.  *grin*


Send cursor.execute a second parameter --- that dictionary 'my_user' ---
and let the driver do the interpolation for you.

###
>>> import pgdb
>>> conn = pgdb.connect(database='dyoo')
>>> cursor = conn.cursor()
>>> my_user = {'id' : 10, 'name' : 'dyoo', 'pet' : None}
>>> cursor.execute('''insert into myTable (my_id, my_name, my_pet_id)
...                   values (%(id)s, %(name)s, %(pet)s)''',
...                my_user)
>>> conn.commit()
###


Do not try to do the interpolation yourself: let the database handler do
it.




Hope this helps!




More information about the DB-SIG mailing list