【问题标题】:psycopg2 "IndexError: tuple index out of range" Error when using '%' like operator with arguments tuplepsycopg2“IndexError:元组索引超出范围”使用带有参数元组的'%'类似运算符时出错
【发布时间】:2012-12-27 12:43:34
【问题描述】:

这很好用:

 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

如何避免这个错误?

【问题讨论】:

    标签: python psycopg2


    【解决方案1】:

    首先,您应该使用%% 插入% 文字,否则,库将尝试使用所有% 作为占位符。其次,最好指定%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
    猜你喜欢
    • 2017-08-23
    • 1970-01-01
    • 2013-07-28
    • 2018-11-16
    • 2017-07-12
    • 2017-05-25
    • 1970-01-01
    相关资源
    最近更新 更多