如何在儲存過程中編寫MySQL處理器,使用SQLSTATE處理預設的MySQL錯誤並退出執行?


眾所周知,當MySQL儲存過程中發生異常時,透過丟擲正確的錯誤訊息來處理異常非常重要。如果不處理異常,儲存過程中的某個異常可能會導致應用程式失敗。MySQL提供了一個處理器,它使用SQLSTATE處理預設的MySQL錯誤並退出執行。為了演示這一點,我們使用以下示例,其中我們嘗試在主鍵列中插入重複值。

示例

mysql> Delimiter //
mysql> Create Procedure Insert_Studentdetails4(S_Studentid INT, S_StudentName Varchar(20), S_Address Varchar(20),OUT got_error INT)
   -> BEGIN
   -> DECLARE EXIT HANDLER FOR 1062 SET got_error=1;
   -> 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)

現在,如果我們嘗試新增列“studentid”的任何重複值,它將退出執行,不會給出儲存過程'select * from student_detail'中編寫的查詢的結果集,只會給出關於輸入重複值的預設MySQL錯誤訊息1062,並將變數got_error的值設定為1。

mysql> Delimiter ;
mysql> CALL Insert_Studentdetails4(104,'Ram','Chandigarh',@got_error);

Query OK, 0 rows affected (0.00 sec)

mysql> Select @got_error;
+------------+
| @got_error |
+------------+
|          1 |
+------------+
1 row in set (0.00 sec)

更新於:2020年2月12日

455 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.