Use of stored procedures (IV) — use declare to define conditions and handlers

Time:2021-9-23

Defining conditions and handlers is to define the problems that may be encountered in the process of program execution in advance, and the methods to solve these problems can be defined in the handler, which can be simply understood as exception handling. This method can predict the possible problems in advance and put forward solutions, so as to enhance the robustness of the program and avoid abnormal stopping of the program. MySQL uses the declare keyword to define conditions and handlers.

Define conditions

In mysql, you can use the declare keyword to define conditions. The basic syntax is as follows:

–Conditional definition syntax

DECLARE  condition_name  CONDITION  FOR  condition_value  

— condition_ Definition format of value

SQLSTATE [VALUE] sqlstate_value | mysql_error_code

Where, condition_ Name indicates the name of the condition_ The value parameter indicates the type of condition; sqlstate_ Value parameter and MySQL_ error_ The code parameter can represent MySQL errors. As in the common error 1146 (42s02), sqlstate_ The value is 42s02, mysql_ error_ The code value is 1146. A simple example is as follows:

–Duplicate primary key definition error

— ERROR 1062 (23000): Duplicate entry ’60’ for key ‘PRIMARY’

–Method 1: use sqlstate_ value

DECLARE  primary_key_duplicate  CONDITION  FOR  SQLSTATE  ‘23000’ ;  

–Method 2: use MySQL_ error_ code

DECLARE primary_key_duplicate CONDITION  FOR  1062 ;

Use of stored procedures (IV) -- use declare to define conditions and handlers

This article comes from Song Wenchao super. The exclusive platforms include CSDN, segment fault, Jianshu and open source China. Please indicate the source for reprint.

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]