Trying to pass a variable to a psql query. 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.
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...
"for clarity, and pass the single argument as a tuple:query = ("""SELECT * FROM product WHERE product.esb_timestamp > %s AND product.esb_timestamp < '2019-05-11'""", (date1,)). Does that work? If not, swap%sfor?; I can't be sure on the binding parameter expected here.?.