2020.12.14:通过autocommit对原本的存储过程进行了优化,由原本的每insert一次就commit一次,改为一次性commit所有insert,mysql对此执行效率进行了优化,对照测试数据详见:https://blog.lakesideknight.com/archives/175#性能对照测试

  • autocommit:当开启自动提交之后,你的每一次sql执行都会立马作为一个事务提交。如果关闭自动提交,你执行的sql都不会生效,除非手动执行commit;

  • autocommit是属于连接的参数,不是数据库参数;

  • autocommit只在Innodb引擎下有效。

优化前

delimiter //
DROP PROCEDURE IF EXISTS proc_batch_insert;
CREATE PROCEDURE proc_batch_insert()
BEGIN
DECLARE i INT DEFAULT 1;
WHILE i <= 100 DO
 INSERT INTO tbl_school (name) VALUES ('xxx');
SET i=i+1;
END WHILE;
END //
call proc_batch_insert();
DROP PROCEDURE IF EXISTS proc_batch_insert;

优化后

delimiter //
DROP PROCEDURE IF EXISTS proc_batch_insert;
CREATE PROCEDURE proc_batch_insert()
BEGIN
DECLARE i INT DEFAULT 1;
SET autocommit=0;
WHILE i <= 100000 DO
 INSERT INTO tbl_school (name) VALUES ('xxx');
SET i=i+1;
END WHILE;
COMMIT;
END //
call proc_batch_insert();
DROP PROCEDURE IF EXISTS proc_batch_insert;