psycopg2" IndexError:元组索引超出范围"使用'%'时出错喜欢带参数元组的运算符

时间:2012-12-27 12:43:34

标签: python psycopg2

这很好用:

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

但如果第二个论点通过:

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

Psycopg错误:

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

如何避免此错误?

1 个答案:

答案 0 :(得分:10)

首先,您应该使用%%插入%字面值,否则,库会尝试将所有%用作占位符。其次,最好指定要插入值的%s

因此,您的代码应如下所示:

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