Bind Variables with Python and Postgres

December 19, 2009

When executing SQL against Postgres with python, the bind variable format is different from that used for Oracle.

lCursor = connection.cursor()
lCursor.execute("""SELECT event.date_of_event, 
                   FROM contests_contest contest, contests_contestevent event 
                   WHERE event.owner_id = %(userid)s 
                   AND event.contest_id = 
                   AND event.date_of_event > %(startyear)s 
                   AND event.date_of_event < %(endyear)s 
                   ORDER BY event.date_of_event desc""",
     {'userid' :, 'startyear' : lStartYear, 'endyear' : lEndYear})

Note the s after the bind variable name in the body of the sql - this is a normal format specifier like %s.

Processing Results

Results can be processed using fetchall(), and then iterating around the rows:

lRows = lCursor.fetchall()
lClasses = []
for row in lRows:

row will be an array of the columns for the row being processed, here we're just referencing the first column.


If you're working within django, then you can get the connection from

from django.db import connection