如何在儲存過程中編寫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日

456 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.