当前位置:网站首页>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;
边栏推荐
- Key knowledge of embedded driver
- Comment la transformation numérique du crédit d'information de la Chine passe - t - elle du ciel au bout des doigts?
- ZABBIX API pulls the values of all hosts of a monitoring item and saves them in Excel
- A. ABC
- Neo4j learning notes
- G3 boiler water treatment registration examination and G3 boiler water treatment theory examination in 2022
- Key knowledge of C language
- Servlet simple verification code generation
- MySQL utilise la vue pour signaler les erreurs, Explicit / show ne peut pas être publié; Verrouillage des fichiers privés pour la table sous - jacente
- [typora installation package] old typera installation package, free version
猜你喜欢
Will the memory of ParticleSystem be affected by maxparticles
Bugku Zhi, you have to stop him
Yyds dry goods inventory override and virtual of classes in C
Mysql-15 aggregate function
Save Private Ryan - map building + voltage dp+deque+ shortest circuit
When tidb meets Flink: tidb efficiently enters the lake "new play" | tilaker team interview
Database concept and installation
How to subcontract uniapp and applet, detailed steps (illustration) # yyds dry goods inventory #
VRRP+BFD
Node solves cross domain problems
随机推荐
Libcblas appears when installing opencv import CV2 so. 3:cannot open shared object file:NO such file or directory
Save Private Ryan - map building + voltage dp+deque+ shortest circuit
The latest analysis of hoisting machinery command in 2022 and free examination questions of hoisting machinery command
Network communication basic kit -- IPv4 socket structure
2022 electrician (elementary) examination question bank and electrician (elementary) simulation examination question bank
Final consistency of MESI cache in CPU -- why does CPU need cache
Setting function of Jerry's watch management device [chapter]
Yyds dry goods inventory override and virtual of classes in C
Write the first CUDA program
[typora installation package] old typera installation package, free version
17. File i/o buffer
SQL statement
Yyds dry goods inventory it's not easy to say I love you | use the minimum web API to upload files
After listening to the system clear message notification, Jerry informed the device side to delete the message [article]
Sequence sorting of basic exercises of test questions
Jerry's watch information type table [chapter]
2022 new examination questions for safety management personnel of hazardous chemical business units and certificate examination for safety management personnel of hazardous chemical business units
Cancer biopsy instruments and kits - market status and future development trends
Node write API
Global and Chinese market of box seals 2022-2028: Research Report on technology, participants, trends, market size and share