_mysql_exceptions.IntegrityError: (1062, "Duplicate entry, Python操作MySQL数据库,插入重复数据...

本文探讨了在使用SQL进行数据插入时常见的问题及其解决办法。重点介绍了如何使用`INSERT IGNORE`来避免因键值重复导致的错误,并对比了`REPLACE INTO`的功能差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[python] view plain copy

  1. sql = "INSERT  INTO test_c(id,name,sex)values(%s,%s,%s)"  
  2. param = (1,'AJ','MAN')  
  3. n = cursor.execute(sql,param)  
  4. db.commit() 
当我们使用普通的 “INSERT INTO" 插入数据,如果数据有重复就会有报错:

提示的是键值重复

[python]  view plain  copy
  1. Traceback (most recent call last):  
  2.   File "D:/python/tongbu_py/test.py", line 14, in <module>  
  3.     n = cursor.execute(sql,param)  
  4.   File "D:\Python27\lib\site-packages\MySQLdb\cursors.py", line 174, in execute  
  5.     self.errorhandler(self, exc, value)  
  6.   File "D:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler  
  7.     raise errorclass, errorvalue  
  8. _mysql_exceptions.IntegrityError: (1062, "Duplicate entry

INSERT IGNORE会忽略数据库中已经存在的数据,如果数据库没有数据,就插入新的数据,如果有数据的话就跳过这条数据。这样就可以保留数据库中已经存在数据,达到在间隙中插入数据的目的

REPLACE INTO 如果存在primary 或 unique相同的记录,则先删除掉。再插入新记录。

 

You seem to be inserting constants into the database, not your actual values. Instead, try something similar to;

db_query = cur.execute("INSERT INTO tblS100CurrentListing " + "(articleCode, dateReceived, s100RSD, remarks) VALUES (%s, %s, %s, %s)", (articleCode, dateReceived, s100rsd, remark_text))

 

What you want to search for is something called "SQLSTATE" - a set of standard error codes that cover most common RDBMS error states. They don't necessarily provide enough detail for all purposes though, and I don't know if sqlite supports them.

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值