【发布时间】:2019-08-05 12:01:58
【问题描述】:
无法执行 psycopg2 插入查询 (Postgres db),该查询使用最佳实践 %s 符号进行插入并包含包含 % 符号的 LIKE 语句。
LIKE 语句中的% 符号被解释为插入占位符。
'IndexError: tuple index out of range' 被抛出。
尝试使用反斜杠转义 %,但没有成功。
with psycopg2.connect(some_url) as conn:
with conn.cursor() as cur:
query = """
SELECT id
FROM users
WHERE surname IN %s AND named LIKE '%john'
"""
cur.execute(query, (tuple(["smith", "mcnamara"]),))
data = cur.fetchall()
【问题讨论】:
-
谢谢蒂姆,实际上 %s 的收藏对我来说很好用。
-
我对此感到惊讶,但无论如何我尝试了下面的答案,这可能会对您有所帮助。
-
来自手册:
in order to include a literal % in the query you can use the %% string。所以,LIKE '%%john'应该可以工作。 -
我知道这是旧的,但是 Jeremy 的上述解决方案在这种情况下对我有用。谢谢!
标签: python-3.x postgresql psycopg2