和C#中处理异常的方法很相像,mysql也有它自己处理异常的方法,本文列出了mysql处理实例的代码,通过代码我们来了解mysql数据库处理异常的原理和方法。
具体的实例代码如下:
- 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=_count+1;
- end if;
- set _row_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操作,即继续执行后面的语句。
而且在执行可能出错的语句的时候我们用事务语句:START TRANSACTION; …… COMMIT; 可以保证完整性。
DELIMITER $$
DROP PROCEDURE IF EXISTS `vm`.`sp_DelItem`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_DelItem`(IN nType int,IN nLsh int,IN nChanNo int,OUT nRetNum int)
BEGIN
declare _err int default 0;
declare nChanNum int;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION,SQLWARNING,NOT FOUND set _err=1;
set nRetNum = 0;
START TRANSACTION;
set nChanNum = 0;
if nType = 0 then
delete from USERRIGHT where USERLSH in (select LSH from USR where REGIONALISMLSH=nLsh);
delete from USR where REGIONALISMLSH = nLsh;
delete from REGIONALISM where LSH = nLsh;
end if;
if (nType = 1) then
delete from MEDIASRV where LSH = nLsh;
end if;
if (nType = 2) then
delete from CHANNEL where NETDVRLSH = nLsh;
delete from USERRIGHT where NETDVRLSH = nLsh;
delete from NETDVR where LSH =nLsh;
end if;
if (nType = 3) then
delete from USERRIGHT where CHANNO = nChanNo and NETDVRLSH = nLsh;
update NETDVR set CHANNUM = CHANNUM - 1 where LSH = nLsh;
delete from CHANNEL where CHANNO = nChanNo and NETDVRLSH = nLsh;
end if;
if (nType = 4) then
delete from USERRIGHT where USERLSH = nLsh;
delete from USR where LSH = nLsh;
end if;
COMMIT;
if _err=1 then
set nRetNum = 1;
Rollback;
end if;
select nRetNum;
END$$
DELIMITER ;