- sql = "INSERT INTO test_c(id,name,sex)values(%s,%s,%s)"
- param = (1,'AJ','MAN')
- n = cursor.execute(sql,param)
- 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" 插入数据,如果数据有重复就会有报错:
提示的是键值重复
- Traceback (most recent call last):
- File "D:/python/tongbu_py/test.py", line 14, in <module>
- n = cursor.execute(sql,param)
- File "D:Python27libsite-packagesMySQLdbcursors.py", line 174, in execute
- self.errorhandler(self, exc, value)
- File "D:Python27libsite-packagesMySQLdbconnections.py", line 36, in defaulterrorhandler
- raise errorclass, errorvalue
- _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:Python27libsite-packagesMySQLdbcursors.py", line 174, in execute self.errorhandler(self, exc, value) File "D:Python27libsite-packagesMySQLdbconnections.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相同的记录,则先删除掉。再插入新记录。
转自, 年数久远 ,未能找到作者,特此为原作者致谢