zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    slf4j+log4j的使用
    <context:component-scan>详解
    Spring装配Bean---使用xml配置
    Spring应用上下文中Bean的生命周期
    bootstrap table 复选框选中后,翻页之后保留先前选中数据
    前后端分离的时代,如何解决前后端接口联调问题?
    利用vue-cli搭建vue项目
    vue之注册自定义的全局js函数
    小程序之图片上传
    微信小程序-蓝牙连接
  • 原文地址:https://www.cnblogs.com/Simonsun002/p/9788353.html
Copyright © 2011-2022 走看看