MySQL transaction and lock mechanism


Tip: The following is the content of the main text of this article, and the series of MySQL learning will continue to be updated

insert image description here

1. Affairs

  • In the database, we hope that some operations can be performed in an atomic manner, either they can be executed successfully, or they are not executed, that is, they can only be executed as a whole. We call such a group of atomic operations It is business .
  • Our MySQL supports 9 database engines, but only the default Innodbengine supports transaction functions.

1.1 Transaction characteristics

  • Atomicity : A transaction is an indivisible unit of work, and the operations included in the transaction are either done or not done.
  • Consistency : A transaction must change the database from one consistent state to another. The integrity of the database is not compromised before the transaction begins and after the transaction ends.
  • Isolation : When multiple transactions operate on the same resource at the same time, the execution of one transaction cannot be interfered by other transactions. The simultaneity here is only a macroscopic performance, in fact, only one transaction is executing at the same time on the microscopic level, while other transactions are waiting.
  • Durability : Once a transaction is committed, its changes to the data in the database should be permanent, even if the system fails, it will not be lost.

1.2 Isolation level

More pursuit of isolation (data is more correct) ----------------------------- ------------------------------------------------ ---------------------------------> More pursuit of concurrency (higher performance)
(serializability)
serializable
(snapshot read)
snapshot_read
(repeatable read)
repeatable_read
(read committed)
read_committed
(read uncommitted)
read_uncommitted

This is the highest isolation level, and it solves phantom reads by enforcing the ordering of transactions so that they cannot conflict with each other. In short, it adds a shared lock on each data row read . At this level, a large number of timeouts and lock contention can result.



Not an isolation level that exists in the standard, and currently, has no side effects.
Repeatable reads in MySQL are actually snapshot reads. Because the MVCC mechanism solves phantom reading .


This is MySQL's default transaction isolation level, which ensures that multiple instances of the same transaction will see the same data rows when they read data concurrently . This causes a phantom read : 当用户修改某一范围的数据行时,另一个事务又在该范围内插入了新行,当用户再读取该范围的数据行时,会发现有一条未修改的数据“幻影”. It can only read the content that has been submitted by other transactions , and there is a non-repeatable read problem: 一个事务多次读取同一数据可能会得到多个不同的结果.



It can read uncommitted content in other transactions , and there is a problem of dirty reading. Read uncommitted data, also called 脏读.




We can modify the isolation level:

set session transaction isolation level read uncommitted;

back to content...

1.3 Start a transaction

①SQL opens the transaction

-- 开启事务
start transaction; / begin;
SQL1;
SQL2;
rollback; -- 主动回滚

-- 开启事务
start transaction; / begin;
SQL1;
SQL2;
SQL3;
commit; -- 提交事务,失败也会回滚

②JDBC use transaction

// 要使用事务,在同一个事务中,操作 sql1 和 sql2,意味着必须在一条 Connection 完成
try (Connection c = DBUtil.connection()) {
    
    
    // connection 中有一个自动提交(autocommit)的属性,默认情况下是 true(开启)
    // 开启状态下,意味着,每一条 sql 都会被独立的视为一个事务
    // 我们要让 sql1 和 sql2 看作整体,只需要关闭 connection 的自动提交
    c.setAutoCommit(false);
    // 此时就可以手动的控制事务的结束位置,并且需要手动提交

    try (PreparedStatement ps = c.prepareStatement(sql1)) {
    
    
        ps.executeUpdate();
    }

    try (PreparedStatement ps = c.prepareStatement(sql2)) {
    
    
        ps.executeUpdate();
    }

    // 由于我们关闭了自动提交了,所以,所有的修改还没有真正地落盘
    c.commit();     // 只有加上这句话,才表示事务被提交了(数据真正落盘了)
}

back to content...

2. Lock mechanism

We know that at the level of repeatable reading, MySQL solves the phantom reading problem to a certain extent:

  • In the case of snapshot reads (without locks), mysql uses MVCC (multi-version concurrency control) to avoid phantom reads.
  • In the current read (locked) read situation, mysql uses next-key to avoid phantom reading.

2.1 Read lock, write lock

In terms of the type of operation on data, locks are divided into read locks and write locks:

  • Read lock : It is also called a shared lock. When a transaction adds a read lock, other transactions can also add a read lock or read data, but they cannot perform write operations. They can only wait until all the read locks are released.
  • Write lock : also called an exclusive lock. When a transaction adds a write lock, other transactions cannot read, write, or add any locks. They can only wait for the current transaction to release the lock.

2.2 Global locks, table locks, row locks

Divided from the scope of the lock, it is divided into global locks, table locks and row locks:

①Global lock : The lock acts globally, and all operations of the entire database are restricted by the lock.

flush tables with read lock;

②Table lock : The lock acts on the entire table, and all operations on the table will be restricted by the lock.

lock table 表名称 read; -- 读锁
lock table 表名称 write; -- 写锁

-- 除了手动释放锁之外,当我们的会话结束后,锁也会被自动释放。
unlock tables;

③Row lock : The lock acts on a certain row in the table, and only restricts the operation of a certain row through the lock (only supported by InnoDB)

-- 添加读锁(共享锁)
select * from 表名 where ... lock in share mode;
-- 添加写锁(排他锁)
select * from 表名 where ... for update;

back to content...

2.3 Record locks, gap locks, and key locks

We know that InnoDB supports the use of row locks , but row locks are more complicated. They can be further divided into multiple types. For details, please refer to the article: MySQL's lock mechanism-record locks, gap locks, and key locks

①Record Locks (Record Locks): Only one row of index records is locked, and a single index record is locked. Record lock always locks the index, not the record itself. Therefore, when a sql does not use any index, a write lock will be added behind each aggregated index. This is similar to a table lock, but in principle it should be completely different from a table lock.

  • The id column must be a unique index column or a primary key column, otherwise the added lock will become a temporary key lock.
  • At the same time, the query statement must be an exact match (=), not >, <, like, etc., otherwise it will degenerate into a temporary key lock.

②Gap Locks: Only lock an index interval (open interval). Lock in the gap between index records, or lock before or after an index record, not including the index record itself. For example, in 1 and 2, the possible values ​​of gap locks are (-∞, 1), (1, 2), (2, +∞). Gap locks can be used to prevent phantom reading and ensure that data will not be inserted between indexes .

  • For the primary key index: precise query for existing columns will only generate record locks; precise query for non-existent columns will generate record locks and gap locks; range query will generate gap locks.
  • For ordinary indexes: no matter what kind of query, as long as the lock is added, a gap lock will be generated.
    insert image description here

③Next -Key Locks: Record lock + Gap lock , open left and close right . By default, InnoDB uses exactly Next-key Locks to lock records (eg select … for update.

It will also flexibly transform according to the scene:

Scenes convert
Exact match using unique index, but record does not exist in the table Automatic conversion to Gap Locks
Use a unique index for an exact match and a record exists in the table Automatic conversion to Record Locks
Use non-unique index for exact match do not convert
Range matching using unique indexes Do not convert, but only lock the upper bound, not the lower bound

back to content...


Summary :
Tip: Here is a summary of the article:
This article is a study of MySQL. First, I learned the four characteristics of transactions, isolation levels, and how to start transactions. I also learned the lock mechanism, and learned about read-write locks, row table locks, record locks, etc. The following learning content will continue to be updated! ! !

Guess you like

Origin blog.csdn.net/qq15035899256/article/details/130003231