psycopg NULL

Ross M Karchner ross at karchner.com
Wed Feb 18 12:08:12 EST 2004


What is the value of psycopg.paramstyle ?

You probably have to follow the paramstyle format to get the automatic 
translation between Python None to SQL Null.

http://www.python.org/peps/pep-0249.html

If it is 'pyformat' (Like MySQLdb), then this might work:

curs.execute('INSERT INTO foo (i) VALUES (%s)' , None)
curs.execute('INSERT INTO foo (i) VALUES (%d)' , None)
curs.execute('INSERT INTO foo (i) VALUES (%i)' , None)
conn.commit()

note: all I did was replace the %'s with commas

-Ross
Lee Harr wrote:
> When I am retrieving rows using psycopg, a NULL value
> from the database will be translated to python None.
> 
> What I cannot figure out is how to insert a NULL.
> 
> 
> 
> import psycopg
> 
> DSN = 'dbname=test6 user=auth1'
> conn = psycopg.connect(DSN)
> curs = conn.cursor()
> 
> curs.execute('CREATE TABLE foo (i integer)')
> conn.commit()
> 
> # These all work
> curs.execute('INSERT INTO foo (i) VALUES (%s)' % 5)
> curs.execute('INSERT INTO foo (i) VALUES (%i)' % 4)
> curs.execute('INSERT INTO foo (i) VALUES (%d)' % 3)
> conn.commit()
> 
> # None of these work ...
> #curs.execute('INSERT INTO foo (i) VALUES (%s)' % None)
> #curs.execute('INSERT INTO foo (i) VALUES (%d)' % None)
> #curs.execute('INSERT INTO foo (i) VALUES (%i)' % None)
> #conn.commit()
> 
> # If I insert NULL some other way, this works
> curs.execute('SELECT * FROM foo')
> rows = curs.fetchall()
> for row in rows:
>     if row[0] is None:
>         print 'None!'
> 
> 
> 
> Any suggestions?
> 



More information about the Python-list mailing list