带你轻松接触MySQL数据库的异常处理
ER=`root`@`localhost` PROCEDURE `handlerdemo`()
-> BEGIN -> DECLARE CONTINUE HANDLER FOR SQLSTATE ''23000'' BEGIN END; -> SET @x = 1; -> INSERT INTO t VALUES (1); -> SET @x = 2; -> INSERT INTO t VALUES (1); -> SET @x = 3; -> END$ Query OK, 0 rows affected (0.01 sec)
mysql> DELIMITER ; mysql> call handlerdemo(); Query OK, 0 rows affected (0.00 sec)
mysql> select @x; +------+
| @x | +------+
| 3 | +------+
1 row in set (0.00 sec)
mysql> call handlerdemo(); Query OK, 0 rows affected (0.00 sec)
mysql> select @x; +------+
| @x | +------+
| 3 | +------+
1 row in set (0.00 sec)
mysql>
我们可以看到,始终执行到最后。 当然,上面的SQLSTATE ''23000''可以替换为1062。
警告:
mysql> alter table t add s2 int not null; Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0
这个列没有默认值,插入的时候会出现警告或者1364错误提示。 mysql> DELIMITER $ mysql> DROP PROCEDURE IF EXISTS `t_girl`.`handlerdemo`$ Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> CREATE DEFINER=`root`@`localhost` PROCEDURE `handlerdemo`() -> BEGIN -> DECLARE CONTINUE HANDLER FOR 1062 BEGIN END; -> DECLARE CONTINUE HANDLER FOR SQLWARNING -> BEGIN -> update t set s2 = 2; -> END; -> DECLARE CONTINUE HANDLER FOR 1364 -> BEGIN -> INSERT INTO t(s1,s2) VALUES (1,3); -> END; -> SET @x = 1; -> INSERT INTO t(s1) VALUES (1); -> SET @x = 2; -> INSERT INTO t(s1) VALUES (1); -> SET @x = 3; -> END$ Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> call handlerdemo(); Query OK, 0 rows affected (0.00 sec)
mysql> select * from t; +----+----+
| s1 | s2 | +----+----+
| 1 | 3 | +----+----+
1 row in set (0.00 sec) 遇到错误时,插入的新记录。
mysql> select @x; +------+
| @x | +------+
| 3 | +------+
1 row in set (0.00 sec) |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |