当前位置:网站首页>[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 .
边栏推荐
- 最多可以参加的会议数目[贪心 + 优先队列]
- 力扣 1790. 仅执行一次字符串交换能否使两个字符串相等
- vulnhub之Funfox2
- Force buckle 1961 Check whether the string is an array prefix
- Creation of kubernetes mysql8
- 841. String hash
- 第二十章 使用工作队列管理器(三)
- Gorilla official: sample code for golang to open websocket client
- 【哲思与实战】程序设计之道
- Machine learning notes - explore object detection datasets using streamlit
猜你喜欢
随机推荐
vulnhub之school 1
Welcome to the markdown editor
LeetCode_7_5
【哲思与实战】程序设计之道
Try the tuiroom of Tencent cloud (there is an appointment in the evening, which will be continued...)
JVM GC垃圾回收简述
YoloV6:YoloV6+Win10---训练自己得数据集
JVM GC garbage collection brief
pom. Brief introduction of XML configuration file label function
Leetcode force buckle (Sword finger offer 36-39) 36 Binary search tree and bidirectional linked list 37 Serialize binary tree 38 Arrangement of strings 39 Numbers that appear more than half of the tim
Some arrangements about oneself
Force buckle 1961 Check whether the string is an array prefix
Semantic slam source code analysis
Force buckle 2319 Judge whether the matrix is an X matrix
Automatic classification of defective photovoltaic module cells in electroluminescence images-論文閱讀筆記
ASP. Net learning & ASP's one word
力扣599. 两个列表的最小索引总和
Sword finger offer II 013 Sum of two-dimensional submatrix
Openeuler prize catching activities, to participate in?
pom.xml 配置文件标签:dependencies 和 dependencyManagement 区别