mysql存储过程事务和捕获异常信息

注:以下脚本均是在公司的mysql环境上跑的,版本号是5.6.16-log
其他版本可根据关键字 get diagnostics 自行百度。

drop table if exists simon_task;
drop table if exists simon_log;
create table simon_task(task varchar(200));-- 业务表
CREATE TABLE simon_log (test001 varchar(2000));-- 日志表


-- 失败测试
drop procedure if exists print_exception_msg;
create procedure print_exception_msg()
begin
declare v_commit int default 2; -- 定义事务用,1为正常,-10为失败
declare msg text;-- 记录错误信息
-- 异常的时候msg捕获报错信息
declare continue handler for sqlexception 
begin get diagnostics condition 1  msg = message_text;set v_commit = -10; end ;
    
start transaction;-- 设置事务


-- 业务表相关
insert into simon_task values ('111111111');
insert into staff (sda) values('111111111');


if v_commit = -10 then   
ROLLBACK;
-- 记录报错信息到日志
insert into simon_log values (msg);
end if ;


end;


call print_exception_msg;
-- 预期:insert into staff (sda) values('as'); 这句是错误的,所以simon_task表和staff表都不应该insert成功,并且simon_log记录报错原因
select * from simon_task ;
select * from simon_log ;
-- 实际:同预期。




-- 成功测试
drop procedure if exists print_exception_msg2;
create procedure print_exception_msg2()
begin
declare v_commit int default 2; -- 定义事务用,1为正常,-10为失败
declare msg text;-- 记录错误信息
-- 异常的时候msg捕获报错信息
declare continue handler for sqlexception 
begin get diagnostics condition 1  msg = message_text;set v_commit = -10; end ;
    
start transaction;-- 设置事务


-- 业务相关语法
insert into simon_task values ('2222222222');
insert into simon_task values ('3333333333');

if v_commit = -10 then   
ROLLBACK;
insert into simon_log values (msg);
end if ;


end;


call print_exception_msg2;
-- 预期:simon_task表新增两条记录,simon_log表没有新增的记录


select * from simon_task ;
select * from simon_log;
-- 实际:同预期。
View Code

 

转载于:https://www.cnblogs.com/Simonsun002/p/9788353.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值