当前位置:网站首页>[MySQL - Basic] transactions
[MySQL - Basic] transactions
2022-07-07 20:13:00 【I'm not greedy】
List of articles
brief introduction
- A transaction is a collection of operations , It is an indivisible unit of work , The transaction will submit or revoke the operation request to the system as a whole . These operations are either all successful , All or nothing .
- give an example :
Zhang Sanyou 2000, Li Si has 2000, Zhang San transfers money to Li Si 1000.
- step : Check Zhang San's account balance , You can transfer money over 1000 , Zhang San's account decreased 1000, Li Si's account increased 1000.
- Situation 1 : Zhang San's account balance was reduced successfully , Li Si's account balance increased successfully .
- Situation two : Zhang San's account balance was reduced successfully , Li Si threw an exception when his account balance increased . At this time, there will be an amount error .
- solve : Put the three steps in a transaction scope .
Open transaction —> Check Zhang San's account balance —> Zhang San's balance decreased 1000—> Li Si balance increase 1000—> Throw exceptions —> Roll back the transaction —> Commit transaction
- operation :
- Create table statement :
CREATE TABLE account(
a_id INT AUTO_INCREMENT PRIMARY KEY COMMENT ‘ Primary key ID’,
a_name VARCHAR(10) COMMENT ‘ full name ’,
a_money INT COMMENT ‘ The account balance ’
)COMMENT ‘ Account form ’;
- insert data
INSERT INTO account(a_id,a_name,a_money) VALUES (NULL,‘ Zhang San ’,2000),(NULL,‘ Li Si ’,2000);
- Update data
UPDATE account SET a_money=2000 WHERE a_name = ‘ Zhang San ’ OR a_name =‘ Li Si ’;
1、 Transfer operation : Situation 1 ( There will be book imbalance , Zhang San's account balance has decreased 1000, But Li Si's account balance was not added 1000)
(1) Check Zhang San's account balance
SELECT * FROM account WHERE a_name = ‘ Zhang San ’;
(2) Subtract... From Zhang San's account balance 1000
UPDATE account SET a_money = a_money - 1000 WHERE a_name = ‘ Zhang San ’;
Throw an exception
(3) Add the balance of Li Si's account 1000
UPDATE account SET a_money = a_money + 1000 WHERE a_name = ‘ Li Si ’;
2、 Transfer operation : Mode 1 of case 2
(1) Open transaction
A、 View the submission method statement :SELECT @@autocommit; if 1, Automatic submission ; if 0, Manual submission .
B、 Set the submission method to manual statement :SET @@autocommit = 0;
(2) Check Zhang San's account balance
SELECT * FROM account WHERE a_name = ‘ Zhang San ’;
(3) Subtract... From Zhang San's account balance 1000
UPDATE account SET a_money = a_money - 1000 WHERE a_name = ‘ Zhang San ’;
(4) Add the balance of Li Si's account 1000
UPDATE account SET a_money = a_money + 1000 WHERE a_name = ‘ Li Si ’;
(5) Commit transaction
COMMIT;
(6) Rollback transaction statement ( If you are adding the balance of Li Si 1000 Previous error reporting , You can manually execute this statement ):
CALLBACK;
- Show the execution steps and results :
A、 First set the transaction to manual commit ;
B、 perform (2)(3)(4);
C、 Then reopen a terminal , Execute statement select * from account; The result picture is shown below :
D、 In execution (5), Then re execute the query statement on the newly opened terminal :select * from account; The following results will appear :
- Be careful
- If in execution (4) Before , It's a mistake ; Should be implemented (6)
- SET @@autocommit And START TRANSACTION or BEGIN; It's all manual submission ; The difference lies in :
SET @@autocommit Control the whole console, and START TRANSACTION Single transaction controlled ;
3、 Transfer operation : Mode 2 of case 2
(1) Open transaction
A、 View the submission method statement :SELECT @@autocommit; if 1, Automatic submission ; if 0, Manual submission .
B、 Set the submission method to automatic statement :SET @@autocommit = 1;
C、 Execute statements on a terminal : START TRANSACTION or BEGIN;
(2) Check Zhang San's account balance
SELECT * FROM account WHERE a_name = ‘ Zhang San ’;
(3) Subtract... From Zhang San's account balance 1000
UPDATE account SET a_money = a_money - 1000 WHERE a_name = ‘ Zhang San ’;
(4) Add the balance of Li Si's account 1000
UPDATE account SET a_money = a_money + 1000 WHERE a_name = ‘ Li Si ’;
(5) Commit transaction
COMMIT;
(6) Rollback transaction statement ( If you are adding the balance of Li Si 1000 Previous error reporting , You can manually execute this statement ):
CALLBACK;
- Show the execution steps and results :
A 、 Set to auto submit , perform START TRANSACTION; sentence ;
B、 Re execution (2)(3)(4);
C、 Reopen a terminal , perform select * from account; sentence , give the result as follows :
D、 If it is executed at the first terminal commit command ; When another terminal executes the query statement , The result is :
- Add :
- When the insert statement is executed , The database error is as follows :
- terms of settlement :
(1) Query the code of fields in the table through statements :SHOW FULL COLUMNS FROM Table name ;
(2) Execute the modify statement :ALTER TABLE Table name CONVERT TO CHARACTER SET gbk COLLATE gbk_chinese_ci;
(3) When querying the coding format of table fields :( Same as the first query statement )
(4) Execute the insert statement on the data :
Four characteristics (ACID)
- Atomicity (Atomicity)
- Transactions are the smallest and indivisible unit of operations , All or nothing , All or nothing .
- Uniformity (Consistency)
- When the transaction completes , All data must be in a consistent state .
- Isolation, (Isolation)
- The isolation mechanism provided by the database system , Ensure that transactions run in an independent environment that is not affected by external concurrent operations .
- persistence (Durability)
- Once a transaction is committed or rolled back , Its changes to the data in the database are permanent .( After the data is submitted , It will be permanently stored on disk )
Concurrent transaction problems
- Dirty reading
- One transaction reads data that has not been committed by another transaction .
for example : Business A Accessing data , And modify the data ; At this point, the transaction B Also to access data , Transaction used A The updated data .
- Fantasy reading
- When a transaction queries data according to criteria , There is no corresponding data row ; But when inserting data , It is found that this line of data already exists , It seems that " The phantom ".
for example : Business A Query data according to criteria , No query result ; At this time, concurrent transactions B Insert data and submit ; Business A Also insert data , But the error is reported. This data already exists ; Business A Query the data again , Still can't access data .
- It can't be read repeatedly
- A transaction reads the same record one after the other , But the data read twice is different , It's called unrepeatable reading .
for example : Business A Access the data , At this time, concurrent transactions B The data has been updated and submitted ; Business A When accessing data again , It is inconsistent with the data of the previous visit .
Four isolation levels
- Read uncommitted (Read Uncommitted)
- At this level of isolation , Dirty reading 、 Fantasy reading 、 It can't be solved without repeated reading .
- Example :
A、 Open both terminals : terminal 1 And terminals 2
B、 terminal 1 In the implementation of SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
C、 Re execution START TRANSACTION ;
D、 Query the data :SELECT * FROM account; give the result as follows :
E、 At terminal 2 perform
START TRANSACTION ;
UPDATE account SET a_money = a_money - 1000 WHERE a_name = ‘ Zhang San ’;
F、 Again at the terminal 1 Execute the query :SELECT * FROM account; give the result as follows :
- Read submitted (Read Committed)
- At this level of isolation , Solved dirty reading .
- Example :
A、 Open both terminals : terminal 1 And terminals 2
B、 terminal 1 In the implementation of SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
C、 Re execution START TRANSACTION ;
D、 Query the data :SELECT * FROM account; give the result as follows :
E、 At terminal 2 perform
START TRANSACTION ;
UPDATE account SET a_money = a_money - 1000 WHERE a_name = ‘ Zhang San ’;
F、 Again at the terminal 1 Point to query :SELECT * FROM account; give the result as follows :
G、 At terminal 2 Committing transactions , perform commit;
H、 Again at the terminal 1 The query :SELECT * FROM account; give the result as follows :
- Repeatable (Repeatable Read)( Default )
- At this level of isolation , Solved dirty reading 、 It can't be read repeatedly .
- Example 1:
A、 Open both terminals : terminal 1 And terminals 2
B、 terminal 1 In the implementation of SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
C、 Re execution START TRANSACTION ;
D、 Query the data :SELECT * FROM account; give the result as follows :
E、 At terminal 2 perform
START TRANSACTION ;
UPDATE account SET a_money = a_money - 1000 WHERE a_name = ‘ Zhang San ’;
commit;
F、 Again at the terminal 1 Point to query :SELECT * FROM account; give the result as follows :
G、 At terminal 1 Committing transactions , perform commit;
H、 Again at the terminal 1 The query :SELECT * FROM account; give the result as follows :- Example 2( Will produce unreal reading ):
A、 At terminal 1 perform
START TRANSACTION ;
SELECT * FROM account WHERE a_id = 3; give the result as follows :
B、 At terminal 2 perform :
START TRANSACTION ;
INSERT INTO account VALUES(3,‘ Wang Wu ’,2000);
COMMIT;
C、 At terminal 1 Execute the query :SELECT * FROM account WHERE a_id = 3; give the result as follows :
D、 At terminal 1 perform INSERT INTO account VALUES(3,‘ I'm also Wang Wu ’,2000); give the result as follows :
- Serialization (Serializable)
- At this level of isolation , Solved dirty reading 、 Fantasy reading 、 It can't be read repeatedly .
- Example 2:
A、 Open both terminals : terminal 1 And terminals 2
B、 terminal 1 In the implementation of
SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE ;
START TRANSACTION ;
SELECT * FROM account WHERE a_id = 4; give the result as follows :
C、 At terminal 2 perform
START TRANSACTION ;
INSERT INTO account VALUES(4,‘ Pockmarks ’,2000);
You will find that the rotation has been carried out , Eventually, the execution will timeout .
D、 At terminal 1 perform INSERT INTO account VALUES(4,‘ Pockmarks ’,2000); Will execute successfully :
- View the isolation level of the transaction :
- SELECT @@tx_isolation;
- mysql8 Then the query statement :SELECT @@transaction_isolation;
- Set the transaction isolation level :(session Valid for the current session window ;global Valid for all client session windows )
- SET SESSION|GLOBAL TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
- Be careful :
- The higher the transaction isolation level , The more secure the data , But the lower the performance .
边栏推荐
- 力扣 1961. 检查字符串是否为数组前缀
- 国家网信办公布《数据出境安全评估办法》:累计向境外提供10万人信息需申报
- YoloV6:YoloV6+Win10---训练自己得数据集
- R language dplyr package select function, group_ The by function, filter function and do function obtain the third largest value of a specific numerical data column in a specified level in a specified
- Graduation season | regretful and lucky graduation season
- Cloud 组件发展升级
- Visual Studio 插件之CodeMaid自动整理代码
- Vulnhub's funfox2
- Try the tuiroom of Tencent cloud (there is an appointment in the evening, which will be continued...)
- Creation of kubernetes mysql8
猜你喜欢
国家网信办公布《数据出境安全评估办法》:累计向境外提供10万人信息需申报
Vulnhub tre1
Machine learning notes - explore object detection datasets using streamlit
CSDN syntax description
模拟实现string类
使用高斯Redis实现二级索引
CSDN语法说明
Opencv learning notes high dynamic range (HDR) imaging
Force buckle 599 Minimum index sum of two lists
关于cv2.dnn.readNetFromONNX(path)就报ERROR during processing node with 3 inputs and 1 outputs的解决过程【独家发布】
随机推荐
CUDA versions are inconsistent, and errors are reported when compiling apex
力扣 2319. 判断矩阵是否是一个 X 矩阵
【解决】package ‘xxxx‘ is not in GOROOT
Welcome to the markdown editor
Force buckle 459 Duplicate substring
PHP method of obtaining image information
力扣 912.排序数组
The boundary of Bi: what is bi not suitable for? Master data, Martech? How to expand?
力扣 643. 子数组最大平均数 I
Vulnhub's funfox2
Oracle 存储过程之遍历
CIS芯片测试到底怎么测?
Vulnhub tre1
Force buckle 2315 Statistical asterisk
Simulate the implementation of string class
Cloud 组件发展升级
R language dplyr package select function, group_ The by function, filter function and do function obtain the third largest value of a specific numerical data column in a specified level in a specified
JVM GC垃圾回收简述
整型int的拼接和拆分
Boot 和 Cloud 的版本选型