当前位置:网站首页>[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 .
边栏推荐
猜你喜欢
RESTAPI 版本控制策略【eolink 翻译】
有了ST7008, 蓝牙测试完全拿捏住了
PHP method of obtaining image information
Chapter 9 Yunji datacanvas company won the highest honor of the "fifth digital finance innovation competition"!
CSDN syntax description
The boundary of Bi: what is bi not suitable for? Master data, Martech? How to expand?
AIRIOT助力城市管廊工程,智慧物联守护城市生命线
Automatic classification of defective photovoltaic module cells in electroluminescence images-論文閱讀筆記
ASP. Net learning & ASP's one word
Flink并行度和Slot详解
随机推荐
浅尝不辄止系列之试试腾讯云的TUIRoom(晚上有约,未完待续...)
BI的边界:BI不适合做什么?主数据、MarTech?该如何扩展?
Mysql, sqlserver Oracle database connection mode
Chapter 9 Yunji datacanvas was rated as 36 krypton "the hard core technology enterprise most concerned by investors"
[auto.js] automatic script
Semantic slam source code analysis
力扣 88.合并两个有序数组
Navicat连接2002 - Can‘t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock‘解决
sql 常用优化
mock. JS returns an array from the optional data in the object array
第二十章 使用工作队列管理器(三)
关于cv2.dnn.readNetFromONNX(path)就报ERROR during processing node with 3 inputs and 1 outputs的解决过程【独家发布】
Gorilla official: sample code for golang to open websocket client
模拟实现string类
JVM class loading mechanism
大厂经典指针笔试题
力扣 912.排序数组
Kubernetes -- detailed usage of kubectl command line tool
php 获取图片信息的方法
Vulnhub tre1