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