tags:

views:

83

answers:

1

It should be simple, bit I've spent the last hour searching for the answer. This is using psychopg2 on python 2.6.

I need something like this:

    special_id = 5
    sql = """
          select count(*) as ct,
            from some_table tbl
           where tbl.id = %(the_id)
      """
cursor = connection.cursor()
cursor.execute(sql, {"the_id" : special_id})

I cannot get this to work. Were special_id a string, I could replace %(the_id) with %(the_id)s and things work well. However, I want it ot use the integer so that it hits my indexes correctly.

There is a surprising lack of specific information on psychopg2 on the internet. I hope someone has an answer to this seemingly simple question.

+2  A: 

Per PEP 249, since in psycopg2 paramstyle is pyformat, you need to use %(the_id)s even for non-strings -- trust it to do the right thing.

BTW, internet searches will work better if you use the correct spelling (no h there), but even if you mis-spelled, I'm surprised you didn't get a "did you mean" hint (I did when I deliberately tried!).

Alex Martelli
I *hate* trusting DB drivers to do the right thing. I've been bitten by implicit Sybase date conversion missing indexes on too many times. I guess I have no choice with psycopg. As for the spelling, I guess the mind-image of the correct spelling of psycho over ruled any Google suggestions - thanks for the pointer.