Psycopg2 ProgrammingError:SELECT或附近的语法错误

时间:2019-05-10 18:14:44

标签: python sql python-2.7 psycopg2 psql

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

2 个答案:

答案 0 :(得分:2)

psycopg2 docs提到

  

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

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

答案 1 :(得分:0)

COPY不支持参数。 Reference