Mysql批量插⼊数据时是否为原⼦操作摘要
mysql⽀持批量插⼊,即insert into values(),().. ,可以⼀次插⼊多条数据,那么这⼀次插⼊是否为原⼦操作呢?通过测试验证⼀下mysql⼀次批量插⼊结果是不是要么全部插⼊成功,要么全部插⼊失败
建⽴测试表
建⽴⼀个带unique key的表作为实验表,当插⼊重复uk的数据mysql会插⼊失败
CREATE TABLE `uk_test` (
`id` bigint(32) NOT NULL AUTO_INCREMENT,
`ip` varchar(32) NOT NULL,
`gmt_create` datetime NOT NULL COMMENT 'create time',
`gmt_modify` datetime NOT NULL COMMENT 'modify time',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq` (`ip`)
) ENGINE=InnoDB AUTO_INCREMENT=106 DEFAULT CHARSET=utf8
⽤ip列建⽴了uk
测试批量插⼊
case 1.当⼀次插⼊的多条数据中,存在相同uk的情况:
select * from uk_test;
+-----+---------+---------------------+---------------------+
| id  | ip      | gmt_create          | gmt_modify          |
+-----+---------+---------------------+---------------------+
| 106 | 1.1.1.1 | 2020-11-17 14:43:43 | 2020-11-17 14:43:43 |
+-----+---------+---------------------+---------------------+
//插⼊数据
insert into uk_test(id,ip,gmt_create,gmt_modify) values(null, "1.1.1.2",now(),now()),(null,"1.1.1.2",now(),now());
ERROR 1062 (23000): Duplicate entry '1.1.1.2' for key 'uniq'
//两条都没有插⼊成功
select * from uk_test;
+-----+---------+---------------------+---------------------+
| id  | ip      | gmt_create          | gmt_modify          |
+-----+---------+---------------------+---------------------+
| 106 | 1.1.1.1 | 2020-11-17 14:43:43 | 2020-11-17 14:43:43 |
+-----+---------+---------------------+---------------------+
两条uk⼀样的数据插⼊都失败了
case 2.⼀次插⼊的多条数据中,部分uk重复:
insert into uk_test(id,ip,gmt_create,gmt_modify) values(null, "1.1.1.2",now(),now()),(null,"1.1.1.3",now(),now()),(null,"1.1.1.3",now(),now()); ERROR 1062 (23000): Duplicate entry '1.1.1.3' for key 'uniq'
//三条都插⼊失败
select * from uk_test;
+-----+---------+---------------------+---------------------+
| id  | ip      | gmt_create          | gmt_modify          |
+-----+---------+---------------------+---------------------+
| 106 | 1.1.1.1 | 2020-11-17 14:43:43 | 2020-11-17 14:43:43 |
+-----+---------+---------------------+---------------------+
1 row in set (0.01 sec)
结果是插⼊全部失败了
case 3.⼀次插⼊的多条数据中,存在个别数据与db中已有的记录uk冲突
insert into uk_test(id,ip,gmt_create,gmt_modify) values(null, "1.1.1.1",now(),now()),(null,"1.1.1.2",now(),now()),(null,"1.1.1.3",now(),now()); ERROR 1062 (23000): Duplicate entry '1.1.1.1' for key 'uniq'
//修改数据的顺序,把符合条件的放在前⾯,依然失败
insert into uk_test(id,ip,gmt_create,gmt_modify) values(null, "1.1.1.3",now(),now()),(null,"1.1.1.2",now(),now()),(null,"1.1.1.1",now(),now()); ERROR 1062 (23000): Duplicate entry '1.1.1.1' for key 'uniq'
select * from uk_test;
+-----+---------+---------------------+---------------------+
| id  | ip      | gmt_create          | gmt_modify          |
mysql下载失败怎么办+-----+---------+---------------------+---------------------+
| 106 | 1.1.1.1 | 2020-11-17 14:43:43 | 2020-11-17 14:43:43 |
+-----+---------+---------------------+---------------------+
1 row in set (0.00 sec)
结果依然是失败
结论
mysql批量插⼊是原⼦操作,类似于默认开启了事务

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。