Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Psycopg2 using wildcard causes TypeError

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 ;)

like image 613
The Jug Avatar asked Oct 15 '10 16:10

The Jug


People also ask

How do you handle psycopg2 error?

In the psycopg2 adapter library you can return the code by accessing the exception's pgcode attribute. It should be an alpha-numeric string, five characters in length, that corresponds to an exception in the PostgreSQL Error Codes table.

Is psycopg2 connection thread safe?

Thread and process safetyThe Psycopg module and the connection objects are thread-safe: many threads can access the same database either using separate sessions and creating a connection per thread or using the same connection and creating separate cursors. In DB API 2.0 parlance, Psycopg is level 2 thread safe.

Does psycopg2 need PostgreSQL?

Prerequisites. The current psycopg2 implementation supports: Python versions from 3.6 to 3.11. PostgreSQL server versions from 7.4 to 15.

Is psycopg2 asynchronous?

Psycopg allows asynchronous interaction with other database sessions using the facilities offered by PostgreSQL commands LISTEN and NOTIFY.


1 Answers

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 

EDIT: 10+ years later, I'm looking at the psycopg2 issues for an unrelated bug and found that the developers recognize this as an issue. My comments below were correct. If you're passing arguments in your query, then you must escape the percent signs in your LIKE clause. If you're not passing arguments, then you don't escape your LIKE clause.

like image 171
Joe Holloway Avatar answered Oct 15 '22 22:10

Joe Holloway