[MySQL database | Article 15] Transaction

 

 

c6e9b8cdd80f447a9d5b085ec88483be.png

Table of contents

 

 Foreword:

 Introduce business:

 Control transactions:

 Four characteristics of transactions:

 Concurrent transaction issues:

 Transaction isolation level:

Summarize:


 

 Foreword:

In this chapter, we will enter the last chapter of MySQL Basics: Transactions. I hope you can persevere and follow me through the MySQL learning journey.

 Introduce business:

MySQL is a relational database management system that supports transaction management. A transaction is a set of database operations that are performed in a specific order and either all commit successfully or all fail and roll back . In MySQL, transactions can be used to ensure data integrity and consistency.

In MySQL, by using transactions, operations on data can be guaranteed to be reliable and safe. When complex operations are performed on data, the use of transactions can ensure that a set of operations succeed or fail, preventing data inconsistency.

Example:
49300c92f5364096a8f842eb68911d58.png

Bank transfer is a typical transaction. If Zhang San wants to remit money to Li Si, then we can't deduct 1,000 yuan to Zhang San and transfer 1,000 yuan to Li Si separately, because even if Zhang San does not have 1,000 yuan, we will transfer money to Li Si. Therefore, we should organize these two operations into one operation: first deduct money from Zhang San, and if the deduction is successful, remit money to Li Si, so that if Zhang San does not have enough money, we can interrupt the operation in time, and we integrate multiple operations together to execute it. This is called defining a transaction.

MySQL transactions are automatically committed by default, that is to say: when a DML statement is executed, MySQL will immediately and implicitly commit the transaction.

Control transactions:

  • Start transaction (BEGIN): It is used to specify the start of a transaction, and all subsequent operations belong to the same transaction scope.
  • Commit transaction (COMMIT): It is used to submit a transaction to the database, indicating that all modification operations of the transaction have been completed, the data has been persisted, and the execution of the transaction has been completed.
  • Rollback transaction (ROLLBACK): used to undo all modification operations that occurred in a transaction, so that the data returns to the state before the transaction started. When a transaction cannot be completed, all changes made by the transaction need to be undone.

1. View/set transaction submission method

SELECT @@ autocommit;//查询当前事务提交状态
SET @@ cutocommit =0;//1  自动提交   0    手动提交

2. Submit the transaction

COMMIT;

3. Roll back the transaction

ROLLBACK;

Control transaction case:

1. Control the transaction by modifying the method of transaction submission

We can demonstrate the bank example just mentioned through code:
the initial state of two people:
2378713ea5704f09b3ae967164e0dd41.png

We modify the transaction submission method to perform the transfer operation after manual submission:

select @@autocommit;
set @@autocommit =0;
-- 1. 查询张三余额
select * from account where name = '张三';
-- 2. 张三的余额减少1000
update account set money = money - 1000 where name = '张三';
-- 3. 李四的余额增加1000
update account set money = money + 1000 where name = '李四';

 If we execute these statements at this time:
the result:
704b22a5900a421cadd28ead911d34fe.png

This is because we set the transaction submission method to manual submission, so that the system will not submit the transaction to the database when executing the statement.

Commit the transaction (commit):

select @@autocommit;
set @@autocommit =0;
-- 1. 查询张三余额
select * from account where name = '张三';
-- 2. 张三的余额减少1000
update account set money = money - 1000 where name = '张三';
-- 3. 李四的余额增加1000
update account set money = money + 1000 where name = '李四';

commit;

result:

0285d4c3053945b4aaa6066604a3b599.png

It should be noted that if we continue to execute operations without committing the transaction, we cannot think that these operations have not been executed, but they are stored in the pending operations. As long as we commit the transaction, these operations will be executed one by one:
 4d76fe505e5547c48e3f0f9a33ffa688.png

Proof: We try to execute the statement without submitting for the first time, and execute the statement and submit for the second time

Operation result:

cf2561af24f2475bb6a85de526283581.png

2. Do not modify the transaction submission method to operate the transaction:

1. Open the transaction

START TRANSACTION 或 BEGIN;

2. Submit the transaction

COMMIT;

3. Roll back the transaction

ROLLBACK;

code: 

START TRANSACTION ;

select * from account where name = '张三';

update account set money = money - 1000 where name = '张三';

update account set money = money + 1000 where name = '李四';

COMMIT ;

result:
07ed118ca8cb4eb78809e1cd9ee770f9.png

 Four characteristics of transactions:

  1. Atomicity : In a transaction, either all operations are successfully submitted, or all operations are rolled back to the state before the transaction started, ensuring the atomicity of operations.

  2. Consistency : After the transaction execution ends, the data should maintain a consistent state, regardless of whether the transaction execution succeeds or fails, the database should meet the predefined integrity constraints.

  3. Isolation : During the execution of a transaction, it will not be interfered by other concurrent transactions, which ensures the isolation of the transaction.

  4. Durability : After a transaction is committed, its modifications will be permanently saved in the database.

Concurrent transaction issues:

1. Dirty Read : A transaction reads data that has not been committed by another transaction. If that transaction rolls back or modifies the data, it may cause data inconsistency.

2. Non-repeatable read (Non-repeatable Read) : When a transaction reads a piece of data multiple times, because the data is modified by other transactions, it reads different results multiple times. In this case, the first transaction may think that the data has been modified multiple times, but in fact it is only modified by one transaction.

3. Phantom Read: When a transaction reads a set of data multiple times, it reads different data rows because other transactions insert new data. In this case, the first transaction may think that the data has been modified or deleted, but in fact only new rows are inserted.

The solution to these problems is usually to lock or use a higher transaction isolation level. For example:

1. Avoid dirty reads and non-repeatable reads by locking when reading data, such as using row locks or table locks.

2. Increase the transaction isolation level, such as upgrading to the repeatable read level, which prevents non-repeatable reads, but cannot completely avoid phantom reads.

3. Use a higher isolation level, such as serialization, which can avoid dirty reads, non-repeatable reads, and phantom reads at the same time, but it will also have a certain impact on performance.

It is necessary to select an appropriate solution based on specific business scenarios, data types, and access modes to ensure data consistency and reliability.

Transaction isolation level:

  1. Read Uncommitted (Read Uncommitted): A transaction can read data in another uncommitted transaction. This level of isolation is the lowest, and there will be problems of dirty reads, non-repeatability, and phantom reads. It has the largest amount of concurrency and the best performance.

  2. Read Committed (Read Committed): read the changed data submitted by another concurrent transaction, and lock when reading, so dirty reading can be avoided to a certain extent. However, because it is based on read uncommitted, problems of non-repeatable reads and phantom reads may still occur.

  3. Repeatable Read (Repeatable Read): When the same record is read multiple times in a transaction, it can ensure that the read data is the same. This level locks the read data at the row level to avoid non-repeatable reads, but phantom reads may still occur.

  4. Serializable: All transactions are executed sequentially, that is, sequentially and cannot be executed concurrently, so as to ensure the highest level of isolation and data consistency under the isolation level. Is the safest transaction isolation level, but the worst concurrency, the lowest performance.

       Repeatable Read is MySQL's default transaction isolation level

 grammar:

1. View the current transaction isolation level

SELECT @@TRANSACTION_ISOLATION;

2. Set the transaction isolation level

SET [SESSION | GLOBAL] TRANSACTION ISOLATION LEVEL {隔离级别};

The difference between SESSION and GLOBAL:

  • SESSION refers to setting the isolation level on the current client
  • GLOBAL refers to setting the isolation level on all clients.

 

Summarize:

        In this film, we introduced transactions and transaction submission issues. This is the end of the basic article on MySQL database. In the next article, I will explain in detail what dirty reads, phantom reads, and non-repeatable reads are . Then the advanced chapter will be continuously updated, that is, the optimization of various statements. Welcome to continue reading.

 

This is the end of today's content, thank you for reading.

If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!

8ec5ca9680024c9ca2ac25b357ec4821.png  

 

Guess you like

Origin blog.csdn.net/fckbb/article/details/131118338