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

PyMySQL忽略警告失败:插入重复request_id致循环终止求助

解决方案

方案1:使用INSERT IGNORE语句

直接修改SQL语句,MySQL会自动忽略唯一键重复的插入操作,不会抛出异常,循环可正常继续执行。

修改后的SQL:

INSERT IGNORE INTO `mydb`.`logs` (`request_id`) VALUES (%s);

对应代码片段调整:

sql = "INSERT IGNORE INTO `mydb`.`logs` (`request_id`) VALUES (%s);"
cursor.execute(sql, (request_id,))  # 注意加逗号,确保参数是元组格式
connection.commit()

方案2:使用ON DUPLICATE KEY UPDATE

如果需要在遇到重复键时执行更新操作(比如更新记录时间),或者仅需避免报错,可使用该语法。若无需更新字段,可设置字段等于自身:

INSERT INTO `mydb`.`logs` (`request_id`) VALUES (%s) ON DUPLICATE KEY UPDATE request_id = request_id;

该语句遇到重复键时会执行无意义的更新,既不修改数据,也不会抛出异常。

方案3:捕获特定异常并跳过

若需要在遇到重复时做额外处理(比如记录日志),可在代码中捕获IntegrityError,判断错误码为1062时跳过当前循环:

修改后的完整代码:

import pymysql
import json

# 假设is_json是你定义的判断函数
def is_json(s):
    try:
        json.loads(s)
        return True
    except:
        return False

try:
    # 这里补充你的connection创建逻辑,比如:
    # connection = pymysql.connect(host='xxx', user='xxx', password='xxx', db='mydb')
    cur = connection.cursor()
    with cur as cursor:
        with open("logs.json", 'r', encoding='UTF-8') as file:
            for line in file:
                json_line = line.strip()
                if is_json(json_line):
                    json_logs = json.loads(json_line)
                    request_id = json_logs['request_id']
                    sql = "INSERT INTO `mydb`.`logs` (`request_id`) VALUES (%s);"
                    try:
                        cursor.execute(sql, (request_id,))
                        connection.commit()
                    except pymysql.err.IntegrityError as e:
                        if e.args[0] == 1062:
                            # 唯一键重复,跳过当前记录
                            print(f"重复request_id: {request_id}")
                        else:
                            # 其他完整性错误,重新抛出
                            raise
finally:
    connection.close()

关键注意点

  • cur._defer_warnings = True仅对警告有效,而唯一键冲突属于错误,因此该设置无效,无需保留。
  • 执行execute时,参数必须是元组格式,(request_id)会被解析为单个值,需写成(request_id,)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:50:54