Python操作MySQL数据库,插入重复数据

[python] view plain copy
 
print?
  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()  
sql = "INSERT  INTO test_c(id,name,sex)values(%s,%s,%s)"
param = (1,'AJ','MAN')
n = cursor.execute(sql,param)
db.commit()


当我们使用普通的 “INSERT INTO" 插入数据,如果数据有重复就会有报错:

 

提示的是键值重复

 

[python] view plain copy
 
print?
  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 '1-AJ-MAN' for key 'PRIMARY'")  
Traceback (most recent call last):
  File "D:/python/tongbu_py/test.py", line 14, in <module>
    n = cursor.execute(sql,param)
  File "D:\Python27\lib\site-packages\MySQLdb\cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "D:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.IntegrityError: (1062, "Duplicate entry '1-AJ-MAN' for key 'PRIMARY'")

 

 

我们可以使用另外2个传入方法: ”INSERT IGNORE INTO 和 REPLACE INTO“:


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


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

转自, 年数久远 ,未能找到作者,特此为原作者致谢

posted @ 2017-07-28 09:43  一片黑  阅读(4888)  评论(0编辑  收藏  举报