You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 23:54:03