Postgres 插入语法错误

Postgres insert syntax error

我的 SQL 查询如下所示:

product = 'Huggies Little Movers Diaper Pants for Boys Size 5 (60 Count)'
retailer = 'Target'
query = """SELECT * FROM product_info WHERE product_name = %s AND retailer = %s""" % (product, retailer)

conn = psycopg2.connect("dbname='test1' user='postgres' host='localhost' password='123'")
cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
cur.execute(query)

当我执行它时,我收到一条错误消息:

psycopg2.ProgrammingError: syntax error at or near "Basic"

我不确定为什么我的语法错误

您的声明;

query = """SELECT * FROM product_info WHERE product_name = %s AND retailer = %s""" % (product, retailer)

...从查询和参数构建一个完整的字符串,而不在您的字符串周围加引号,这使得整个字符串无效 SQL,在 execute 时失败;

SELECT * FROM product_info 
WHERE product_name = Huggies Little Movers Diaper Pants for Boys Size 5 (60 Count) 
  AND retailer = Target

您可能想要做的是参数化您的查询,而不是通过在元组中传递参数在 execute 中完成;

query = """SELECT * FROM product_info WHERE product_name = %s AND retailer = %s"""
...
cur.execute(query, (product, retailer))