MySql中捕获异常的方法
mySql中是否能有SQLserver的@@error变量呢,或者如c#中的try catch语法呢。
答案是肯定的,实例代码如下:
Code
DROP PROCEDURE IF EXISTS sp_call_jobs;
CREATE PROCEDURE sp_call_jobs()
NOT DETERMINISTIC
SQL SECURITY DEFINER
COMMENT ''
BEGIN
declare _row,_err,_count int default 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION,SQLWARNING,NOT FOUND set _err=1;
while _row<3 DO
START TRANSACTION;
insert into t1(cond_val)values(null);
COMMIT;
if _err=1 then
set _count=_count+1;
end if;
set _row=_row+1;
end while;
select _count;
END;
DROP PROCEDURE IF EXISTS sp_call_jobs;
CREATE PROCEDURE sp_call_jobs()
NOT DETERMINISTIC
SQL SECURITY DEFINER
COMMENT ''
BEGIN
declare _row,_err,_count int default 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION,SQLWARNING,NOT FOUND set _err=1;
while _row<3 DO
START TRANSACTION;
insert into t1(cond_val)values(null);
COMMIT;
if _err=1 then
set _count=_count+1;
end if;
set _row=_row+1;
end while;
select _count;
END;
语句:
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION,SQLWARNING,NOT FOUND set _err=1;
作用是当遇到SQLEXCEPTION,SQLWARNING,NOT FOUND 错误时,设置_err=1并执行CONTINUE操作,即继续执行后面的语句。
这就与c#中的try catch语法很像。
而且在执行可能出错的语句的时候我们用事务语句:START TRANSACTION; …… COMMIT; 可以保证完整性。
-----------------------------------------------------------------