当前位置:网站首页>Talking about custom conditions and handling errors in MySQL Foundation
Talking about custom conditions and handling errors in MySQL Foundation
2022-07-04 02:14:00 【Little pig brother】
I wrote some storage functions and stored procedures , It has been said that its debugging is difficult , But can it be carried out specifically . So in MYSQL Solve this problem by defining conditions and processes .
Defined conditions : It is the problem of defining possible statements in the process of program execution in advance
The handler : It defines how to deal with problems , And ensure that stored procedures or functions can continue to execute when encountering errors or warnings .
This can increase the ability of storing programs or functions to deal with problems , Avoid abnormal program stop .
In fact, if this is explained in language , To tell you the truth, I will be confused
# First create a table And then insert the data
CREATE TABLE test_1(
t_id INT NOT NULL,
t_name VARCHAR(10)
);
INSERT INTO test_1 VALUES (1,' Zhang San ');
INSERT INTO test_1 VALUES (1,' Li Si ');
Then create a stored procedure that will definitely report an error .
DELIMITER $
CREATE PROCEDURE test1()
BEGIN
SET @t_flag=1;
UPDATE test_1 SET t_id=NULL WHERE t_name=' Zhang San ';
SET @t_flag=2;
UPDATE test_1 SET t_id='22' WHERE t_name=' Zhang San ';
SET @t_flag=2;
END $
DELIMITER ;
Then call the storage function
CALL test1();
# This place is bound to be wrong

But at this time add some , If not sqlyog It will be more detailed if you use the command window .

Then check some @t_flag value .
select @t_flag;

This shows that the stored procedure reports an error after execution , But by defining a variable, we can see that in UPDATE An error is reported when the first statement is executed .
In fact, this is often the case when writing stored procedure debugging , Because this is very simple, it is easy to know what is wrong , But most of the time, you don't know the location when you report an error , So keep debugging the position or shield the back for step-by-step debugging .
From here, we can see another thing: conditions and handlers are not defined in stored procedures , That is, when the stored procedure is executed SQL When reporting a mistake ,MYSQL The database will throw an error , And exit the current SQL Logic , Do not execute the following statements in the stored procedure . Therefore, the understanding of definitions and handlers is a bit like customizing a JAVA Medium try-catch sentence .
Defined conditions
The defining condition is to give MYSQL Wrong name in , This helps to make the stored program code clearer . It associates an error name with the specified error condition , This name can be all defined in the process DECLARE HANDLER In language .
If you define a condition , The format is as follows :
DECLARE Wrong name CONDITION FOR Error codes or conditions
Description of error code :
Before this explanation, let's take a look at the previous error report. There are two numbers 1048 and 23000 These two are actually two different error codes :MYSQL_error_code and sqlstate_value;

- MYSQL_error_code: Is a numeric type error code . That is to say :1048
- sqlstate_value: It's a length of 5 String type of Error code for , That is to say :‘23000’
In fact, both of them represent a kind of mistake , Can be used as a condition as follows :
# Use MYSQL_error_code
DECLARE Field_NOT_Is_Null CONDITION FOR 1048;
# Use sqlstate_value
DECLARE Field_NOT_Is_Null CONDITION FOR SQLSTATE '23000';
Define handler
This is for SQL Some type of error that occurs during execution defines a special handler , When defining a handler , Use DECLARE The statement is as follows :
DECLARE Processing mode HANDLER FOR Wrong type Processing statements
There are three ways to deal with :CONTINUE,EXIT and UNDO;
- CONTINUE: Indicates that an error is encountered and will not be processed , Carry on , and JAVA Zhongfa for The keywords in the loop have similar meanings .
- EXIT: It means to quit immediately when encountering errors , It's kind of like JAVA Medium break It's about the same .
- UNDO: Indicates that the previous operation is withdrawn after a statement error . But if you have one sentence to say, you may be scolded , That's it MYSQL Currently, this operation is not supported in .
Wrong type : In fact, it is the wrong condition , It can take the following values :
- sqlstate_value: That is to say sqlstate The middle length is 5 Wrong numeric string
- MYSQL_error_code: Matching array type error code
- Wrong name : That is, in the conditional statement defined above DECLARE…CONDITION Defined error condition name .
This can be seen since the first two can be used as error conditions , Why should we prove it , In fact, the essence is to increase readability , Show some error numbers with names , It is more convenient to read stored functions or stored procedures .
- SQLWARNINT: Match all to 01 At the beginning sqlstate_value Error code .
- NOT FOUND: Match all to 02 At the beginning sqlstate_value Error code .
- SQLEXCEPTION: Match all not included in SQLWARNINT and NOT FOUND Captured in sqlstate_value Error code .
Processing statements : If one of the above conditions occurs , The corresponding processing method is adopted , And execute the specified processing language .
The statement can be set as before @t_flag The same goes through SET assignment , Then query the @t_flag Value to know the operation , You can also use BEGIN…END Written symbolic statements .
demonstration
Case study 1
DELIMITER $
CREATE PROCEDURE test2()
BEGIN
# The way 1
DECLARE Field_NOT_Is_Null CONDITION FOR 1048;
DECLARE EXIT HANDLER FOR Field_NOT_Is_Null SET @t_flag=-1;
# The way 2
#DECLARE EXIT HANDLER FOR 1048 SET @t_flag=1;
# The way 3
#DECLARE EXIT HANDLER FOR '23000' SET @t_flag=1;
# SQLEXCEPTION In order to 02 and 01 Beyond the beginning sqlstate
#DECLARE EXIT HANDLER FOR SQLEXCEPTION SET @t_flag=1;
SET @t_flag=1;
UPDATE test_1 SET t_id=NULL WHERE t_name=' Zhang San ';
SET @t_flag=2;
UPDATE test_1 SET t_id='22' WHERE t_name=' Zhang San ';
SET @t_flag=2;
END $
DELIMITER ;
And look at the results :
CALL test2();
SELECT @t_flag;

Case study 2
This effect and case 1 The same is demonstration , If there are many sentences , It can be used BEGIN…END As a module , Tell the following to execute the block after meeting this condition SQL sentence .
DELIMITER $
CREATE PROCEDURE test3()
BEGIN
DECLARE Field_NOT_Is_Null CONDITION FOR 1048;
DECLARE EXIT HANDLER FOR Field_NOT_Is_Null
BEGIN
SET @t_flag=-2; # Many other things can be written in this , But this is just a demonstration
END ; # The ending symbol in this place continues to be used ; Because the previous application $ For the new closing statement this , If you use $ Equals the end of this stored procedure , So use ;
SET @t_flag=1;
UPDATE test_1 SET t_id=NULL WHERE t_name=' Zhang San ';
SET @t_flag=2;
UPDATE test_1 SET t_id='22' WHERE t_name=' Zhang San ';
SET @t_flag=2;
END $
DELIMITER ;
Now let's look at the results
CALL test3;
SELECT @t_flag;

边栏推荐
- The difference between lambda expressions and anonymous inner classes
- Comment la transformation numérique du crédit d'information de la Chine passe - t - elle du ciel au bout des doigts?
- Data collection and summary
- Career development direction
- Day05 branch and loop (II)
- Chapter 3.4: starrocks data import - Flink connector and CDC second level data synchronization
- Huawei cloud micro certification Huawei cloud computing service practice has been stable
- Bugku Zhi, you have to stop him
- Jerry's watch listens to the message notification of the target third-party software and pushes the message to the device [article]
- Yyds dry goods inventory hand-in-hand teach you the development of Tiktok series video batch Downloader
猜你喜欢

Buuctf QR code

Should enterprises start building progressive web applications?

Introduction to graphics: graphic painting (I)

Save Private Ryan - map building + voltage dp+deque+ shortest circuit

Applet graduation project based on wechat selection voting applet graduation project opening report function reference

Libcblas appears when installing opencv import CV2 so. 3:cannot open shared object file:NO such file or directory

Override and virtual of classes in C #

中電資訊-信貸業務數字化轉型如何從星空到指尖?

Magical usage of edge browser (highly recommended by program ape and student party)

FRP intranet penetration
随机推荐
Huawei cloud micro certification Huawei cloud computing service practice has been stable
Should enterprises start building progressive web applications?
Chapter 3.4: starrocks data import - Flink connector and CDC second level data synchronization
12. Gettimeofday() and time()
Data collection and summary
Day05 branch and loop (II)
Final consistency of MESI cache in CPU -- why does CPU need cache
Reading notes - learn to write: what is writing?
Global and Chinese market of digital impression system 2022-2028: Research Report on technology, participants, trends, market size and share
SQL statement
Pesticide synergist - current market situation and future development trend
Ceramic metal crowns - current market situation and future development trend
中電資訊-信貸業務數字化轉型如何從星空到指尖?
Gee import SHP data - crop image
Global and Chinese market of small batteries 2022-2028: Research Report on technology, participants, trends, market size and share
Why can't it run (unresolved)
Database concept and installation
C language black Technology: Archimedes spiral! Novel, interesting, advanced~
MySQL advanced (Advanced) SQL statement (I)
mysql使用視圖報錯,EXPLAIN/SHOW can not be issued; lacking privileges for underlying table