Home >Database >Mysql Tutorial >MySQL存储过程中一些基本的异常处理教程_MySQL

MySQL存储过程中一些基本的异常处理教程_MySQL

WBOY
WBOYOriginal
2016-05-27 13:46:011246browse

有时候,不希望存储过程抛出错误中止执行,而是希望返回一个错误码。 Mysql 支持异常处理,通过定义 CONTINUE/EXIT 异常处理的 HANDLER 来捕获 SQLWARNING/NOT FOUND/SQLEXCEPTION (警告 / 无数据 / 其他异常)。其中, FOR 后面可以改为 SQLWARNING, NOT FOUND, SQLEXCEPTION 来指示所有异常都处理,相当于 oracle 中的 others 。例如,当不进行异常处理时,以下代码将直接抛出一个 ERROR 1062 (23000) 错误:

CREATE PROCEDURE test_proc_ins1(
     IN i_id INT,
     IN i_name VARCHAR(100)
)
BEGIN
     INSERT INTO testproc VALUES (i_id,i_name);
     INSERT INTO testproc VALUES (i_id,i_name);
END;

经过异常处理后,可以避免抛出错误,而是定义一个返回参数 o_ret 赋予特殊值来表示失败,这样,比如在 java 代码中,可以通过获取返回值而不是捕获异常的方式来处理业务逻辑。例如将返回值设置为 -1:

CREATE PROCEDURE test_proc_ins1(
     IN i_id INT,
     IN i_name VARCHAR(100),
     OUT o_ret INT)
BEGIN
     DECLARE EXIT HANDLER FOR SQLSTATE '23000' set o_ret = -1;
-- 也可以这样使用:
-- DECLARE EXIT HANDLER FOR SQLWARNING,NOT FOUND,SQLEXCEPTION set o_ret=-1;
     INSERT INTO testproc VALUES (i_id,i_name);
     INSERT INTO testproc VALUES (i_id,i_name);
     set o_ret = 1;
END;

当然,对于特定的SQL语句,也可以指定比如主键冲突,就rollback;

DECLARE exit HANDLER FOR SQLSTATE '23000'

delimiter //

CREATE PROCEDURE TEST()
BEGIN
DECLARE exit HANDLER FOR SQLEXCEPTION,SQLWARNING,NOT FOUND
begin
rollback;
insert into bb values('error');
end;
START TRANSACTION;
INSERT INTO aa VALUES (1);
INSERT INTO aa VALUES (2);
COMMIT;
END;
//

CALL test()//

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn