MySQL 报 duplicate entry for key primary 错误

原因:
插入数据时,要插入数据的主键数据(…)已经存在,不能再重复添加了。
另外 1062、1060等错误都是同一个意思
解决:
1、插入前,先执行一遍查询,看主键是否已存在
2、写一个exists查询语句
if not exists (select ip from table1 where id = id1)
insert into table1 (id ,name,...) values(id1,'第一行')
else
update table1 set name= '第二行' where id = id1
但不推荐这么做,每次都需要执行2次sql,影响效率
3、加锁
悲观锁太影响性能
乐观锁,一般用于更新操作
4、ON DUPLICATE KEY UPDATE 当主键存在则更新,不存在则插入
insert into table1 (id ,name,...) values(id1,'第一行')
on duplicate key update
name='第二行'
5、int长度已达最大值
如你的表数据量庞大,如日志表,int的最大长度为:2147483647 ,先看看你的表主键已达到多少,如果已达到这个值则无法继续增长
设计表之初优先考虑表的用途,如日志表主键则使用 bigint