I have the following code:
query = "SELECT * FROM appointments WHERE service IN %s AND location LIKE '%London%'"
values = (services,) # services is a tuple of strings.
cur.execute(query, values)
When I execute this code I get the following error:
--> cur.execute(query, values)
IndexError: tuple index out of range
After researching the topic a little bit, I think that the %L
in the query is being detected as a placeholder, so the psycopg2
library is trying to insert data there, but there is no more data in the values
tuple.
I have tried escaping the %
sign using the following query:
query = "SELECT * FROM appointments WHERE service IN %s AND location LIKE '%%London%'"
but this has also not worked.
How can I fix this issue and get the expected behaviour?
2
Answers
You can safely format your query using the
pscyopg2.sql
library. The below code adds a placeholder value for each element within the services tuple into the query string, then you can execute as you normally would.from the docs, a better and easier approach for such use cases would be to use
POSIX
regex overLIKE
orSIMILAR TO
operators,im not sure about its compatibility with different psycopg as well as posgresql versions.