views:

29

answers:

1

Currently I am attempting to search a database to grab certain events. My query is as such

SELECT * FROM events WHERE summary ILIKE E'%test%' AND start_time > '2010-10-01'

Simply put I need the query to look through a database of calendar events and return anything with a summary with 'test' in it and after the beginning of this month.

This returns the expected results when queried from the database command line. However when I attempt to use it in my Python script with psycopg2 as such:

cursor.execute("SELECT * FROM events WHERE summary ILIKE E'%test%' AND start_time > %(begin)s ", {'begin' : datetime.datetime(2010,10,1) })

I get a type error

*** TypeError: 'dict' object does not support indexing

Doing some initial Googling it sounds like something with the way I'm using my wildcards. I could be wrong though and I am probably missing something simple that I don't see. Hopefully a fresh pair of eyes from the community can correct my noobishness ;)

+1  A: 

Not sure if this is the full root of your problem, but I think you need to escape your wildcards or the parameterization logic will get confused.

SELECT * FROM events WHERE summary ILIKE E'%%test%%' AND start_time > %(begin)s 

I think %% is the correct escaping, but it could be \%

Joe Holloway
Hm that does fix that. But I don't believe that is the root problem since I tried on a whim of getting rid of the dictionary and just running the line without substitution to see if the wildcard was indeed not being escaped right. Getting rid of the dictionary worked so why do I need to escape the wildcard when a dictionary is used?
The Jug
The underlying parameter substitution uses '%' as a special character meaning 'hey, substitute a value from my dict in here'. My guess is that if you don't pass the dict, this parameterization logic is skipped entirely so there's no chance for it to get confused by the presence of '%' in your where clause. In other words, it's likely choking *in* the parameterization step which you're no longer doing. So, if you're passing parameters you need to escape the special % character, otherwise not.
Joe Holloway
Okay that makes sense. Thank you sir!
The Jug