当前位置:网站首页>MySQL learning summary 12: system variables, user variables, definition conditions and handlers

MySQL learning summary 12: system variables, user variables, definition conditions and handlers

2022-06-13 03:24:00 koping_ wu

1、 Variable

   stay MySQL Stored procedures and functions in the database , Variables can be used to store intermediate result data of queries or calculations , Or output the final result data .
   stay MySQL In the database , Variables are divided into System variables as well as User defined variables .

1.1 System variables

1.1.1 Classification of system variables

   Variables are defined by the system , Not user defined , Belong to The server level . start-up MySQL service , Generate MySQL During the service instance ,MySQL Will be for MySQL Assignment of system variables in server memory , These system variables define the current MySQL Properties of the service instance 、 features . these The value of the system variable is either compile MySQL Time parameters The default value of , Or The configuration file ( for example my.ini etc. ) Parameter value in . You can go to the website https://dev.mysql.com/doc/refman/8.0/en/server-system-
variables.html
see MySQL The system variable of the document .
   System variables are divided into global system variables ( Need to add global keyword ) And session system variables ( Need to add session keyword ), Sometimes global system variables are referred to as global variables , Sometimes the session system variable is also called local Variable . If you don't write , Default session level . Static variables ( stay MySQL Their values cannot be used while service instances are running set Dynamic modification ) Belongs to a special global system variable .
   every last MySQL Client successfully connected MySQL After the server , Will produce the corresponding session . During the conversation ,MySQL The service instance will be in MySQL The session system variable corresponding to the session is generated in the server memory , The initial values of these session system variables are copies of the global system variable values .

  • The global system variable is for all sessions ( Connect ) It works , but Can't cross restart
  • conversation 1 Modifying the value of a global system variable will cause the session to 2 Modification of the same global system variable value in .

   stay MySQL Some system variables in can only be global , for example max_connections Used to limit the maximum number of connections to the server ; Some system variable scopes can be both global and session , for example character_set_client Character set used to set the client ; Some system variables can only be scoped to the current session , for example pseudo_thread_id Used to mark the current session MySQL Connect ID.

1.1.2 Look at the system variables

1) View all or part of the system variables

# See all global variables 
SHOW GLOBAL VARIABLES;
# View all session variables 
SHOW SESSION VARIABLES;
 or 
SHOW VARIABLES;
# Look at some of the system variables that meet the criteria .
SHOW GLOBAL VARIABLES LIKE '% identifier %';
# Look at some session variables that meet the criteria 
SHOW SESSION VARIABLES LIKE '% identifier %';

2) View the specified system variable
   As MySQL Coding standards ,MySQL The system variables in are expressed in Two “@” start , among “@@global” Used only to mark global system variables ,“@@session” Used only to mark the session system variable .“@@” First, mark the session system variable , If the session system variable does not exist , Then mark the global system variable .

# View the value of the specified system variable 
SELECT @@global. Variable name ;
# View the value of the specified session variable 
SELECT @@session. Variable name ;
# perhaps 
SELECT @@ Variable name ;

3) Modify the value of the system variable
   Sometimes , The database administrator needs to modify the default value of the system variable , To modify the current session or MySQL Properties of the service instance 、 features . The specific methods :

  1. modify MySQL The configuration file , Then modify MySQL The value of the system variable ( This method needs to be restarted MySQL service )
  2. stay MySQL During service operation , Use “set” Command to reset the value of the system variable
SET @@global. Variable name = A variable's value ;
# The way 2:
SET GLOBAL  Variable name = A variable's value ;
# Assign a value to a session variable 
# The way 1:
SET @@session. Variable name = A variable's value ;
# The way 2:
SET SESSION  Variable name = A variable's value ;

1.2 User variables

1.2.1 Classification of user variables

   User variables are defined by the user , As MySQL Coding standards ,MySQL User variables in One “@” start . Depending on the scope of action , It is divided into Session user variables and local variable .

  • Session user variables : The scope is the same as the session variable , Only right Current connection Session valid .
  • local variable : Only in BEGIN and END Valid in statement block . Local variables can only be used in Stored procedures and functions Use in .

1.2.2 Session user variables

1) Definition of variables

# The way 1:“=” or “:=”
SET @ User variables  =  value ;
SET @ User variables  :=  value ;
# The way 2:“:=”  or  INTO keyword 
SELECT @ User variables  :=  expression  [FROM  Equal clause ];
SELECT  expression  INTO @ User variables 
[FROM  Equal clause ];

2) Look at the value of the user variable ( see 、 Compare 、 Operations, etc )

SELECT @ User variables 

1.2.3 local variable

   Definition : have access to DECLARE Statement defines a local variable
   Scope : Just defining it BEGIN … END Effective in
   Location : Only on the BEGIN … END in , And can only be placed in the first sentence

BEGIN
	# Declare local variables 
	DECLARE  Variable name 1  Variable data type  [DEFAULT  Variable defaults ];
	DECLARE  Variable name 2, Variable name 3,...  Variable data type  [DEFAULT  Variable defaults ];
	# Assign values to local variables 
	SET  Variable name 1 =  value ;
	SELECT  value  INTO  Variable name 2 [FROM  Clause ];
	# View the value of a local variable 
	SELECT  Variable 1, Variable 2, Variable 3;
END

1) Defining variables

DECLARE  Variable name   type  [default  value ];  #  without DEFAULT Clause , The initial value is NULL

2) Variable assignment
The way 1: Generally used to assign simple values

SET  Variable name = value ;
SET  Variable name := value ;

The way 2: It is generally used to assign field values in the table

SELECT  Field name or expression  INTO  Variable name  FROM  surface ;

3) Using variables ( see 、 Compare 、 Operations, etc )

SELECT  Local variable name ;

1.2.4 Compare session user variables with local variables

 Insert picture description here

2、 Define conditions and handlers

   Defined conditions It is to define the problems that may be encountered 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 in case of warnings or errors . This can enhance the ability of the stored program to deal with problems , Avoid abnormal program stop .
   explain : Define conditions and handlers in stored procedures 、 All storage functions are supported .

2.1 Defined conditions

   The defining condition is to give MySQL Error code naming in , This helps to make the stored program code clearer . It will One Wrong name and Specified error condition Connect . This name can then be used to define the handler DECLARE HANDLER In the sentence .
   Define conditional usage DECLARE sentence , The syntax is as follows :

DECLARE  Wrong name  CONDITION FOR  Error code ( Or wrong conditions )

Description of error code :

  • MySQL_error_code and sqlstate_value All of them can express MySQL Error of .MySQL_error_code Is a numeric type error code .sqlstate_value It's a length of 5 String type error code .
  • for example , stay ERROR 1418 (HY000) in ,1418 yes MySQL_error_code,'HY000’ yes sqlstate_value.
  • for example , stay ERROR 1142(42000) in ,1142 yes MySQL_error_code,'42000’ yes sqlstate_value.

2.2 Define handler

   It can be for SQL Some type of error that occurs during execution defines a special handler . When defining a handler , Use DECLARE The syntax of the statement is as follows :

DECLARE  Processing mode  HANDLER FOR  Wrong type   Processing statements 

1) Processing mode : The treatment methods are 3 A value of :CONTINUE、EXIT、UNDO.

  • CONTINUE : Indicates that an error is encountered and will not be processed , Carry on .
  • EXIT : Exit immediately in case of an error .
  • UNDO : Indicates that the previous operation is withdrawn after an error is encountered .MySQL This operation is not supported in the .

2) Wrong type ( I.e. conditions ) It can be taken as follows :

  • SQLSTATE ‘ String error code ’ : The length is 5 Of sqlstate_value Error code for type ;
  • MySQL_error_code : Match numeric type error code ;
  • Wrong name : Express DECLARE … CONDITION Defined error condition name .
  • SQLWARNING : Match all to 01 At the beginning SQLSTATE Error code ;
  • NOT FOUND : Match all to 02 At the beginning SQLSTATE Error code ;
  • SQLEXCEPTION : Match all that have not been SQLWARNING or NOT FOUND The captured SQLSTATE Error code ;

3) Processing statements :
   If one of the above conditions occurs , The corresponding processing method is adopted , And execute the specified processing statement . The statement can be
image “ SET Variable = value ” Such a simple statement , It can also be used BEGIN … END Write compound statements .

2.3 Illustrate with examples

Create a name “InsertDataWithCondition” Stored procedure , The code is as follows .
In the stored procedure , Define handler , Capture sqlstate_value value , When you meet sqlstate_value The value is 23000 when , perform EXIT fuck
do , And will @proc_value Is set to -1.

# preparation 
CREATE TABLE departments
AS
SELECT * FROM dbtest1.`departments`;
ALTER TABLE departments
ADD CONSTRAINT uk_dept_name UNIQUE(department_id);
DELIMITER //
CREATE PROCEDURE InsertDataWithCondition()
	BEGIN
		DECLARE duplicate_entry CONDITION FOR SQLSTATE '23000' ;
		DECLARE EXIT HANDLER FOR duplicate_entry SET @proc_value = -1;
		
		SET @x = 1;
		INSERT INTO departments(department_name) VALUES(' test ');
		SET @x = 2;
		INSERT INTO departments(department_name) VALUES(' test ');
		SET @x = 3;
	END //
DELIMITER ;

3、MySQL 8.0 New features — Persistence of global variables

stay MySQL In the database , Global variables can be accessed through SET GLOBAL Statement . for example , Set the limit of server statement timeout , You can set the system variable max_execution_time To achieve :

SET GLOBAL MAX_EXECUTION_TIME=2000;

Use SET GLOBAL The variable value set by the statement will only Provisional entry into force . Database restart after , The server will start from MySQL Read the default value of the variable in the configuration file . MySQL 8.0 Version added SET PERSIST command ,MySQL The configuration of the command will be saved in the data directory mysqld-auto.cnf In file , The file will be read the next time you start , use
The default configuration file is overwritten by the configuration in the .
.

for example , Set the maximum number of connections to the server to 1000:

SET PERSIST global max_connections = 1000;
原网站

版权声明
本文为[koping_ wu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280530399579.html