【问题标题】:Psycopg2 ProgrammingError: syntax error at or near SELECTPsycopg2 ProgrammingError:SELECT 处或附近的语法错误
【发布时间】:2019-05-10 18:14:44
【问题描述】:

试图将变量传递给 psql 查询。代码如下。我最终试图将结果复制到 CSV 文件中,但在尝试执行模块 cur.copy_expert 时发生错误。

date1 = ('2019-05-06',)
query = ('''SELECT * FROM product WHERE (product.esb_timestamp > %s AND product.esb_timestamp < '2019-05-11')''', date1)

# Copy the results to a new file
output = "COPY ({0}) to STDOUT WITH CSV HEADER".format(query)
with open('Database_Query.csv', 'w') as file1:
    cur.copy_expert(output, file1)

以下错误:

Traceback (most recent call last):
  File "database_query.py", line 55, in <module>
    cur.copy_expert(output, file1)
psycopg2.ProgrammingError: syntax error at or near ""SELECT * FROM nwwproduct WHERE (nwwproduct.esb_timestamp > %s AND nwwproduct.esb_timestamp < '2019-05-11')""
LINE 1: COPY (("SELECT * FROM nwwproduct WHERE (nwwproduct.esb_times...

【问题讨论】:

  • 去掉括号,为了清楚起见将引号改为",并将单个参数作为元组传递:query = ("""SELECT * FROM product WHERE product.esb_timestamp &gt; %s AND product.esb_timestamp &lt; '2019-05-11'""", (date1,))。那样有用吗?如果没有,请将%s 换成?;我不能确定这里预期的绑定参数。
  • 重构括号会导致同样的错误,就像使用?一样。
  • 你用我的建议的复制/粘贴替换了整行代码?
  • 是的,复制粘贴。
  • 根据 postgresql.org 的这个答案,COPY 不支持参数。 link

标签: python sql python-2.7 psycopg2 psql


【解决方案1】:

正如psycopg2 docs 提到的那样

如果需要动态编写 COPY 语句(因为表, 字段或查询参数在 Python 变量中),您可以使用 psycopg2.sql 模块提供的对象。

psycopg2 的一位作者和当前维护者也从GitHub ticket 中证实了这一点:@dvarrazzo。

from psycopg2 import sql

stmt = """COPY (SELECT * FROM product 
                WHERE (product.esb_timestamp > {dt} 
                  AND  product.esb_timestamp < '2019-05-11')
               ) TO STDOUT WITH CSV HEADER"""

query = sql.SQL(stmt).format(dt=sql.Literal("2019-05-06"))

with open('Database_Query.csv', 'w') as file1:
    cur.copy_expert(query, file1)

请注意,这与 Python 的 str.format 不同,并且可以安全地将值插入到准备好的语句中。

【讨论】:

    【解决方案2】:

    COPY 不支持参数。 Reference

    【讨论】:

      猜你喜欢
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2018-03-12
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      相关资源
      最近更新 更多