如何在存储过程中编写 MySQL 处理程序,以便抛出错误消息并退出执行?


众所周知,每当 MySQL 存储过程中发生异常时,通过抛出正确的错误消息来处理它非常重要,因为如果不处理异常,存储过程中的某个异常可能会导致应用程序失败。MySQL 提供了一个处理程序,该处理程序会抛出错误消息并退出执行。为了演示这一点,我们使用以下示例,其中我们尝试在主键列中插入重复值。

示例

mysql> Delimiter //
mysql> Create Procedure Insert_Studentdetails3(S_Studentid INT, S_StudentName Varchar(20), S_Address Varchar(20))
    -> BEGIN
    -> DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'Got an error';
    -> INSERT INTO Student_detail
    -> (Studentid, StudentName, Address)
    -> Values(S_Studentid,S_StudentName,S_Address);
    -> Select * from Student_detail;
    -> END //
Query OK, 0 rows affected (0.00 sec)

mysql> Delimiter ;
mysql> CALL Insert_Studentdetails3(105, 'Mohan', 'Chandigarh');
+-----------+-------------+------------+
| Studentid | StudentName | address    |
+-----------+-------------+------------+
|       100 | Gaurav      | Delhi      |
|       101 | Raman       | Shimla     |
|       103 | Rahul       | Jaipur     |
|       104 | Ram         | Chandigarh |
|       105 | Mohan       | Chandigarh |
+-----------+-------------+------------+
5 rows in set (0.04 sec)
Query OK, 0 rows affected (0.06 sec)

现在,如果我们尝试添加列“studentid”的任何重复值,它将退出执行,它不会给出存储过程中编写的查询“select * from student_detail”的结果集,而只会给出错误消息“got an error”。

mysql> CALL Insert_Studentdetails3(105, 'Sohan', 'Bhopal');
+--------------+
| Got an error |
+--------------+
| Got an error |
+--------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

更新于:2020年6月22日

543 次浏览

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.