PostgreSQL查询在pgAdmin4正常运行 Python psycopg2加条件报语法错误
问题解决方法
错误原因
你当前的代码语法错误是因为将and product.prodtempindex = 2这部分SQL条件写在了cur.execute()方法的调用括号之外,不属于传入execute方法的SQL语句参数,直接被Python解析为独立的字符串常量,不符合语法规则。
修复方案
根据product.prodtempindex的取值是否固定,有两种可选写法:
方案1:prodtempindex取值固定为2
直接把条件拼接进SQL语句字符串即可,参数列表保持不变:
cur.execute( "select product.width, product.height from product inner join product_template on product.prodtempindex = product_template.prodtempindex inner join painting on painting.pntindex = product.pntindex where painting.catalognumber = %s and product.prodtempindex = 2", [number] )
方案2:prodtempindex取值为动态变量
新增一个%s占位符对应第二个查询条件,参数列表传入两个值即可:
# 可以根据业务需要修改temp_index的取值 temp_index = 2 cur.execute( "select product.width, product.height from product inner join product_template on product.prodtempindex = product_template.prodtempindex inner join painting on painting.pntindex = product.pntindex where painting.catalognumber = %s and product.prodtempindex = %s", (number, temp_index) )
注意事项
psycopg2框架的查询参数统一使用%s作为占位符,不需要额外加单引号,参数可以用列表或者元组传递,数量要和占位符一一对应。
内容的提问来源于stack exchange,提问作者meejo57
相关产品推荐
相关产品推荐

