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

Python SQL查询报错psycopg2.errors.SyntaxError:where子句语法错误

问题解决思路

你的报错根源是SQL语法错误——一条SELECT语句只能有一个WHERE关键字,你连续写了三个WHERE,数据库解析到第二个WHERE时就会触发语法报错,和is true/= true的写法无关。

修正步骤

  • 合并所有过滤条件到同一个WHERE子句,用AND连接每个条件
  • (可选但推荐)替换字符串格式化方式,使用参数化查询避免SQL注入风险

修正后的代码示例

基础修正(解决语法错误)

student_info_query = """
select student_age from students sd
inner join registers rv on sd.id = rv.student_id
where rv.is_paid is true 
  and rv.is_accepted is true
  and sd.id = {}
  and sd.class_id = {}
""" 
query_df = db_connection.query(student_info_query.format(std_id, cls_id))

更安全的参数化查询(psycopg2推荐写法)

student_info_query = """
select student_age from students sd
inner join registers rv on sd.id = rv.student_id
where rv.is_paid is true 
  and rv.is_accepted is true
  and sd.id = %s
  and sd.class_id = %s
""" 
query_df = db_connection.query(student_info_query, (std_id, cls_id))

内容的提问来源于stack exchange,提问作者moh19814

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:17:08