MySQL資料庫的異常處理

來源:互聯網
上載者:User

對於MySQL的異常處理,本人不常用。不過我覺得還是有寫下來的必要。

標準格式

DECLARE handler_type HANDLER FOR condition_value[,...] statement
handler_type:
CONTINUE
| EXIT
| UNDO --暫時不支援
condition_value:
SQLSTATE [VALUE] sqlstate_value
| condition_name
| SQLWARNING
| NOT FOUND
| SQLEXCEPTION
| mysql_error_code

condition_value細節

1、MySQL ERROR CODE 列表

如果需要查看更多的錯誤清單可以直接到MySQL安裝路徑下。

比如我的/usr/local/mysql/share/mysql/errmsg.txt

說明:SQLSTATE [VALUE] sqlstate_value這種格式是專門為ANSI SQL 和 ODBC以及其他的標準.

並不是所有的MySQL ERROR CODE 都映射到SQLSTATE。

2、假如不需要插入ERROR CODE,可以用速記條件來代替

SQLWARNING 代表所有以01開頭的錯誤碼

NOT FOUND 代表所有以02開頭的錯誤碼,當然也可以代表一個遊標到達資料集的末尾。

SQLEXCEPTION 代表除了SQLWARNING和NOT FOUND 的所有錯誤碼。

3、具體樣本:

create TABLE t (s1 int,primary key (s1));
mysql> use t_girl
Database changed
mysql> create TABLE t (s1 int,primary key (s1));
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql>
mysql> DELIMITER ||
mysql> create PROCEDURE handlerdemo ()
-> BEGIN
-> DECLARE EXIT HANDLER FOR SQLSTATE ’23000’ BEGIN END; -- 遇到重複索引值就退出
-> SET @x = 1;
-> insert INTO t VALUES (1);
-> SET @x = 2;
-> insert INTO t VALUES (1);
-> SET @x = 3;
-> END||
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> call handlerdemo();
Query OK, 0 rows affected (0.00 sec)
mysql> select @x;
+------+
| @x |
+------+
| 2 |
+------+
1 row in set (0.00 sec)
mysql> call handlerdemo();
Query OK, 0 rows affected (0.00 sec)
mysql> select @x;
+------+
| @x |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
mysql>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.