MySQL Error Handling in Stored Procedures 2
Summary: this tutorial shows you how to use MySQL handler to handle exceptions or errors encountered in stored procedures.
When an error occurs inside a stored procedure, it is important to handle it appropriately, such as continuing or exiting the current code block’s execution, and issuing a meaningful error message.
MySQL provides an easy way to define handlers that handle from general conditions such as warnings or exceptions to specific conditions e.g., specific error codes.
Declaring a handler
To declare a handler, you use the DECLARE HANDLER statement as follows:
|
1
|
DECLARE action HANDLER FOR condition_value statement;
|
If a condition whose value matches the condition_value , MySQL will execute the statementand continue or exit the current code block based on the action .
The action accepts one of the following values:
CONTINUE: the execution of the enclosing code block (BEGIN…END) continues.EXIT: the execution of the enclosing code block, where the handler is declared, terminates.
The condition_value specifies a particular condition or a class of conditions that activates the handler. The condition_value accepts one of the following values:
- A MySQL error code.
- A standard
SQLSTATEvalue. Or it can be anSQLWARNING,NOTFOUNDorSQLEXCEPTIONcondition, which is shorthand for the class ofSQLSTATEvalues. TheNOTFOUNDcondition is used for a cursororSELECT INTO variable_liststatement. - A named condition associated with either a MySQL error code or
SQLSTATEvalue.
The statement could be a simple statement or a compound statement enclosing by the BEGINand END keywords.
MySQL error handling examples
Let’s look into several examples of declaring handlers.
The following handler means that if an error occurs, set the value of the has_error variable to 1 and continue the execution.
|
1
|
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET has_error = 1;
|
The following is another handler which means that in case any error occurs, rollback the previous operation, issue an error message, and exit the current code block. If you declare it inside theBEGIN END block of a stored procedure, it will terminate stored procedure immediately.
|
1
2
3
4
5
|
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SELECT 'An error has occurred, operation rollbacked and the stored procedure was terminated';
END;
|
The following handler means that if there are no more rows to fetch, in case of a cursoror SELECT INTOstatement, set the value of the no_row_found variable to 1 and continue execution.
|
1
|
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_row_found = 1;
|
The following handler means that if a duplicate key error occurs, MySQL error 1062 is issued. It issues an error message and continues execution.
|
1
2
|
DECLARE CONTINUE HANDLER FOR 1062
SELECT 'Error, duplicate key occurred';
|
MySQL handler example in stored procedures
First, we create a new table named article_tags for the demonstration:
|
1
2
3
4
5
|
CREATE TABLE article_tags(
article_id INT,
tag_id INT,
PRIMARY KEY(article_id,tag_id)
);
|
The article_tags table stores the relationships between articles and tags. Each article may have many tags and vice versa. For the sake of simplicity, we don’t create articles and tagstables, as well as the foreign keys in the article_tags table.
Next, we create a stored procedure that inserts article id and tag id into the article_tags table:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
DELIMITER $$
CREATE PROCEDURE insert_article_tags(IN article_id INT, IN tag_id INT)
BEGIN
DECLARE CONTINUE HANDLER FOR 1062
SELECT CONCAT('duplicate keys (',article_id,',',tag_id,') found') AS msg;
-- insert a new record into article_tags
INSERT INTO article_tags(article_id,tag_id)
VALUES(article_id,tag_id);
-- return tag count for the article
SELECT COUNT(*) FROM article_tags;
END
|
Then, we add tag id 1, 2 and 3 for the article 1 by calling the insert_article_tags stored procedure as follows:
|
1
2
3
|
CALL insert_article_tags(1,1);
CALL insert_article_tags(1,2);
CALL insert_article_tags(1,3);
|
After that, we try to insert a duplicate key to check if the handler is really invoked.
|
1
|
CALL insert_article_tags(1,3);
|
We got an error message. However, because we declared the handler as a CONTINUE handler, the stored procedure continued the execution. As the result, we got the tag count for the article as well.

If we change the CONTINUE in the handler declaration to EXIT , we will get an error message only.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
DELIMITER $$
CREATE PROCEDURE insert_article_tags_2(IN article_id INT, IN tag_id INT)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
SELECT 'SQLException invoked';
DECLARE EXIT HANDLER FOR 1062
SELECT 'MySQL error code 1062 invoked';
DECLARE EXIT HANDLER FOR SQLSTATE '23000'
SELECT 'SQLSTATE 23000 invoked';
-- insert a new record into article_tags
INSERT INTO article_tags(article_id,tag_id)
VALUES(article_id,tag_id);
-- return tag count for the article
SELECT COUNT(*) FROM article_tags;
END
|
Finally, we can try to add a duplicate key to see the effect.
|
1
|
CALL insert_article_tags_2(1,3);
|
MySQL handler precedence
In case there are multiple handlers that are eligible for handling an error, MySQL will call the most specific handler to handle the error first.
An error always maps to one MySQL error code because in MySQL it is the most specific. AnSQLSTATE may map to many MySQL error codes therefore it is less specific. An SQLEXCPETIONor an SQLWARNING is the shorthand for a class of SQLSTATES values so it is the most generic.
Based on the handler precedence’s rules, MySQL error code handler, SQLSTATE handler andSQLEXCEPTION takes the first, second and third precedence.
Suppose we declare three handlers in the insert_article_tags_3 stored procedure as follows:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
DELIMITER $$
CREATE PROCEDURE insert_article_tags_3(IN article_id INT, IN tag_id INT)
BEGIN
DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered';
DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered';
DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000';
-- insert a new record into article_tags
INSERT INTO article_tags(article_id,tag_id)
VALUES(article_id,tag_id);
-- return tag count for the article
SELECT COUNT(*) FROM article_tags;
END
|
We try to insert a duplicate key into the article_tags table by calling the stored procedure:
|
1
|
CALL insert_article_tags_3(1,3);
|
As you see the MySQL error code handler is called.

Using named error condition
Let’s start with an error handler declaration.
|
1
2
|
DECLARE EXIT HANDLER FOR 1051 SELECT 'Please create table abc first';
SELECT * FROM abc;
|
What does the number 1051 really mean? Imagine you have a big stored procedure polluted with those numbers all over places; it will become a nightmare to maintain the code.
Fortunately, MySQL provides us with the DECLARE CONDITION statement that declares a named error condition, which associates with a condition.
The syntax of the DECLARE CONDITION statement is as follows:
|
1
|
DECLARE condition_name CONDITION FOR condition_value;
|
The condition_value can be a MySQL error code such as 1015 or a SQLSTATE value. Thecondition_value is represented by the condition_name .
After declaration, we can refer to condition_name instead of condition_value .
So we can rewrite the code above as follows:
|
1
2
3
|
DECLARE table_not_found CONDITION for 1051;
DECLARE EXIT HANDLER FOR table_not_found SELECT 'Please create table abc first';
SELECT * FROM abc;
|
This code is obviously more readable than the previous one.
Notice that the condition declaration must appear before handler or cursor declarations.
MySQL Error Handling in Stored Procedures 2的更多相关文章
- MySQL Error Handling in Stored Procedures
http://www.mysqltutorial.org/mysql-error-handling-in-stored-procedures/ mysql存储过程中的异常处理 定义异常捕获类型及处 ...
- MySQL Error Handling in Stored Procedures---转载
This tutorial shows you how to use MySQL handler to handle exceptions or errors encountered in store ...
- mysql Error Handling and Raising in Stored Procedures
MySQL的存储过程错误捕获方式和Oracle的有很大的不同. MySQL中可以使用DECLARE关键字来定义处理程序.其基本语法如下: DECLARE handler_type HANDLER FO ...
- An Introduction to Stored Procedures in MySQL 5
https://code.tutsplus.com/articles/an-introduction-to-stored-procedures-in-mysql-5--net-17843 MySQL ...
- Home / Python MySQL Tutorial / Calling MySQL Stored Procedures in Python Calling MySQL Stored Procedures in Python
f you are not familiar with MySQL stored procedures or want to review it as a refresher, you can fol ...
- Cursors in MySQL Stored Procedures
https://www.sitepoint.com/cursors-mysql-stored-procedures/ After my previous article on Stored Proce ...
- [MySQL] Stored Procedures 【转载】
Stored routines (procedures and functions) can be particularly useful in certain situations: When mu ...
- MySql Error: Can't update table in stored function/trigger
MySql Error: Can't update table in stored function/trigger because it is already used by statement w ...
- Good Practices to Write Stored Procedures in SQL Server
Reference to: http://www.c-sharpcorner.com/UploadFile/skumaar_mca/good-practices-to-write-the-stored ...
随机推荐
- Redis学习笔记~Redis主从服务器,读写分离
回到目录 Redis这个Nosql的存储系统一般会被部署到linux系统中,我们可以把它当成是一个数据服务器,对于并发理大时,我们会使用多台服务器充当Redis服务器,这时,各个Redis之间也是分布 ...
- python多线程网络编程
背景 使用过flask框架后,我对request这个全局实例非常感兴趣.它在客户端发起请求后会保存着所有的客户端数据,例如用户上传的表单或者文件等.那么在很多客户端发起请求时,服务器是怎么去区分不同的 ...
- iOS-----用LLDB调试,让移动开发更简单(二)
image lookup –address 当我们有一个地址,想查找这个地址具体对应的文件位置,可以使用image lookup --address,简写为image lookup -a e.g: 当 ...
- IBM appscan 9.0破解版分享
简介:IBM AppScan该产品是一个领先的 Web 应用安全测试工具,曾以 Watchfire AppScan 的名称享誉业界.Rational AppScan 可自动化 Web 应用的安全漏洞评 ...
- 新手入门:史上最全Web端即时通讯技术原理详解
前言 有关IM(InstantMessaging)聊天应用(如:微信,QQ).消息推送技术(如:现今移动端APP标配的消息推送模块)等即时通讯应用场景下,大多数都是桌面应用程序或者native应用较为 ...
- 记一次裸迁 MySQL 经历
记一次裸迁MySQL经历 前言:博主企业有一台企业阿里云机器,因为安装了云锁,造成服务器动不动就给我所死服务器.(就是那种 chattr +i /bin/bash ,分分钟日死狗 )趁着周末,Boos ...
- 加载的过程中图片变形了? --教你自定义自动适配图片宽高比的RatioLayout
很多同行在开发中可能会遇到这样的问题,就是在加载图片的时候会出现图片变形的问题.其实这很可能就是你的图片宽高比和图片所在容器的宽高比不匹配造成的.比如说图片的宽为200,高为100.宽高比就是2,那么 ...
- Linux下程序包管理工具RPM
实验环境: CentOS release 6.6 (Final) 一台 IP地址:172.16.249.230 RPM 是 Red Hat Package Manager 的缩写,本意是Red Ha ...
- 基于Metronic的Bootstrap开发框架经验总结(3)--下拉列表Select2插件的使用
在上篇<基于Metronic的Bootstrap开发框架经验总结(2)--列表分页处理和插件JSTree的使用>介绍了数据的分页处理,使用了Bootstrap Paginator插件,另外 ...
- dpi 、 dip 、分辨率、屏幕尺寸、px、density 关系以及换算
一.基本概念 dip : Density independent pixels ,设备无关像素. dp :就是dip px : 像素 dpi :d ...
