染卷不卷'blog

12年站长,AI实践中。互联网 IT行业,工作见闻、技术教程全分享。

学习资料 / 服务器运维

mysql事务&批量插入

参考教程MySQL存储过程 事务transaction

操作mysql数据库时如果有大量sql操作需要控制要么一起成功,要么一起失败的时候,就需要用到事务操作,一旦使用事务在捕获到失败后就需要 rollback 回滚操作,如果不进行错误检测,可能会导致部分成功(因为没做报错判断就直接commit提交了)

一次性批量插入200条记录到数据库,并记录下每条插入记录的id

delimiter //
drop procedure if exists test_insert;
create procedure test_insert()
 
BEGIN
DECLARE i int DEFAULT 1;
DECLARE insert_times int DEFAULT 200;
DECLARE insert_id int DEFAULT 0;
 
DECLARE t_error INTEGER DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET t_error=1;
 
start transaction; #--整个存储过程指定为一个事务
 
 
WHILE i < insert_times DO
 
insert into test(record)values(concat('这是插入的第',i,'记录'));
select last_insert_id() into insert_id;#获取mysql当前连接用户最近一次插入的id
update test set remark=concat('插入id=',insert_id) where id=insert_id;
 
SET i = i + 1;
END WHILE;
 
 
IF t_error = 1 THEN
ROLLBACK;
ELSE
COMMIT;
END IF;
 
select t_error; #返回标识位的结果集;
 
 
END
//
 
call test_insert();
染卷

本站文章也会定期同步到微信公众号,可以关注下避免错过~

建站 12年 17天
微信公众号

发表评论

邮箱不会公开,带 * 为必填。