Psycopg2 ProgrammingError: syntax error at or near SELECT

Psycopg2 ProgrammingError: syntax error at or near SELECT

正在尝试将变量传递给 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...

COPY 不支持参数。 Reference

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.

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

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 不同,并且可以安全地将值插入到准备好的语句中。