mysql自定义异常

在存储过程中,执行多个sql,如果某个sql执行出现异常如何处理 ?

1.使用自定义异常

declare xxx1 handler for xxx2 执行sql

xxx1可以使用几个值,continue , exit ,undo 

xxx2是sqlstate ,sqlwarning,notfound,sqlexception

2.重点介绍continue ,exit

continue,当sql遇到错误时,sql执行往下zhix执行;

exit遇到错误,整个存储过程ting停止,不再往下执行,一般情况下不用exit,因为写存储过程时,我们会使用事务,开启事务后,当出错时,使用rollbackhuig回滚就可以了。

3.例子

BEGIN
	#Routine body goes here...
   declare err int default 0;
   declare  continue handler  for sqlexception set err =1;

   start transaction ;

    insert into user_balance(user_id,user_money)values(3,'q');
    insert into user_balance(user_id,user_money)values(4,1);

   
    if err =1  then 
        select '出错了' 
        ROLLBACK;
      else 
        commit;
    end if;

END

上面两条sql都是往user_balance表插入数据,其中第一条会出错,当出错时,handler句柄会执行set err = 1,

同时因为shiy使用了continue,因此sql接着往下zhix执行。

最后pand判断,err = 1,执行回滚,否则commit提交事务。

猜你喜欢

转载自blog.csdn.net/a453220542/article/details/81194297