Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

วิธีเขียน Handler ใน Stored Procedure โยนข้อความผิดพลาดและออกจากการดำเนินการ


ตามที่ทราบว่าเมื่อเกิดข้อยกเว้นใน MySQL Stored Procedure การจัดการข้อยกเว้นโดยการโยนข้อความผิดพลาดที่เหมาะสมนั้นสำคัญมาก เพราะหากเราไม่จัดการข้อยกเว้น จะมีโอกาสที่แอปพลิเคชันจะล้มเหลวด้วยข้อยกเว้นนั้นใน Stored Procedure MySQL มี Handler ที่โยนข้อความผิดพลาดและออกจากการดำเนินการ เพื่อสาธิต เราใช้ตัวอย่างต่อไปนี้ ซึ่งเราพยายามแทรกค่าซ้ำในคอลัมน์ Primary Key

ตัวอย่าง

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 มันจะออกจากการดำเนินการ ไม่ให้ชุดผลลัพธ์ของคำสั่งใน Procedure 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)