当前位置:网站首页>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;
边栏推荐
- Applet graduation project is based on wechat classroom laboratory reservation applet graduation project opening report function reference
- Experimental animal models - current market situation and future development trend
- Feign implements dynamic URL
- Save Private Ryan - map building + voltage dp+deque+ shortest circuit
- Global and Chinese markets for electroencephalogram (EEG) devices 2022-2028: Research Report on technology, participants, trends, market size and share
- Conditional statements of shell programming
- Sword finger offer 14- I. cut rope
- Global and Chinese market of thin film deposition systems 2022-2028: Research Report on technology, participants, trends, market size and share
- Jerry's watch information type table [chapter]
- All ceramic crowns - current market situation and future development trend
猜你喜欢
Bacteriostatic circle scanning correction template
Chain ide -- the infrastructure of the metauniverse
Applet graduation project is based on wechat classroom laboratory reservation applet graduation project opening report function reference
Gee import SHP data - crop image
C # learning notes: structure of CS documents
在尋求人類智能AI的過程中,Meta將賭注押向了自監督學習
Life cycle of instance variables, static variables and local variables
Jerry's synchronous weather information to equipment [chapter]
Applet graduation design is based on wechat course appointment registration. Applet graduation design opening report function reference
[leetcode daily question] a single element in an ordered array
随机推荐
Applet graduation design is based on wechat course appointment registration. Applet graduation design opening report function reference
STM32 key content
The latest analysis of hoisting machinery command in 2022 and free examination questions of hoisting machinery command
MySQL advanced SQL statement (1)
Buuctf QR code
Valentine's Day - 9 jigsaw puzzles with deep love in wechat circle of friends
C # learning notes: structure of CS documents
The difference between lambda expressions and anonymous inner classes
From the 18th line to the first line, the new story of the network security industry
Override and virtual of classes in C #
How to view the computing power of GPU?
AI 助力藝術設計抄襲檢索新突破!劉芳教授團隊論文被多媒體頂級會議ACM MM錄用
Network communication basic kit -- IPv4 socket structure
MySQL workbench use
Ai aide à la recherche de plagiat dans le design artistique! L'équipe du professeur Liu Fang a été embauchée par ACM mm, une conférence multimédia de haut niveau.
Global and Chinese market of cell scrapers 2022-2028: Research Report on technology, participants, trends, market size and share
Bacteriostatic circle scanning correction template
12. Gettimeofday() and time()
What are the advantages and disadvantages of data center agents?
[typora installation package] old typera installation package, free version