程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> 關於MYSQL數據庫 >> MySQL 錯誤處理例子[譯]

MySQL 錯誤處理例子[譯]

編輯:關於MYSQL數據庫
from http://www.devshed.com/c/a/MySQL/Error-Handling-Examples/
Error Handler Examples
Here are some examples of handler declarations:
If any error condition arises (other than a NOT FOUND ), continue execution after setting l_error=1 :
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
SET l_error=1;
If any error condition arises (other than a NOT FOUND ), exit the current block or stored program after issuing a ROLLBACK statement and issuing an error message:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SELECT 'Error occurred – terminating';
END;
If MySQL error 1062 (duplicate key value) is encountered, continue execution after executing the SELECT statement (which generates a message for the calling program):
DECLARE CONTINUE HANDER FOR 106 2
SELECT 'Duplicate key in index';
If SQLSTATE 23000 (duplicate key value) is encountered, continue execution after executing the SELECT statement (which generates a message for the calling program):
DECLARE CONTINUE HANDER FOR SQLSTATE '23000'
SELECT 'Duplicate key in index';
When a cursor fetch or SQL retrieves no values, continue execution after setting l_done=1 :
DECLARE CONTINUE HANDLER FOR NOT
FOUND
SET l_done=1;
Same as the previous example, except specified using a SQLSTATE variable rather than a named condition:
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000 '
SET l_done=1;
Same as the previous two examples, except specified using a MySQL error code variable rather than a named condition or SQLSTATE variable:
DECLARE CONTINUE HANDLER FOR 1329
SET l_done=1;

錯誤處理例子
有幾種錯誤處理的聲明形式:
§ 如果任何錯誤(不是 NOT FOUND ) , 設置 l_error 為 1 後繼續執行:
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
SET l_error=1;
§ 如果發生任何錯誤(不是 NOT FOUND), 執行 ROLLBACK和產生一條錯誤消息後退出當前塊或存儲過程。
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SELECT 'Error occurred – terminating';
END;
§ 如果 MySQL 1062錯誤 (重復的健值 )發生,執行 SELECT語句(向調用程序發一條消息)後繼續執行
DECLARE CONTINUE HANDER FOR 106 2
SELECT 'Duplicate key in index';
§ 如果 SQLSTATE 2300錯誤 (重復的健值 )發生,執行 SELECT語句(向調用程序發一條消息)後繼續執行
DECLARE CONTINUE HANDER FOR SQLSTATE '23000'
SELECT 'Duplicate key in index';
§ 當游標或者 SQL 選擇語句沒有返回值時,設置 l_done=1 後繼續執行
DECLARE CONTINUE HANDLER FOR NOT
FOUND
SET l_done=1;
§ 此例除了用 SQLSTATE 變量而不是命名條件以外,跟前一個例子一樣
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000 '
SET l_done=1;
§ 此例除了用 MySQL 的錯誤碼變量而不是命名條件或者 SQLSTATE 變量以外,跟前兩個例子一樣
DECLARE CONTINUE HANDLER FOR 1329
SET l_done=1;
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved