lburnett
lburnett

Reputation: 11

IndexError: tuple index out of range with psycopg2

This code has no issues:

cursor.execute("select message from snippets where keyword=%s", (name,))

However, with this I get an IndexError: tuple index out of range

cursor.execute("select * from table where prescription like '\"%\"%s%'", (string,))

Where am I going wrong?

Upvotes: 1

Views: 2087

Answers (2)

piro
piro

Reputation: 13931

In order to enter a literal % in the query you have to use %%.

Upvotes: 0

Mureinik
Mureinik

Reputation: 312136

The second snippet puts the variable inside a string literal (as it's surrounded by single quotes), so psycopg doesn't handle it. One way to solve this is to keep the placeholder form and perform the string manipulation in your Python code before binding it:

name = '%%%s%%' % name
cursor.execute("select * from table where prescription like %s", (name,))

Upvotes: 2

Related Questions