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

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

我们知道,每当MySQL存储过程中发生异常时,通过抛出适当的错误消息处理异常非常重要,否则在存储过程中使用某些异常可能导致应用程序失败。 MySQL提供了一个处理程序,该处理程序会抛出错误消息并继续执行。为了演示它,我们使用以下示例,其中我们尝试在主键列中插入重复值。

示例

mysql> DELIMITER //
mysql> Create Procedure Insert_Studentdetails(S_Studentid INT, S_StudentName Varchar(20), S_Address Varchar(20))
   -> BEGIN
   -> DECLARE CONTINUE 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.19 sec)

调用上述过程时,如果我们尝试在“studentid”列中输入重复值,它将抛出“got an error”错误消息并继续执行。

mysql> Delimiter ;
mysql> CALL Insert_Studentdetails(100, 'Gaurav', 'Delhi');
+-----------+-------------+---------+
| Studentid | StudentName | address |
+-----------+-------------+---------+
| 100       | Gaurav      | Delhi   |
+-----------+-------------+---------+
1 row in set (0.11 sec)

Query OK, 0 rows affected (0.12 sec)

mysql> CALL Insert_Studentdetails(101, 'Raman', 'Shimla');
+-----------+-------------+---------+
| Studentid | StudentName | address |
+-----------+-------------+---------+
|       100 | Gaurav      | Delhi   |
|       101 | Raman       | Shimla  |
+-----------+-------------+---------+
2 rows in set (0.06 sec)

Query OK, 0 rows affected (0.12 sec)

mysql> CALL Insert_Studentdetails(101, 'Rahul', 'Jaipur');
+--------------+
| Got an error |
+--------------+
| Got an error |
+--------------+
1 row in set (0.03 sec)

+-----------+-------------+---------+
| Studentid | StudentName | address |
+-----------+-------------+---------+
|       100 | Gaurav      | Delhi   |
|       101 | Raman       | Shimla  |
+-----------+-------------+---------+
2 rows in set (0.04 sec)

Query OK, 0 rows affected (0.05 sec)

mysql> CALL Insert_Studentdetails(103, 'Rahul', 'Jaipur');
+-----------+-------------+---------+
| Studentid | StudentName | address |
+-----------+-------------+---------+
|      100  | Gaurav      | Delhi   |
|      101  | Raman       | Shimla  |
|      103  | Rahul       | Jaipur  |
+-----------+-------------+---------+
3 rows in set (0.08 sec)
Query OK, 0 rows affected (0.10 sec)

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程