当前位置:网站首页>MySQL learning notes (Advanced)
MySQL learning notes (Advanced)
2022-07-02 20:57:00 【Love and dream】
One 、MySQL Stored procedures and functions
1. The concept of stored procedures and functions
- Stored procedures and functions are A segment that has been compiled in advance and stored in a database SQL Collection of statements
2. The benefits of stored procedures and functions
- Stored procedures and functions can be reused , Reduce the workload of developers . Be similar to java Methods in can be called multiple times
- Reduce network traffic , Stored procedures and functions are on the server , Just pass the name and parameters when calling
- Reduce data transfer between database and application server , It can improve the efficiency of data processing
- Implement some business logic at the database level , It can reduce the business processing at the code level
3. The difference between stored procedures and functions
- Function must have a return value
- The stored procedure did not return a value
4. Create stored procedure
- Little knowledge
/* This keyword is used to declare sql Statement separator , tell MySQL The command is over ! sql The default separator for a statement is a semicolon , But sometimes we need a function sql The statement contains a semicolon , But not as an end sign . It can be used at this time DELIMITER To specify the separator ! */
-- Standard grammar
DELIMITER Separator
- Data preparation
-- establish db8 database
CREATE DATABASE db8;
-- Use db8 database
USE db8;
-- Create student table
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT, -- Student id
NAME VARCHAR(20), -- The student's name
age INT, -- Student age
gender VARCHAR(5), -- Student gender
score INT -- Student achievement
);
-- Add data
INSERT INTO student VALUES (NULL,' Zhang San ',23,' male ',95),(NULL,' Li Si ',24,' male ',98),
(NULL,' Wang Wu ',25,' Woman ',100),(NULL,' Zhao Liu ',26,' Woman ',90);
-- Group by gender , Check the total score of each group . In ascending order of total scores
SELECT gender,SUM(score) getSum FROM student GROUP BY gender ORDER BY getSum ASC;
- Create stored procedure syntax
-- Change the separator to $
DELIMITER $
-- Standard grammar
CREATE PROCEDURE Stored procedure name ( Parameters ...)
BEGIN
sql sentence ;
END$
-- Change the separator to semicolon
DELIMITER ;
- Create stored procedure
-- Change the separator to $
DELIMITER $
-- Create stored procedure , Package group query student total score sql sentence
CREATE PROCEDURE stu_group()
BEGIN
SELECT gender,SUM(score) getSum FROM student GROUP BY gender ORDER BY getSum ASC;
END$
-- Change the separator to semicolon
DELIMITER ;
5. Calling stored procedure
- Call stored procedure syntax
-- Standard grammar
CALL Stored procedure name ( The actual parameter );
-- call stu_group stored procedure
CALL stu_group();
6. View stored procedures
- Look at the stored procedure syntax
-- Query all stored procedures in the database Standard grammar
SELECT * FROM mysql.proc WHERE db=' Database name ';
7. Delete stored procedure
- Delete stored procedure syntax
-- Standard grammar
DROP PROCEDURE [IF EXISTS] Stored procedure name ;
-- Delete stu_group stored procedure
DROP PROCEDURE stu_group;
8. Stored procedure syntax
8.1 Introduction to stored procedure syntax
- Stored procedures are programmable . It means that variables can be used 、 expression 、 Conditional control statements 、 Loop statement, etc , To complete more complex functions !
8.2 Use of variables
- Defining variables
-- Standard grammar
DECLARE Variable name data type [DEFAULT The default value is ];
-- Be careful : DECLARE Local variables are defined , Can only be used in BEGIN END Within limits
-- Define a int Type variable 、 And the default value is 10
DELIMITER $
CREATE PROCEDURE pro_test1()
BEGIN
DECLARE num INT DEFAULT 10; -- Defining variables
SELECT num; -- Query variables
END$
DELIMITER ;
-- call pro_test1 stored procedure
CALL pro_test1();
- The assignment of a variable 1
-- Standard grammar
SET Variable name = A variable's value ;
-- Define string type variables , And the assignment
DELIMITER $
CREATE PROCEDURE pro_test2()
BEGIN
DECLARE NAME VARCHAR(10); -- Defining variables
SET NAME = ' stored procedure '; -- Assign values to variables
SELECT NAME; -- Query variables
END$
DELIMITER ;
-- call pro_test2 stored procedure
CALL pro_test2();
- The assignment of a variable 2
-- Standard grammar
SELECT Name INTO Variable name FROM Table name [WHERE Conditions ];
-- Define two int Variable , It's used to store the total scores of boys and girls
DELIMITER $
CREATE PROCEDURE pro_test3()
BEGIN
DECLARE men,women INT; -- Defining variables
SELECT SUM(score) INTO men FROM student WHERE gender=' male '; -- Calculate the total score of male students and assign it to men
SELECT SUM(score) INTO women FROM student WHERE gender=' Woman '; -- Calculate the total score of female students and assign it to women
SELECT men,women; -- Query variables
END$
DELIMITER ;
-- call pro_test3 stored procedure
CALL pro_test3();
8.3if Use of statements
- Standard grammar
-- Standard grammar
IF Judge the condition 1 THEN Executive sql sentence 1;
[ELSEIF Judge the condition 2 THEN Executive sql sentence 2;]
...
[ELSE Executive sql sentence n;]
END IF;
- Case presentation
/* Define a int Variable , It is used to store the total grade of the class Define a varchar Variable , Used to store score descriptions According to the total score : 380 Above and above Study well 320 ~ 380 Learning is good 320 following General learning */
DELIMITER $
CREATE PROCEDURE pro_test4()
BEGIN
-- Define the total score variable
DECLARE total INT;
-- Define the score to describe the variable
DECLARE description VARCHAR(10);
-- Assign a value to the total score variable
SELECT SUM(score) INTO total FROM student;
-- Judge the total score
IF total >= 380 THEN
SET description = ' Study well ';
ELSEIF total >= 320 AND total < 380 THEN
SET description = ' Learning is good ';
ELSE
SET description = ' General learning ';
END IF;
-- Query the total score and description information
SELECT total,description;
END$
DELIMITER ;
-- call pro_test4 stored procedure
CALL pro_test4();
8.4 Parameter passing
- The syntax of parameter passing
DELIMITER $
-- Standard grammar
CREATE PROCEDURE Stored procedure name ([IN|OUT|INOUT] Parameter name data type )
BEGIN
Executive sql sentence ;
END$
/* IN: Represents the input parameter , The actual data needs to be passed by the caller . default OUT: Represents the output parameter , This parameter can be used as the return value INOUT: It can be used as an input parameter , It can also be used as an output parameter */
DELIMITER ;
- Input parameters
- Standard grammar
DELIMITER $
-- Standard grammar
CREATE PROCEDURE Stored procedure name (IN Parameter name data type )
BEGIN
Executive sql sentence ;
END$
DELIMITER ;
- Case presentation
/* Enter the total score variable , Represents the student's total score Define a varchar Variable , Used to store score descriptions According to the total score : 380 Above and above Study well 320 ~ 380 Learning is good 320 following General learning */
DELIMITER $
CREATE PROCEDURE pro_test5(IN total INT)
BEGIN
-- Define the score to describe the variable
DECLARE description VARCHAR(10);
-- Judge the total score
IF total >= 380 THEN
SET description = ' Study well ';
ELSEIF total >= 320 AND total < 380 THEN
SET description = ' Learning is good ';
ELSE
SET description = ' General learning ';
END IF;
-- Query the total score and description information
SELECT total,description;
END$
DELIMITER ;
-- call pro_test5 stored procedure
CALL pro_test5(390);
CALL pro_test5((SELECT SUM(score) FROM student));
- Output parameters
- Standard grammar
DELIMITER $
-- Standard grammar
CREATE PROCEDURE Stored procedure name (OUT Parameter name data type )
BEGIN
Executive sql sentence ;
END$
DELIMITER ;
- Case presentation
/* Enter the total score variable , Represents the student's total score The output fraction describes the variable , A description of the student's total score According to the total score : 380 Above and above Study well 320 ~ 380 Learning is good 320 following General learning */
DELIMITER $
CREATE PROCEDURE pro_test6(IN total INT,OUT description VARCHAR(10))
BEGIN
-- Judge the total score
IF total >= 380 THEN
SET description = ' Study well ';
ELSEIF total >= 320 AND total < 380 THEN
SET description = ' Learning is good ';
ELSE
SET description = ' General learning ';
END IF;
END$
DELIMITER ;
-- call pro_test6 stored procedure
CALL pro_test6(310,@description);
-- Query the total score description
SELECT @description;
- Little knowledge
@ Variable name : This variable should be preceded by the name of the variable “@” Symbol , It's called the user session variable , On behalf of the whole conversation, he is useful , This is similar to a global variable .
@@ Variable name : This adds... To the variable "@@" Symbol , It's called system variables
8.5 case Use of statements
- Standard grammar 1
-- Standard grammar
CASE expression
WHEN value 1 THEN perform sql sentence 1;
[WHEN value 2 THEN perform sql sentence 2;]
...
[ELSE perform sql sentence n;]
END CASE;
- Standard grammar 2
-- Standard grammar
CASE
WHEN Judge the condition 1 THEN perform sql sentence 1;
[WHEN Judge the condition 2 THEN perform sql sentence 2;]
...
[ELSE perform sql sentence n;]
END CASE;
- Case presentation
/* Enter the total score variable , Represents the student's total score Define a varchar Variable , Used to store score descriptions According to the total score : 380 Above and above Study well 320 ~ 380 Learning is good 320 following General learning */
DELIMITER $
CREATE PROCEDURE pro_test7(IN total INT)
BEGIN
-- Defining variables
DECLARE description VARCHAR(10);
-- Use case Judge
CASE
WHEN total >= 380 THEN
SET description = ' Study well ';
WHEN total >= 320 AND total < 380 THEN
SET description = ' Learning is good ';
ELSE
SET description = ' General learning ';
END CASE;
-- Query score description information
SELECT description;
END$
DELIMITER ;
-- call pro_test7 stored procedure
CALL pro_test7(390);
CALL pro_test7((SELECT SUM(score) FROM student));
8.6 while loop
- Standard grammar
-- Standard grammar
Initialization statement ;
WHILE Conditional statements DO
Loop body statement ;
Conditional control statements ;
END WHILE;
- Case presentation
/* Calculation 1~100 Between even numbers and */
DELIMITER $
CREATE PROCEDURE pro_test8()
BEGIN
-- Define the summation variable
DECLARE result INT DEFAULT 0;
-- Define initialization variables
DECLARE num INT DEFAULT 1;
-- while loop
WHILE num <= 100 DO
-- Even number judgment
IF num%2=0 THEN
SET result = result + num; -- Add up
END IF;
-- Give Way num+1
SET num = num + 1;
END WHILE;
-- Query the sum result
SELECT result;
END$
DELIMITER ;
-- call pro_test8 stored procedure
CALL pro_test8();
8.7 repeat loop
- Standard grammar
-- Standard grammar
Initialization statement ;
REPEAT
Loop body statement ;
Conditional control statements ;
UNTIL Conditional statements
END REPEAT;
-- Be careful :repeat The loop stops when the condition is met .while Loop is executed when the condition is met
- Case presentation
/* Calculation 1~10 The sum between */
DELIMITER $
CREATE PROCEDURE pro_test9()
BEGIN
-- Define the summation variable
DECLARE result INT DEFAULT 0;
-- Define initialization variables
DECLARE num INT DEFAULT 1;
-- repeat loop
REPEAT
-- Add up
SET result = result + num;
-- Give Way num+1
SET num = num + 1;
-- Stop the cycle
UNTIL num>10
END REPEAT;
-- Query the sum result
SELECT result;
END$
DELIMITER ;
-- call pro_test9 stored procedure
CALL pro_test9();
8.8 loop loop
- Standard grammar
-- Standard grammar
Initialization statement ;
[ Cycle name :] LOOP
Conditional statements
[LEAVE Cycle name ;]
Loop body statement ;
Conditional control statements ;
END LOOP Cycle name ;
-- Be careful :loop Simple loops can be implemented , But exiting the loop requires other statements to define . We can use leave Sentence completion !
-- If you don't add a statement to exit the loop , Then it becomes an endless cycle .
- Case presentation
/* Calculation 1~10 The sum between */
DELIMITER $
CREATE PROCEDURE pro_test10()
BEGIN
-- Define the summation variable
DECLARE result INT DEFAULT 0;
-- Define initialization variables
DECLARE num INT DEFAULT 1;
-- loop loop
l:LOOP
-- Conditions established , Stop the cycle
IF num > 10 THEN
LEAVE l;
END IF;
-- Add up
SET result = result + num;
-- Give Way num+1
SET num = num + 1;
END LOOP l;
-- Query the sum result
SELECT result;
END$
DELIMITER ;
-- call pro_test10 stored procedure
CALL pro_test10();
8.9 The cursor
- The concept of cursors
- Cursors can traverse multiple rows of returned results , Get a whole line of data at a time
- In stored procedures and functions, cursors can be used to cycle the result set
- In simple terms, cursors are similar to iterator traversal of a collection
- MySQL Cursors in can only be used in stored procedures and functions
- The syntax of cursors
- Create cursors
-- Standard grammar
DECLARE Cursor name CURSOR FOR Inquire about sql sentence ;
- Open cursor
-- Standard grammar
OPEN Cursor name ;
- Get data using cursors
-- Standard grammar
FETCH Cursor name INTO Variable name 1, Variable name 2,...;
- Close cursor
-- Standard grammar
CLOSE Cursor name ;
- Basic use of cursors
-- establish stu_score surface
CREATE TABLE stu_score(
id INT PRIMARY KEY AUTO_INCREMENT,
score INT
);
/* take student Save all scores in the table to stu_score In the table */
DELIMITER $
CREATE PROCEDURE pro_test11()
BEGIN
-- Define performance variables
DECLARE s_score INT;
-- Create cursors , Query all student achievement data
DECLARE stu_result CURSOR FOR SELECT score FROM student;
-- Open cursor
OPEN stu_result;
-- Use cursors , Ergodic result , Get the number 1 Row data
FETCH stu_result INTO s_score;
-- Save data to stu_score In the table
INSERT INTO stu_score VALUES (NULL,s_score);
-- Use cursors , Ergodic result , Get the number 2 Row data
FETCH stu_result INTO s_score;
-- Save data to stu_score In the table
INSERT INTO stu_score VALUES (NULL,s_score);
-- Use cursors , Ergodic result , Get the number 3 Row data
FETCH stu_result INTO s_score;
-- Save data to stu_score In the table
INSERT INTO stu_score VALUES (NULL,s_score);
-- Use cursors , Ergodic result , Get the number 4 Row data
FETCH stu_result INTO s_score;
-- Save data to stu_score In the table
INSERT INTO stu_score VALUES (NULL,s_score);
-- Close cursor
CLOSE stu_result;
END$
DELIMITER ;
-- call pro_test11 stored procedure
CALL pro_test11();
-- Inquire about stu_score surface
SELECT * FROM stu_score;
-- ===========================================================
/* What happened : student There is a total of 4 Data , We traversed the cursor 4 Time , No problem ! But how many times do you traverse the cursor ? There will be problems */
DELIMITER $
CREATE PROCEDURE pro_test11()
BEGIN
-- Define performance variables
DECLARE s_score INT;
-- Create cursors , Query all student achievement data
DECLARE stu_result CURSOR FOR SELECT score FROM student;
-- Open cursor
OPEN stu_result;
-- Use cursors , Ergodic result , Get the number 1 Row data
FETCH stu_result INTO s_score;
-- Save data to stu_score In the table
INSERT INTO stu_score VALUES (NULL,s_score);
-- Use cursors , Ergodic result , Get the number 2 Row data
FETCH stu_result INTO s_score;
-- Save data to stu_score In the table
INSERT INTO stu_score VALUES (NULL,s_score);
-- Use cursors , Ergodic result , Get the number 3 Row data
FETCH stu_result INTO s_score;
-- Save data to stu_score In the table
INSERT INTO stu_score VALUES (NULL,s_score);
-- Use cursors , Ergodic result , Get the number 4 Row data
FETCH stu_result INTO s_score;
-- Save data to stu_score In the table
INSERT INTO stu_score VALUES (NULL,s_score);
-- Use cursors , Ergodic result , Get the number 5 Row data
FETCH stu_result INTO s_score;
-- Save data to stu_score In the table
INSERT INTO stu_score VALUES (NULL,s_score);
-- Close cursor
CLOSE stu_result;
END$
DELIMITER ;
-- call pro_test11 stored procedure
CALL pro_test11();
-- Inquire about stu_score surface , Although the data are correct , However, an error will be reported when executing the stored procedure
SELECT * FROM stu_score;
- Optimized use of cursors ( In combination with recycling )
/* When the cursor ends , Will trigger the cursor end event . We can use this feature to complete the loop operation Tagging thought : 1. Define a variable , The default value is 0( It means there's data ) 2. When the cursor ends , Change the variable value to 1( Means there's no data ) */
-- 1. Define a variable , The default value is 0( It means there's data )
DECLARE flag INT DEFAULT 0;
-- 2. When the cursor ends , Change the variable value to 1( Means there's no data )
DECLARE EXIT HANDLER FOR NOT FOUND SET flag = 1;
/* take student Save all scores in the table to stu_score In the table */
DELIMITER $
CREATE PROCEDURE pro_test12()
BEGIN
-- Define performance variables
DECLARE s_score INT;
-- Define tag variables
DECLARE flag INT DEFAULT 0;
-- Create cursors , Query all student achievement data
DECLARE stu_result CURSOR FOR SELECT score FROM student;
-- At the end of the cursor , Change the tag variable to 1
DECLARE EXIT HANDLER FOR NOT FOUND SET flag = 1;
-- Open cursor
OPEN stu_result;
-- Recycle cursors
REPEAT
-- Use cursors , Ergodic result , Get the data
FETCH stu_result INTO s_score;
-- Save data to stu_score In the table
INSERT INTO stu_score VALUES (NULL,s_score);
UNTIL flag=1
END REPEAT;
-- Close cursor
CLOSE stu_result;
END$
DELIMITER ;
-- call pro_test12 stored procedure
CALL pro_test12();
-- Inquire about stu_score surface
SELECT * FROM stu_score;
9. Summary of stored procedures
- The stored procedure is A segment that has been compiled in advance and stored in a database SQL Collection of statements . You can do some business processing at the database level
- To put it bluntly, a stored procedure is to put sql Statements are encapsulated as methods , You can then call the method to execute sql Just a statement
- Benefits of stored procedures
- Security
- Efficient
- Strong reusability
10. Storage function
- Stored functions and stored procedures are very similar . What storage functions can do , Stored procedures can also do !
- The storage function has a return value , The stored procedure did not return a value ( Parametric out In fact, it is equivalent to returning data )
- Standard grammar
- Create a storage function
DELIMITER $
-- Standard grammar
CREATE FUNCTION The name of the function ([ Parameters data type ])
RETURNS return type
BEGIN
Executive sql sentence ;
RETURN result ;
END$
DELIMITER ;
- Calling the storage function
-- Standard grammar
SELECT The name of the function ( The actual parameter );
- Delete storage function
-- Standard grammar
DROP FUNCTION The name of the function ;
- Case presentation
/* Define storage functions , Get the score in the student table greater than 95 The number of students divided */
DELIMITER $
CREATE FUNCTION fun_test1()
RETURNS INT
BEGIN
-- Define statistical variables
DECLARE result INT;
-- The query result is greater than 95 The number of students divided , Assign values to statistical variables
SELECT COUNT(*) INTO result FROM student WHERE score > 95;
-- Return Statistics
RETURN result;
END$
DELIMITER ;
-- call fun_test1 Storage function
SELECT fun_test1();
Two 、MySQL trigger
1. The concept of trigger
- Triggers are database objects related to tables , Can be in insert/update/delete Before or after , Trigger and execute the... Defined in the trigger SQL sentence . This feature of trigger can help to ensure the integrity of data in database 、 logging 、 Data verification and other operations .
- Use the alias NEW and OLD To refer to the changed record content in the trigger , This is similar to other databases . Now triggers only support row level triggering , Statement level triggering is not supported .
| Trigger Type | OLD The meaning of | NEW The meaning of |
|---|---|---|
| INSERT Type trigger | nothing ( Because there is no data in the state before insertion ) | NEW Indicates the data to be added or added |
| UPDATE Type trigger | OLD Represents the data before modification | NEW Represents the data that will be or has been modified |
| DELETE Type trigger | OLD Data that will be or has been deleted | nothing ( Because there is no data after deletion ) |
2. Create trigger
- Standard grammar
DELIMITER $
CREATE TRIGGER Trigger Name
BEFORE|AFTER INSERT|UPDATE|DELETE
ON Table name
[FOR EACH ROW] -- Line level triggers
BEGIN
The function that the trigger performs ;
END$
DELIMITER ;
- Trigger Demo . Record the data change log of account table through trigger . contain : increase 、 modify 、 Delete
- Create account table
-- establish db9 database
CREATE DATABASE db9;
-- Use db9 database
USE db9;
-- Create account table account
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT, -- Account id
NAME VARCHAR(20), -- full name
money DOUBLE -- balance
);
-- Add data
INSERT INTO account VALUES (NULL,' Zhang San ',1000),(NULL,' Li Si ',2000);
- Create a log table
-- Create a log table account_log
CREATE TABLE account_log(
id INT PRIMARY KEY AUTO_INCREMENT, -- journal id
operation VARCHAR(20), -- Operation type (insert update delete)
operation_time DATETIME, -- Operating time
operation_id INT, -- Operation table id
operation_params VARCHAR(200) -- Operating parameters
);
- establish INSERT trigger
-- establish INSERT trigger
DELIMITER $
CREATE TRIGGER account_insert
AFTER INSERT
ON account
FOR EACH ROW
BEGIN
INSERT INTO account_log VALUES (NULL,'INSERT',NOW(),new.id,CONCAT(' After inserting {id=',new.id,',name=',new.name,',money=',new.money,'}'));
END$
DELIMITER ;
-- towards account Table add record
INSERT INTO account VALUES (NULL,' Wang Wu ',3000);
-- Inquire about account surface
SELECT * FROM account;
-- Query log table
SELECT * FROM account_log;
- establish UPDATE trigger
– establish UPDATE trigger
DELIMITER $
CREATE TRIGGER account_update
AFTER UPDATE
ON account
FOR EACH ROW
BEGIN
INSERT INTO account_log VALUES (NULL,'UPDATE',NOW(),new.id,CONCAT(' Before the change {id=',old.id,',name=',old.name,',money=',old.money,'}',' After modification {id=',new.id,',name=',new.name,',money=',new.money,'}'));
END$
DELIMITER ;
-- modify account surface
UPDATE account SET money=3500 WHERE id=3;
-- Inquire about account surface
SELECT * FROM account;
-- Query log table
SELECT * FROM account_log;
- establish DELETE trigger
-- establish DELETE trigger
DELIMITER $
CREATE TRIGGER account_delete
AFTER DELETE
ON account
FOR EACH ROW
BEGIN
INSERT INTO account_log VALUES (NULL,'DELETE',NOW(),old.id,CONCAT(' Before deleting {id=',old.id,',name=',old.name,',money=',old.money,'}'));
END$
DELIMITER ;
-- Delete account Table data
DELETE FROM account WHERE id=3;
-- Inquire about account surface
SELECT * FROM account;
-- Query log table
SELECT * FROM account_log;
3. Check triggers
-- Standard grammar
SHOW TRIGGERS;
-- Check triggers
SHOW TRIGGERS;
4. Delete trigger
-- Standard grammar
DROP TRIGGER Trigger Name ;
-- Delete DELETE trigger
DROP TRIGGER account_delete;
5. Summary of triggers
- Triggers are database objects related to tables
- Can be in insert/update/delete Before or after , Trigger and execute the... Defined in the trigger SQL sentence
- This feature of trigger can help to ensure the integrity of data in database 、 logging 、 Data verification and other operations
- Use the alias NEW and OLD To refer to the changed record content in the trigger
3、 ... and 、MySQL Business
1. Concept of transactions
- One or more SQL Statements form an execution unit , The feature is that this unit either succeeds or fails at the same time , Each of the units SQL Statements depend on each other , To form a whole , If one of the SQL Statement execution failed or an error occurred , Then the whole unit will roll back , Back to the original state of the transaction , If all of the units SQL Statements are executed successfully , Then the transaction goes smoothly .
2. Data preparation for transactions
-- establish db10 database
CREATE DATABASE db10;
-- Use db10 database
USE db10;
-- Create account table
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT, -- Account id
NAME VARCHAR(20), -- title of account
money DOUBLE -- The account balance
);
-- Add data
INSERT INTO account VALUES (NULL,' Zhang San ',1000),(NULL,' Li Si ',1000);
3. Unmanaged transaction Demo
-- Zhang San transfers money to Li Si 500 element
-- 1. Zhang San's account -500
UPDATE account SET money=money-500 WHERE NAME=' Zhang San ';
-- 2. Li Si's account +500
Something went wrong ...
UPDATE account SET money=money+500 WHERE NAME=' Li Si ';
-- In this scenario , These two sql The statement either succeeds at the same time , Or fail at the same time . It needs to be managed by the firm !
4. Management transaction Demo
- The three steps of operating a transaction
- Open transaction : Record the rollback point , And notify the server , A set of operations will be performed , Or at the same time 、 Or fail at the same time
- perform sql sentence : Carry out one or more specific sql sentence
- End the business ( Submit | Roll back )
- Submit : No problem , Update the data
- Roll back : Problems arise , The data is restored to the state when the transaction was opened
- Open transaction
-- Standard grammar
START TRANSACTION;
- Roll back the transaction
-- Standard grammar
ROLLBACK;
- Commit transaction
-- Standard grammar
COMMIT;
- Management transaction Demo
-- Open transaction
START TRANSACTION;
-- Zhang San transfers money to Li Si 500 element
-- 1. Zhang San's account -500
UPDATE account SET money=money-500 WHERE NAME=' Zhang San ';
-- 2. Li Si's account +500
-- Something went wrong ...
UPDATE account SET money=money+500 WHERE NAME=' Li Si ';
-- Roll back the transaction ( Problems arise )
ROLLBACK;
-- Commit transaction ( No problem )
COMMIT;
5. How to commit a transaction
- submission
- Automatic submission (MySQL The default is auto submit )
- Manual submission
- Modify submission method
- See how to submit
-- Standard grammar
SELECT @@AUTOCOMMIT; -- 1 On behalf of auto submit 0 On behalf of hand submit
- Modify submission method
-- Standard grammar
SET @@AUTOCOMMIT= Numbers ;
-- Change to manual submit
SET @@AUTOCOMMIT=0;
-- See how to submit
SELECT @@AUTOCOMMIT;
6. The four characteristics of affairs (ACID)
- Atomicity (atomicity)
- Atomicity refers to the success of all operations contained in a transaction , Either all failures roll back , Therefore, if the transaction operation succeeds, it must be fully applied to the database , If the operation fails, there will be no impact on the database
- Uniformity (consistency)
- Consistency refers to the fact that a transaction must transform a database from one consistency state to another , That is to say, a transaction must be in a consistent state before and after execution
- Take money transfer , Suppose the sum of Zhang San's and Li Si's money is 2000, So no matter A and B How to transfer money between banks , Transfer several times , After the transaction, the sum of money of the two users should be 2000, This is the consistency of transactions
- Isolation, (isolcation)
- Isolation is when multiple users access the database concurrently , For example, when operating the same table , A transaction opened by a database for each user , It cannot be interfered by the operation of other transactions , Multiple concurrent transactions should be isolated from each other
- persistence (durability)
- Persistence means that once a transaction is committed , So the change to the data in the database is permanent , Even in the case of database system failure, the transaction commit operation will not be lost
7. The isolation level of the transaction
The concept of isolation level
- When multiple clients operate , Transactions between clients should be isolated , Mutually independent , Unaffected .
- If multiple transactions operate on the same batch of data , You need to set different isolation levels , Otherwise, there will be problems .
- Let's take a look at the names of the four isolation levels , Let's look at the possible problems
Four levels of isolation
1 Read uncommitted read uncommitted
2 Read submitted read committed
3 Repeatable repeatable read
4 Serialization serializablePossible problems
| problem | The phenomenon |
|---|---|
| Dirty reading | Read data from another uncommitted transaction during one transaction , The results of the two queries are inconsistent |
| It can't be read repeatedly | It means that the data modified and committed in another transaction is read in the process of one transaction , The results of the two queries are inconsistent |
| Fantasy reading | select Whether a record exists , non-existent , Ready to insert this record , But enforcement insert Found that this record already exists , Can't insert . Or there is no execution delete Delete , I found that the deletion was successful |
- Query database isolation level
-- Standard grammar
SELECT @@TX_ISOLATION;
- Modify the database isolation level
-- Standard grammar
SET GLOBAL TRANSACTION ISOLATION LEVEL Level string ;
-- Modify the database isolation level to read uncommitted
SET GLOBAL TRANSACTION ISOLATION LEVEL read uncommitted;
-- Check the isolation level
SELECT @@TX_ISOLATION; -- It needs to be disconnected after modification
8. Transaction isolation level demonstration
- The problem of dirty reading
- window 1
-- Query account table
select * from account;
-- Set the isolation level to read uncommitted
set global transaction isolation level read uncommitted;
-- Open transaction
start transaction;
-- Transfer accounts
update account set money = money - 500 where id = 1;
update account set money = money + 500 where id = 2;
-- window 2 Query transfer results , Dirty reading ( Query uncommitted data of other transactions )
-- window 2 After checking the transfer results , rollback
rollback;
- window 2
-- Query isolation level
select @@tx_isolation;
-- Open transaction
start transaction;
-- Query account table
select * from account;
- Solve the problem of dirty reading and demonstrate the problem of non repeatable reading
- window 1
-- Set the isolation level to read committed
set global transaction isolation level read committed;
-- Open transaction
start transaction;
-- Transfer accounts
update account set money = money - 500 where id = 1;
update account set money = money + 500 where id = 2;
-- window 2 Check the transfer results , Nothing has changed ( The dirty reading problem has been solved )
-- Perform commit transactions .
commit;
-- window 2 Check the transfer results , The data has changed ( There's the problem of not being able to read again , Read committed data from other transactions )
- window 2
-- Query isolation level
select @@tx_isolation;
-- Open transaction
start transaction;
-- Query account table
select * from account;
- Solve the problem of non repeatable reading
- window 1
-- Set the isolation level to repeatable read
set global transaction isolation level repeatable read;
-- Open transaction
start transaction;
-- Transfer accounts
update account set money = money - 500 where id = 1;
update account set money = money + 500 where id = 2;
-- window 2 Check the transfer results , Nothing has changed
-- Perform commit transactions
commit;
-- At this time, the window 2 As long as it's still in the last business , The results are the same . Only the window 2 End the business , To see the change ( The problem of non repeatable reading has been solved )
- window 2
-- Query isolation level
select @@tx_isolation;
-- Open transaction
start transaction;
-- Query account table
select * from account;
-- Commit transaction
commit;
-- Query account table
select * from account;
- The problem and solution of unreal reading
- window 1
-- Set the isolation level to repeatable read
set global transaction isolation level repeatable read;
-- Open transaction
start transaction;
-- Add a record
INSERT INTO account VALUES (3,' Wang Wu ',1500);
-- Query account table , In this window, you can see id by 3 Result
SELECT * FROM account;
-- Commit transaction
COMMIT;
- window 2
-- Query isolation level
select @@tx_isolation;
-- Open transaction
start transaction;
-- Query account table , The newly added id by 3 The record of
select * from account;
-- add to id by 3 A piece of data , Discovery add failed . There's unreal reading
INSERT INTO account VALUES (3,' test ',200);
-- Commit transaction
COMMIT;
-- Query account table , The newly added id by 3 The record of
select * from account;
- Solve the problem of unreal reading
/* window 1 */
-- Set the isolation level to serializable
set global transaction isolation level serializable;
-- Open transaction
start transaction;
-- Add a record
INSERT INTO account VALUES (4,' Zhao Liu ',1600);
-- Query account table , In this window, you can see id by 4 Result
SELECT * FROM account;
-- Commit transaction
COMMIT;
/* window 2 */
-- Query isolation level
select @@tx_isolation;
-- Open transaction
start transaction;
-- Query account table , The query statement cannot be executed , The data table is locked ! Only the window 1 After committing the transaction , Before you can continue to operate
select * from account;
-- add to id by 4 A piece of data , It's been discovered that , No more ! The problem of unreal reading has been solved
INSERT INTO account VALUES (4,' test ',200);
-- Commit transaction
COMMIT;
9. Isolation level summary
| Isolation level | name | Dirty reading | Non repeatable reading appears | Phantom reading | Database default isolation level |
|---|---|---|---|---|---|
| 1 | read uncommitted | Read uncommitted | yes | yes | yes |
| 2 | read committed | Read submitted | no | yes | yes Oracle / SQL Server |
| 3 | repeatable read | Repeatable | no | no | yes MySQL |
| 4 | serializable | Serialization | no | no | no |
Be careful : The isolation level is getting higher and higher from small to large , But the efficiency is getting lower , So it's not recommended READ UNCOMMITTED and SERIALIZABLE Isolation level .
10. A summary of the business
- One or more SQL Statements form an execution unit , The feature is that this unit either succeeds or fails at the same time . For example, transfer operations
- Open transaction :start transaction;
- Roll back the transaction :rollback;
- Commit transaction :commit;
- Four characteristics of business
- Atomicity
- persistence
- Isolation,
- Uniformity
- The isolation level of the transaction
- read uncommitted( Read uncommitted )
- read committed ( Read submitted )
- repeatable read ( Repeatable )
- serializable ( Serialization )
边栏推荐
- [12] the water of the waves is clear, which can wash my tassel. The water of the waves is muddy, which can wash my feet
- Google Earth engine (GEE) - Landsat 9 image full band image download (Beijing as an example)
- 想请教一下,究竟有哪些劵商推荐?手机开户是安全么?
- Driverless learning (III): Kalman filter
- I want to ask you, where is a better place to open an account in Dongguan? Is it safe to open a mobile account?
- kernel_ uaf
- 疫情封控65天,我的居家办公心得分享 | 社区征文
- Sweet talk generator, regular greeting email machine... Open source programmers pay too much for this Valentine's day
- 【Hot100】21. Merge two ordered linked lists
- Data preparation for behavior scorecard modeling
猜你喜欢

Sometimes only one line of statements are queried, and the execution is slow
![[internship] solve the problem of too long request parameters](/img/42/413cf867f0cb34eeaf999f654bf02f.png)
[internship] solve the problem of too long request parameters

Common routines of compressed packets in CTF
![[cloud native topic -50]:kubesphere cloud Governance - operation - step by step deployment of microservice based business applications - database middleware MySQL microservice deployment process](/img/e6/1dc747de045166f09ecdce1c5a34b1.jpg)
[cloud native topic -50]:kubesphere cloud Governance - operation - step by step deployment of microservice based business applications - database middleware MySQL microservice deployment process

ROS learning (10): ROS records multiple topic scripts

Summary of interview experience, escort your offer, full of knowledge points
![[question brushing diary] classic questions of dynamic planning](/img/31/fcd8230f809d6178f11e7095c1ef94.jpg)
[question brushing diary] classic questions of dynamic planning

台湾SSS鑫创SSS1700替代Cmedia CM6533 24bit 96KHZ USB音频编解码芯片

通信人的经典语录,第一条就扎心了……

Spark source code compilation, cluster deployment and SBT development environment integration in idea
随机推荐
JDBC | Chapter 3: SQL precompile and anti injection crud operation
Driverless learning (4): Bayesian filtering
接口测试到底怎么做?看完这篇文章就能清晰明了
想请教一下,我在东莞,到哪里开户比较好?手机开户是安全么?
Function, function, efficiency, function, utility, efficacy
[question brushing diary] classic questions of dynamic planning
[internship] solve the problem of too long request parameters
2021 software security report: open source code, happiness and disaster depend on each other?
功能、作用、效能、功用、效用、功效
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
I would like to ask what securities dealers recommend? Is it safe to open a mobile account?
Codeforces round 651 (Div. 2) (a thinking, B thinking, C game, D dichotomy, e thinking)
Volvo's first MPV is exposed! Comfortable and safe, equipped with 2.0T plug-in mixing system, it is worth first-class
Resunet tensorrt8.2 speed and video memory record table on Jetson Xavier NX (continuously supplemented later)
Internal/validators js:124 throw new ERR_ INVALID_ ARG_ Type (name, 'string', value) -- solution
[kubernetes series] comparison of space and memory usage before and after kubedm reset initialization
[QT] QPushButton creation
Makefile: usage of control functions (error, warning, info)
Review of the latest 2022 research on "deep learning methods for industrial defect detection"
测试人员如何做不漏测?这7点就够了