当前位置:网站首页>MySQL transaction
MySQL transaction
2022-07-05 12:13:00 【ziyi813】
MySQL Business
When multiple users access the same piece of data , A user may change in the process of Other users will also initiate change requests at the same time , In order to ensure that the update of data changes from one consistency to another consistency ,MySQL Transactions are used to ensure the consistency of data .
The engines that support transactions are innoDB and BDB.
InnoDB Storage engine transactions are mainly through UNDO Journal and REDO Log implementation ,MyISAM and MEMORY The storage engine does not support transactions .
Overview of the transaction
Transactions have the following four characteristics (ACID)
- Atomicity (Atomicity): All operations in a transaction are treated as an atomic unit , That is, data modification and other operations on the transaction can only be completely committed or rolled back .
- Uniformity (Consistency): The transaction is completed , must Change all data from one consistency state to another consistency state , All changes must be applied to the modification of the transaction , To ensure the integrity of the data .
- Isolation, (Isolation): The modification of the operation statement in a transaction must be isolated from the modification made by other transactions . The state of data when viewing data in a transaction , Or the state before being modified by another concurrent transaction , Or the state after being modified by another concurrent transaction , That is, the current transaction will not view the data being modified by another concurrent transaction . This feature is realized through the locking mechanism .
- persistence (Durability): After the transaction is completed , The impact of the changes made on the data is permanent , Even if the system restarts or there is a system failure, the data can still be recovered .
InnoDB Support ACID Business 、 Row level locks and high concurrency . To support transactions ,InnoDB The engine introduces transaction related UNDO Journal and REDO journal , At the same time, transactions depend on MySQL Lock mechanism provided .
REDO journal
When executing a transaction, you need to write the executed transaction log to the log file first , The corresponding file is REDO journal . When each SQL When updating the database , First of all, will REDO Log write to log buffer , When the client executes COMMIT When the command is submitted , The contents of the log buffer will be flushed to disk , The refresh method or time interval of the log buffer can be determined by the parameter innodb_flush_log_at_trx_commit control .
show variables like '%innodb_flush%';
REDO The log corresponds to... On the disk ib_logfileN file , This file defaults to 5MB, Recommended setting is 512MB To accommodate larger transactions . stay MySQL Crash recovery will be re executed REDO Records in the log .
stay mysql The database stores... In the directory ib_logfile0 and ib_logfile1 That is to say redo journal .
-- see mysql Database storage path
show variables like '%datadir%';
UNDO journal
And REDO Log opposite ,UNDO Logs are mainly used for data rollback in case of transaction exceptions , The specific content is to copy the database content before the transaction to UNDO buffer , Then refresh the content to disk at the right time .
And REDO The difference between logs is , There is no separate... On the disk UNDO Log files , be-all UNDO Logs are stored in the corresponding table space .ibd In the data file , Even if MYSQL The service enables independent tablespaces , It's still the same .UNDO Logs are also called rollback segments .
Transaction control statement
Grammar format :
START TRANSACTION | BEGIN [WORK]
COMMIT [WORK] [AND [NO] CHAIN ] [ [No] RELEASE]
ROLLBACK [WORK] [AND [NO] CHAIN] [ [NO] RELEASE]
SET AUTOCOMMIT = { 0 |1}
1、 Open transaction : start Transaction
Task one DML sentence (insert, update, delete ) perform , All mark the start of the transaction
command : START TRANSACTION perhaps BEGIN [WORK]
2、 Commit transaction : Commit Transaction
The end of success , Will all DML Statement operation history and degree layer hard disk data are synchronized at one time
Letter command :COMMIT
3、 Roll back the transaction : Rollback Transaction
The end of failure , Will all DML The statement operation history is cleared
command :Rollback
Example :
-- Create account table
create table account(
id int primary key,
name varchar(20),
money double
);
-- Insert data into the account table
insert into account values(1, 'litchi', 1000);
insert into account values(2, 'mango', 2000);
-- Query whether the event is automatically submitted ,1 For automatic submission
select @@autocommit;
-- Set up MYSQL The transaction is manually committed ( Turn off auto submit )
set autocommit = 0;
-- Analog transfer
-- Open transaction
begin;
update account set money = money - 500 where id = 1;
update account set money = money + 500 where id = 2;
-- Commit transaction
commit;
-- Roll back the transaction
rollback;
Transaction isolation level
MYSQL There are four isolation levels
- Uncommitted read READ UNCOMMITTED
- Submit to read , It can't be read repeatedly READ COMMITTED
- Repeatable REPEATABLE READ
- Serializable SERIALIZABLE
The default isolation level is : REPEATABLE-READ Repeatable
| Transaction isolation level | Dirty reading | It can't be read repeatedly | Fantasy reading |
|---|---|---|---|
| Uncommitted read READ UNCOMMITTED | yes | yes | yes |
| Submit to read , It can't be read repeatedly READ COMMITTED | no | yes | yes |
| Repeatable REPEATABLE READ | no | no | yes |
| Serializable SERIALIZABLE | no | no | no |
-- View the current MYSQL Transaction isolation level for
show variables like 'transaction_isolation';

You can set different isolation levels through the following statement
-- Uncommitted read
SET GLOBAL TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
-- Submit to read
SET GLOBAL TRANSACTION ISOLATION LEVEL READ COMMITTED;
-- Repeatable
SET GLOBAL TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-- Serializable
SET GLOBAL TRANSACTION ISOLATION LEVEL SERIALIZABLE;
READ UNCOMMITTED Read uncommitted content
In this isolation level , All transactions can see the results of other uncommitted transactions . Because its performance is not much higher than other levels , Therefore, this isolation level is rarely used in practical applications , Reading uncommitted data is called dirty reading (Dirty Read).
Example :
When a transaction B the update sentence , But before committing the transaction , Business A Transaction read B Updated value of . When a transaction B After rolling back , The amount data is restored to the value before modification ,A Dirty reading occurred in the transaction .

READ COMMITTED Read submissions , It can't be read repeatedly
This is the default isolation level for most database systems , But it is not MYSQL The default isolation level of .
This isolation level satisfies the simple definition of isolation : Any changes made by a transaction from start to commit are invisible , The transaction can only see the changes made by the committed transaction .
This isolation level also supports so-called non repeatable reads , Because other instances of the same transaction may New data submission will lead to data change , So the same query may Return different results .
Example :
First of all, open A and B Business ,A The transaction is queried for the first time because B The transaction has not yet been committed , So what you can find is the value before update , stay B After the transaction is committed ,A The transaction found the updated value ( At this time A Two queries in the transaction have different values , That is, non repeatable reading phenomenon )

REPEATABLE READ Repeatable
This is a MYSQL The default transaction isolation level of , It can ensure that multiple instances of the same transaction read data concurrently , You will see the same data lines .
In theory, it will lead to another problem , Fantasy reading . For example 1 A transaction modifies the data in a table , This modification involves all the data rows in the table . At the same time 2 A transaction also modifies the data in this table , This modification is to insert a new row of data into the table . that , Operation... Will occur later 1 The user of a transaction finds that there are still unmodified data rows in the table .
InnoDB and Falcon The storage engine uses multi version concurrency control mechanism (Multi_Version Concurrency Control, MVCC) This problem has been solved .
InnoDB Storage engine MBCC Mechanism :
InnoDB This is achieved by adding two implied values to each data row . This implied value records the creation time of the row , And the expiration date . Each line stores the system version number at the time of the event . Each time a new transaction is started, the version number will be automatically added 1, Each transaction will save the version number at the beginning , Each query will query the result according to the version number of the transaction .
Example :
First of all, open A and B Two transactions , stay B After the transaction is updated and committed ,A The transaction still reads the previous data , Ensure that the same transaction is read The data is consistent .
In the same transaction , Tables with different storage engines are not recommended ,COMMIT, ROLLBACK Only tables of the same transaction type can be committed and rolled back .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-oxGRyYcB-1644764114310)(/home/oscar/snap/typora/49/.config/Typora/typora-user-images/image-20220213222511211.png)]
MySQL All statements in cannot be rolled back , And partly DDL Statement will cause an implicit commit . such as :ALTER TABLE, TRUNCATE TABLE and DROP TABLE etc. .
SERIALIZABLE Serializable ( Serial number )
This is the highest level of isolation , By forcing transaction ordering , Make it impossible to conflict with each other , So as to solve the problem of unreal reading . The shared lock is added to each read data row . At this level, there will be a lot of timeout and lock competition , Generally not recommended .
Other descriptions of transaction isolation level :
this 4 The two transaction isolation levels are implemented with different lock types , If you read the same data , The following problems can easily occur .
Dirty reading (Drity Read): A transaction has updated a data , Another transaction reads the same data at this time , For some reason , The previous transaction was RollBack Rollback operation , Then the data read by the latter transaction may Is the updated data before rollback , It will cause the latter transaction to get the wrong data value .
It can't be read repeatedly (Non-repeatable read): Data inconsistency in two queries of a transaction , This may be possible. It is the update of a transaction inserted between the two query processes, which updates the original data .
Fantasy reading :
Extended data https://segmentfault.com/a/1190000016566788
Fantasy reading , It's not that the result sets obtained by two reads are different , Unreal reading focuses on one aspect or another select The data state represented by the result of the operation cannot support the subsequent business operation . More specifically :select Whether a record exists , non-existent , Ready to insert this record , But enforcement insert Found that this record already exists , Can't insert , At this time, the unreal reading happened .
Simulated the scene , Look at the example in the picture

InnoDB Locking mechanism
In order to solve the concurrency control problem of database , If at the same time , The client updates or queries the same table do , To ensure data consistency , Concurrent operations need to be controlled , So a lock . So is the lock MySQL Transaction isolation provides a guarantee .
The type of lock
Shared lock (S)
Code is S, yes Share Abbreviation , The lock granularity of shared locks is row or no group ( Multiple lines ). After a transaction obtains the shared lock , The data within the locked range can be read do .
Exclusive lock (X)
Code is X, yes eXclusive Abbreviation , The granularity of exclusive locks is the same as that of shared locks , It's also a line or tuple . After a transaction obtains an exclusive lock , You can write to the data within the locked range .
Intent locks
Intention lock is a kind of table lock , The granularity of locking is the whole table , Divided into intention sharing lock (IS) And intent exclusive lock (IX) Two types of .
边栏推荐
- 【load dataset】
- Recyclerview paging slide
- Error modulenotfounderror: no module named 'cv2 aruco‘
- Linux安装部署LAMP(Apache+MySQL+PHP)
- [calculation of loss in yolov3]
- Hiengine: comparable to the local cloud native memory database engine
- 图像超分实验:SRCNN/FSRCNN
- JS for循环 循环次数异常
- Matlab struct function (structure array)
- Principle and performance analysis of lepton lossless compression
猜你喜欢

Seven ways to achieve vertical centering

【SingleShotMultiBoxDetector(SSD,单步多框目标检测)】
自动化测试生命周期
Two minutes will take you to quickly master the project structure, resources, dependencies and localization of flutter
Automated test lifecycle

查看rancher中debug端口信息,并做IDEA Remote Jvm Debug

The evolution of mobile cross platform technology
![[pytorch pre training model modification, addition and deletion of specific layers]](/img/cb/aa0b1116ec9b98e3ee5725aa58f4fe.png)
[pytorch pre training model modification, addition and deletion of specific layers]
Take you two minutes to quickly master the route and navigation of flutter

Master the new features of fluent 2.10
随机推荐
MySQL installation, Windows version
Matlab boundarymask function (find the boundary of the divided area)
PXE启动配置及原理
只是巧合?苹果 iOS16 的神秘技术竟然与中国企业 5 年前产品一致!
【TFLite, ONNX, CoreML, TensorRT Export】
Open3d European clustering
byte2String、string2Byte
Four operations and derivative operations of MATLAB polynomials
IPv6与IPv4的区别 网信办等三部推进IPv6规模部署
abap查表程序
Hiengine: comparable to the local cloud native memory database engine
Matlab struct function (structure array)
调查显示传统数据安全工具在60%情况下无法抵御勒索软件攻击
Why learn harmonyos and how to get started quickly?
多表操作-子查询
How can beginners learn flutter efficiently?
Hash tag usage in redis cluster
Semantic segmentation experiment: UNET network /msrc2 dataset
Intern position selection and simplified career development planning in Internet companies
【主流Nivida显卡深度学习/强化学习/AI算力汇总】