mysql handler 回滚,处理程序中的MySQL回滚

本文探讨了在MySQL中如何正确地使用存储过程中的异常处理机制。通过使用EXITHANDLER来捕获并处理SQL异常,确保事务能够回滚的同时,还能将详细的错误信息返回给客户端,以便进行故障排查。

I have a stored procedure where I'd like to rollback in case anything goes wrong. In order to do that I'm using a EXIT HANDLER like this:

DECLARE EXIT HANDLER FOR sqlexception

begin

ROLLBACK;

end;

But in this way, when I call this stored procedure, in case of any errors, the stored procedure succeed and I don't know what was the actual problem. I want the client (php) to log the error in order to troubleshoot it. So I modify in this way:

DECLARE EXIT HANDLER FOR sqlexception

begin

get diagnostics condition 1

@p1 = MESSAGE_TEXT;

ROLLBACK;

SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = @p1;

end;

So now the stored procedure rollback and than throw the exeption that the handler intercepted. That's cool but sometimes the MESSAGE_TEXT is more than 128 chars and in such cases I get:

Error Code: 1648. Data too long for condition item 'MESSAGE_TEXT'

Of course this solution is not acceptable:

DECLARE EXIT HANDLER FOR sqlexception

begin

get diagnostics condition 1

@p1 = MESSAGE_TEXT;

ROLLBACK;

SET @p1=SUBSTRING(@p1,1,128);

SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = @p1;

end;

Is there any way to intercept any exception, rollback and then throw the same exception to the client?

Thanks very much for your help

解决方案

As suggested by Kenney the answer is:

DECLARE EXIT HANDLER FOR sqlexception

begin

ROLLBACK;

RESIGNAL;

end;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值