【发布时间】: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 > %s AND product.esb_timestamp < '2019-05-11'""", (date1,))。那样有用吗?如果没有,请将%s换成?;我不能确定这里预期的绑定参数。 -
重构括号会导致同样的错误,就像使用
?一样。 -
你用我的建议的复制/粘贴替换了整行代码?
-
是的,复制粘贴。
-
根据 postgresql.org 的这个答案,COPY 不支持参数。 link
标签: python sql python-2.7 psycopg2 psql