[英]Psycopg2 ProgrammingError: syntax error at or near SELECT
Trying to pass a variable to a psql query. 试图将变量传递给psql查询。 Code below.
下面的代码。 I'm ultimately trying to copy the results to a CSV file and an error occurs trying to execute the module cur.copy_expert.
我最终尝试将结果复制到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)
Error below: 错误如下:
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...
As psycopg2 docs mentions 正如psycopg2 docs所提到的
If you need to compose a COPY statement dynamically (because table, fields, or query parameters are in Python variables) you may use the objects provided by the psycopg2.sql module.
如果您需要动态编写COPY语句(因为表,字段或查询参数在Python变量中),则可以使用psycopg2.sql模块提供的对象。
This is also confirmed from this GitHub ticket by one of the psycopg2 authors and current maintainer: @dvarrazzo. psycopg2作者之一和当前维护者@dvarrazzo也从GitHub票证中证实了这一点。
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)
Do be aware this is different from Python's str.format
and safely interpolates values to prepared statement. 请注意,这与Python的
str.format
不同,可以安全地将值插入到准备好的语句中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.