[MySQL] transaction

1 Introduction

Transaction is a very important concept in database management system. This article mainly introduces the four characteristics of transaction, the possible problems caused by concurrent transaction and the isolation level of transaction.

2. Business Introduction

A transaction is a collection of operations. It is an indivisible unit of work. A transaction will submit or revoke operation requests to the system as a whole, that is, these operations either succeed or fail at the same time .

A typical case of transaction usage scenarios is transfer. Any mistakes in transfer are not allowed, and a little bit will cause huge losses. For example, user A transfers 200 yuan to user B at this time. Then the operation performed in the database is to let User A's balance is reduced by 200, and user B's balance is increased by 200.

If you do not use transactions, the following problems may occur: after the balance of user A is reduced by 200, when the database is executed to add 200 to the balance of user B, the database hangs or an abnormal situation occurs. At this time, the balance of user B does not Add 200. Then A will lose 200 yuan for no reason. At this time, the problem is very big.
But if the transaction is used, the balance of user A is reduced by 200, and the balance of user B is increased by 200. These two operations are a whole. The result is Two, either succeed or fail. Then the above problems can be easily dealt with. If the above problems occur, then the database will roll back the transaction at this time, which can be understood as an undo operation. Restore the data Before data execution. This shows the importance of transactions.

3. Transaction operations

There are three main operations for transaction operations: open a transaction, commit a transaction, and roll back a transaction.

There are three ways to start a transaction in MySQL:

使用 BEGIN语句可以手动开启
使用 SET AUTOCOMMIT=0/1 语句(0为手动提交,1为默认提交)
使用 START TRANSACTION语句

Commit and rollback transactions:

COMMIT; # 提交事务
ROLLBACK; # 回滚事务

MySQL's transactions are committed by default, that is, when a DML statement is executed, MySQL will implicitly commit the transaction.

Take the transfer example just mentioned: In fact, the main step is to modify the balance of user A and user B in two steps. Of course, if you are pursuing rigor, you can judge whether the balance is greater than the transfer amount before the transfer. I will not here Written.
The balance of user A and user B in the initial state:
insert image description here
Next, we use transactions to deal with the above-mentioned problems that may arise during database execution:
insert image description here
for example, I changed the SQL statement to a wrong one here to simulate a database error situation.
After execution After the SQL statement, we see that the balance of user A has changed. But the balance of user B has not changed.
insert image description here
At this time, the data has been wrong. We will roll back the transaction to restore the data.
insert image description here
After rolling back the transaction, we can see The data of user A and user B has been restored to the data before modification.

4. Four characteristics of transactions

Transactions have the following four properties, also known as ACID properties:

  1. Atomicity : A transaction is an atomic operation and cannot be divided. All steps of the operation are either all completed or not completed, and there will be no partial completion. If any operation fails, the transaction will be rolled back to the state before it started, and all modified data will be undone.

  2. Consistency : Before and after the execution of the transaction, the state of the database must be consistent . The database state before transaction execution is a legal state, and the database state after execution must also be a legal state. In other words, there will be no contradictions and conflicts during transaction execution, ensuring the integrity and correctness of data.

  3. Isolation : When multiple transactions are executed concurrently , the operations of each transaction should be isolated from the operations of other transactions without interfering with each other . The modifications made by each office must be independent of the modifications made by other offices, so that there will be no mutual interference. It is guaranteed that each transaction is executed independently without causing concurrency problems.

  4. Durability : Once a transaction is committed , its modifications will be permanently saved in the database, and will not be lost even if the system crashes. Data persistence ensures that transaction commit results will not be revoked, and can be recovered even in the event of system failure or crash.

The four characteristics of transactions ensure the reliability, consistency and durability of the database operation process, and are an important means to ensure data integrity and correctness.

5. Problems with concurrent transactions

Transactions are the basic unit of concurrency control , and concurrent transactions may destroy the ACID characteristics of transactions. Concurrent transactions may have the following three problems:

  • Dirty read : Dirty read means that a transaction reads uncommitted data when it reads the data of another uncommitted transaction. If another transaction rolls back, the data read by this transaction is invalid. Dirty reads can lead to data inconsistency.
  • Non-repeatable read : Non-repeatable read means that one transaction reads the same set of data multiple times, but during this period, another transaction updates this set of data, resulting in inconsistency in the data read twice by the first transaction. Non-repeatable reads can lead to data inconsistency.
  • Phantom reading : Phantom reading means that after one transaction reads a set of data, another transaction inserts a new piece of data, causing the first transaction to read the same set of data again and find that the data has increased by one piece, thus creating an illusion . Phantom reads can lead to data inconsistency.

The above three problems are caused by the concurrent execution of multiple transactions. The solutions to these problems include:

  1. Locking : By locking the shared data, each transaction's access to the shared data is guaranteed to be mutually exclusive, solving the problems of dirty reads and non-repeatable reads.
  2. MVCC (Multi-Version Concurrency Control) : By recording the version information of the data in the view of each transaction, the data read by each transaction is guaranteed to be consistent, and the problems of non-repeatable reads and phantom reads are solved.
  3. Serialization : By executing concurrent transactions serially, each transaction is guaranteed to be executed independently without concurrency issues. But serialization will reduce the concurrency and throughput of the system, so it is not suitable for high concurrency scenarios.

6. Transaction isolation level

The isolation level of a transaction refers to the degree of isolation between multiple concurrent transactions. MySQL supports 4 isolation levels, from low to high:

  1. Read Uncommitted (Read Uncommitted): The lowest isolation level that allows one transaction to read data uncommitted by another transaction, which may cause dirty reads, non-repeatable reads, and phantom reads.

  2. Read Committed (Read Committed): Allows a transaction to read data committed by another transaction, avoiding dirty read problems , but may still cause non-repeatable read and phantom read problems.

  3. Repeatable Read (Repeatable Read): Ensure that when the same set of data is read multiple times in the same transaction, the read data is always consistent, avoiding dirty reads and non-repeatable reads , but may still cause phantom reads.

  4. Serializable: The highest isolation level, which avoids all concurrency problems by executing concurrent transactions serially , but leads to performance degradation.

isolation level dirty read non-repeatable read Serialization
Read Uncommitted
Read Committed ×
Repeatable Read × ×
Serializable × × ×

View transaction isolation level:

select @@transaction_isolatio;

Set the isolation level of the transaction:

SET [SESSION/GLOBAL] TRANSACTION ISOLATION LEVEL <隔离级别>;
# SESSION: 针对当前的会话窗口有效
# GLOBAL: 对所有客户端的会话窗口有效

The higher the isolation level, the higher the degree of isolation from each other, but it can also lead to problems such as performance degradation and deadlocks . In practical applications, it is necessary to select an appropriate isolation level according to different business requirements and system performance. MySQL's default isolation level is Repeatable Read.

7. Summary

Transactions are very important to the correctness, reliability, integrity and security of database management systems, and are the key means to ensure data quality. Understand the problems that may be caused by concurrent transactions and what these problems mean, and learn to reasonably set the isolation level of transactions to deal with the problems that may be caused by concurrent transactions.

Thank you for watching! I hope this article can help you!
Column: "Speedthrough MySQL" is constantly being updated, welcome to subscribe!
"Wish to encourage you and make progress hand in hand!"
insert image description here

Guess you like

Origin blog.csdn.net/m0_63463510/article/details/130534523