Psycopg2 "IndexError: tuple index out the range" Error using operator "%" with tuple arguments

This works great:

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

But if the second argument is 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?

+6
source share
1 answer

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

So your code should look like this:

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

All Articles