您现在的位置是:网站首页> 编程资料编程资料
mysql存储中使用while批量插入数据(批量提交和单个提交的区别)_Mysql_
2023-05-26
361人已围观
简介 mysql存储中使用while批量插入数据(批量提交和单个提交的区别)_Mysql_
批量提交
while 语句写法:
while '条件' do 循环体语句; end while;
完整写法
drop procedure if exists test_insert; delimiter $$ create procedure test_insert(n int) begin declare v int default 0; set AUTOCOMMIT = 0; while v < n do insert into test(second_key, text, field_4,status, create_date) values ((v*10), concat('t',v), substring(md5(rand()), 1, 10), 'good', adddate('1970-01-01', rand(v) * 10000)); set v = v + 1; end while; set AUTOCOMMIT = 1; end$$ delimiter ;查看、删除存储过程:
mysql> show procedure status like 'test_insert'; mysql> show create procedure test_insert\G; mysql> drop procedure if exists test_insert;
创建表
CREATE TABLE test ( id INT NOT NULL AUTO_INCREMENT, second_key INT, text VARCHAR(20), field_4 VARCHAR(20), status VARCHAR(10), create_date date, PRIMARY KEY (id), KEY idx_second_key (second_key) ) Engine=InnoDB CHARSET=utf8;
插入100万条数据
mysql> call test_insert(1000000); Query OK, 0 rows affected (31.86 sec)
单个提交
完整写法
drop procedure if exists test_insert; delimiter $$ create procedure test_insert(n int) begin declare v int default 0; while v < n do insert into test(second_key, text, field_4,status, create_date) values ((v*10), concat('t',v), substring(md5(rand()), 1, 10), 'good', adddate('1970-01-01', rand(v) * 10000)); set v = v + 1; end while; end$$ delimiter ;插入1万条数据
mysql> call test_insert(10000); Query OK, 1 row affected (1 min 8.52 sec)
打开另一个窗口查看
mysql> select count(*) from test.test; +----------+ | count(*) | +----------+ | 1428 | +----------+ 1 row in set (0.00 sec) mysql> select count(*) from test.test; +----------+ | count(*) | +----------+ | 1598 | +----------+ 1 row in set (0.00 sec) mysql> select count(*) from test.test; +----------+ | count(*) | +----------+ | 1721 | +----------+ 1 row in set (0.00 sec) mysql> select count(*) from test.test; +----------+ | count(*) | +----------+ | 1983 | +----------+ 1 row in set (0.00 sec)
结论
批量提交100万条数据用了30秒,单个提交1万条数据用了1分钟,对比发现,批量提交的效率远大于单个提交的效率
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
相关内容
- MySQL中出现lock wait timeout exceeded问题及解决_Mysql_
- MySQL8.0连接协议及3306、33060、33062端口的作用解析_Mysql_
- MySQL中隔离级别RC与RR的区别及说明_Mysql_
- MySQL删除表数据与MySQL清空表命令的3种方法浅析_Mysql_
- mysql严格模式Strict Mode详细说明_Mysql_
- mysql递归函数with recursive的用法举例_Mysql_
- MySQL视图的概念、创建、查看、删除和修改详解_Mysql_
- MySQL窗口函数OVER()用法及说明_Mysql_
- 适合新手的mysql日期类型转换实例教程_Mysql_
- 一文带你玩转MySQL获取时间和格式转换各类操作方法详解_Mysql_
