在mysql中插入数据的时候常常因为主键存在而冲突报错,下面有两个解决方法:
1、在insert 语句中添加ignore 关键字,如:insert ignore into table (id,name) values ('1','username');这是如果id主键已经存在的时候,就会忽略现在数据而保留原来的数据不变;
例子:
MySQL [tmp_database]> select * from student; +----+------+ | id | Name | +----+------+ | 1 | rcp | +----+------+ 1 row in set (0.00 sec) MySQL [tmp_database]> insert ignore into student Value(1,'kk'); MySQL [tmp_database]> select * from student; +----+------+ | id | Name | +----+------+ | 1 | rcp | +----+------+ 1 row in set (0.00 sec)
2、插入的时候用REPLACE INTO语句,如 REPLACE INTO table(id,name) values ('1','username');这个方法是如果id主键存在的时候就覆盖掉原来的数据。
MySQL [tmp_database]> REPLACE into student Value(1,'lisi'); Query OK, 2 rows affected (0.00 sec) MySQL [tmp_database]> select * from student; +----+------+ | id | Name | +----+------+ | 1 | lisi | +----+------+ 1 row in set (0.00 sec)
标签:tmp,insert,+----+------+,mysql,主键,student,MySQL,id From: https://www.cnblogs.com/lucktomato/p/16709281.html