mysql 在insert时防止出现主键冲突错误的方法

在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)

  

posted @ 2022-09-19 22:04  lucky_tomato  阅读(1007)  评论(0编辑  收藏  举报