mysql报错:Duplicate entry ‘xx‘ for key ‘PRIMARY‘ 解决可行方案。已解决!
情景:
在插入数据于数据库时,因为是从云服务器中随机拉取的,不知道哪条有没有拉到本地进行数据分析。
报错信息:
报错:Duplicate entry ‘251171‘ for key ‘PRIMARY‘
##### 原因:
问题1.每当唯一索引重复时,会破坏关系型数据库的唯一性原理。即使主键没有重复,设置了自增一。
问题2.主键没有设置自增一,主键重复也会报错。如果此时报错,这一次insert就会失败,就没有成功插入。
解决方案:代码直接一步到位!
代码逻辑就是读取.sql文件后,通过try.except语句pass这样的错误后,继续执行。因为这一条数据本地数据库中已经存在就没必要继续写入,直接跳过就好。
附完整代码:
"""
@contact: 微信 XQCqazwsx
@time: 2024/2/29 19:30
@author: 瑞翼工人
"""
import pymysql
import os
def execute_sql_file(file_path, connection):
if not os.path.exists(file_path):
print(f"File not found: {file_path}")
return
with open(file_path, 'r',encoding='utf-8') as sql_file:
sql_statements = sql_file.read().split(';')
for statement in sql_statements:
# 去除空白字符
statement = statement.strip()
if statement:
try:
with connection.cursor() as cursor:
cursor.execute(statement)
connection.commit()
print(f"Executed SQL statement: {statement}")
except pymysql.err.IntegrityError as e:
# 如果记录已存在则忽略错误
if "Duplicate entry" not in str(e):
print(f"Error executing SQL statement: {statement}\n{e}")
if __name__ == "__main__":
# 替换为你的 MySQL 数据库连接信息
host = "127.0.0.1"
user = "root"
password = "123456"
database = "test"
port = 3306, # 端口号
charset = 'utf8'
# 替换为你的 SQL 文件路径
sql_file_path = r"D:\测试log\data\alert_log1.sql"
try:
# 连接到 MySQL 数据库
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database,
cursorclass=pymysql.cursors.DictCursor
)
if connection.open:
execute_sql_file(sql_file_path, connection)
except pymysql.Error as e:
print(f"Error connecting to MySQL database: {e}")
finally:
# 关闭数据库连接
if 'connection' in locals() and connection.open:
connection.close()
print("MySQL connection closed.")
ction.open:
connection.close()
print("MySQL connection closed.")
总结,这是我实习岗位做数据分析时遇到问题的解决方法,如果你有更好的解决方案,欢迎跟我交流沟通!
“”"
@contact: 微信 XQCqazwsx
@time: 2024/2/29 19:30
@author: 瑞翼工人
“”"