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
  • 相关阅读:
    VLC播放器web插件接口(Part1)
    视频监控/存储系统设计要点
    CVR并发写入测试
    Darwin Streaming Server性能测试报告
    用Red5搭建支持WEB播放的实时监控视频
    RTSP协议-中文定义
    网格最短路径算法(Dijkstra & Fast Marching)
    三维网格精简算法(Quadric Error Metrics)附源码
    三维网格细分算法(Catmull-Clark subdivision & Loop subdivision)附源码
    网格测地线算法(Geodesics in Heat)附源码
  • 原文地址:https://www.cnblogs.com/Simonsun002/p/9788353.html
Copyright © 2011-2022 走看看