【问题标题】:psycopg2 insert statement with LIKE clause containing % sign带有包含 % 符号的 LIKE 子句的 psycopg2 插入语句
【发布时间】: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


【解决方案1】:

尝试对 LIKE 表达式也使用占位符,然后将带有通配符的文字绑定到它:

query = """
    SELECT id
    FROM users
    WHERE surname IN %s AND named LIKE %s"""

cur.execute(query, (tuple(["smith", "mcnamara"]), "%John",))
data = cur.fetchall()

【讨论】:

  • 我不知道可以使用 Python 中的语句绑定集合。它不能用 Java 完成 AFAIK(这是我大部分时间都在使用的)。
  • 我可以确认它在 psycopg2 + Python3.x 中工作,感谢 Tim 的提示。
【解决方案2】:

试试这个:

with psycopg2.connect(some_url) as conn:
    with conn.cursor() as cur:
        query = """
        SELECT id
        FROM users
        WHERE surname IN %s AND named LIKE '%sjohn'
        """

        cur.execute(query, (tuple(["smith", "mcnamara"]), '%'))
        data = cur.fetchall()

【讨论】:

  • 您不需要在 %s 占位符周围加上单引号(事实上,这部分违背了使用准备好的语句的目的)。
  • 这只是修改的初始语句
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
相关资源
最近更新 更多