使用 '%' 运算符和参数元组时,psycopg2 出现“索引错误:元组索引超出范围”的错误

10

这很好用:

 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个回答

15
首先,您应该使用%%来插入%字面值,否则,库将尝试将所有%用作占位符。 其次,最好指定%s,这样您就可以插入值。
所以,您的代码应该像这样:"some_string %% %s"
cursor.execute("select * from books where name like '%%oo%%' OFFSET %s LIMIT %s", (0,1))

请注意,在Python 3中,您需要在元组中添加另一个逗号:cursor.execute("select * from books where name like '%%oo%%' OFFSET %s LIMIT %s", (0,1,)),否则会出现“TypeError: not all arguments converted during string formatting”错误。 - Nicholas Morley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接