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

psycopg2.errors.SyntaxError:执行INSERT语句时输入末尾语法错误

问题排查与解决

错误原因

你的SQL语句使用ON CONFLICT子句后未指定冲突处理逻辑,PostgreSQL要求该子句必须明确冲突发生时的操作(比如忽略或更新),仅写ON CONFLICT (country, year, month)会触发语法错误。

修复方案

根据业务需求选择以下两种写法之一:

方案1:冲突时跳过插入

如果希望冲突发生时不做任何操作,直接跳过当前插入:

data = {
    'country': data['country'][x],
    'year': data['year'][x].astype(float),
    'month': data['month'][x].astype(float)
}
db_connection.execute(
    """
    INSERT INTO my_table (country, year, month) 
    VALUES (%(country)s, %(year)s, %(month)s) 
    ON CONFLICT (country, year, month) DO NOTHING
    """,
    data,
)

方案2:冲突时更新现有记录

如果希望冲突发生时更新现有记录的字段(示例用EXCLUDED指代被冲突拦截的插入数据,可按需调整更新字段):

data = {
    'country': data['country'][x],
    'year': data['year'][x].astype(float),
    'month': data['month'][x].astype(float)
}
db_connection.execute(
    """
    INSERT INTO my_table (country, year, month) 
    VALUES (%(country)s, %(year)s, %(month)s) 
    ON CONFLICT (country, year, month) 
    DO UPDATE SET 
        country = EXCLUDED.country,
        year = EXCLUDED.year,
        month = EXCLUDED.month
    """,
    data,
)

额外注意事项

  • 确保my_table已在country, year, month字段上创建唯一约束(主键或唯一索引),否则ON CONFLICT子句无法生效。
  • 代码中多余的f""""可以去掉,psycopg2的参数化查询(%(key)s格式)本身就能安全传递参数,避免SQL注入风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:55:26