当前位置:网站首页>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 .
边栏推荐
- IPv6与IPv4的区别 网信办等三部推进IPv6规模部署
- The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix
- pytorch-权重衰退(weight decay)和丢弃法(dropout)
- Time tools
- Semantic segmentation experiment: UNET network /msrc2 dataset
- 语义分割实验:Unet网络/MSRC2数据集
- Open3d European clustering
- Design of music box based on assembly language
- 【Win11 多用户同时登录远程桌面配置方法】
- 想问问,如何选择券商?在线开户是很安全么?
猜你喜欢
Simply solve the problem that the node in the redis cluster cannot read data (error) moved
Codeworks 5 questions per day (1700 average) - day 5
[yolov5.yaml parsing]
Simple production of wechat applet cloud development authorization login
Multi table operation - sub query
Reading notes of growth hacker
pytorch-多层感知机MLP
Matlab superpixels function (2D super pixel over segmentation of image)
[yolov3 loss function]
How can beginners learn flutter efficiently?
随机推荐
Image hyperspectral experiment: srcnn/fsrcnn
Redis cluster (master-slave) brain crack and solution
The survey shows that traditional data security tools cannot resist blackmail software attacks in 60% of cases
Open3d European clustering
信息服务器怎么恢复,服务器数据恢复怎么弄[通俗易懂]
Read and understand the rendering mechanism and principle of flutter's three trees
SENT协议译码的深入探讨
Get all stock data of big a
Proof of the thinking of Hanoi Tower problem
What is the difference between canvas and SVG?
Codeforces Round #804 (Div. 2)
【 YOLOv3中Loss部分计算】
[configuration method of win11 multi-user simultaneous login remote desktop]
一款新型的智能家居WiFi选择方案——SimpleWiFi在无线智能家居中的应用
【SingleShotMultiBoxDetector(SSD,单步多框目标检测)】
Splunk configuration 163 mailbox alarm
Principle of persistence mechanism of redis
【load dataset】
【yolov3损失函数】
1. Laravel creation project of PHP