Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psycopg2 "IndexError: tuple index out of range" Error when using '%' like operator with arguments tuple

This works fine:

 cc.execute("select * from books where name like '%oo%'")

But if second argument passed:

cursor.execute("select * from books where name like '%oo%' OFFSET % LIMIT %", (0,1))

Psycopg errors:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

How to avoid this error?

like image 734
juk Avatar asked Dec 27 '12 12:12

juk


1 Answers

First of all, you should use %% to insert % literal, otherwise, library will try to use all % as placeholders. Second, it's better to specify %s, where you want to insert values.

So, your code should look like:

cursor.execute("select * from books where name like '%%oo%%' OFFSET %s LIMIT %s", (0,1))
like image 122
cleg Avatar answered Oct 21 '22 23:10

cleg