The concepts and characteristics of mysql database transactions and the syntax and process of executing transactions in MySQL

Database transaction concepts and characteristics

A database transaction is a mechanism, an operation sequence, and includes a set of database operation commands. A transaction submits or revokes an operation request to the system together with all commands as a whole, that is, this set of database commands are either executed or not executed, so the transaction is an indivisible logical unit of work.

When performing concurrent operations on a database system, transactions are used as the smallest control unit, which is especially suitable for database systems operated by multiple users at the same time. For example, airline booking systems, banks, insurance companies, and securities trading systems.

Transactions have four characteristics, namely atomicity, consistency, isolation and durability. These four characteristics are usually referred to as ACID.

1. Atomicity

A transaction is a complete operation. The elements of a transaction are indivisible (atomic). All elements in the transaction must be committed or rolled back as a whole. If any element in the transaction fails, the entire transaction fails.

Taking the bank transfer transaction as an example, if the transaction is submitted, the data of the two accounts will be updated. If for some reason the transaction terminates before successfully updating both accounts, the balances of both accounts will not be updated, modifications to any account balances will be undone, and the transaction cannot be partially committed.

2. Consistency

When the transaction completes, the data must be in a consistent state. That is, the data stored in the database is in a consistent state before the transaction begins. During an ongoing transaction, the data may be in an inconsistent state, for example, the data may be partially modified. However, when the transaction completes successfully, the data must be returned to a known consistent state again. Modifications made to data through transactions cannot damage the data, or transactions cannot leave the data storage in an unstable state.

Take the bank transfer transaction as an example. Before the transaction begins, the total of all account balances is in a consistent state. During the course of the transaction, the balance of one account is reduced, while the balance of the other account has not been modified. Therefore, the total of all account balances is inconsistent. After the transaction is completed, the total account balance is restored to a consistent state again.

3. Isolation

All concurrent transactions that modify data are isolated from each other, which means that transactions must be independent and should not depend on or affect other transactions in any way. A transaction that modifies data can access the data before another transaction that uses the same data begins, or after another transaction that uses the same data ends.

In addition, when a transaction modifies data, if any other process is using the same data at the same time, the modifications to the data will not take effect until the transaction is successfully committed. The transfer between Zhang San and Li Si and the transfer between Wang Wu and Zhao Er are always independent of each other.

4. Durability

Transaction durability means that regardless of whether the system fails, the results of transaction processing are permanent.

After a transaction completes successfully, the changes it makes to the database are permanent, even if the system fails. That is to say, once the transaction is committed, any changes made to the data by the transaction will be permanently retained in the database.

The ACID principle of transactions ensures that a transaction is either successfully committed or failed and rolled back, or one of the two. Therefore, its modifications to the transaction are recoverable. That is, when a transaction fails, its data modifications will be restored to the state before the transaction was executed.

MySQL transaction execution syntax and process

MySQL provides multiple storage engines to support transactions. Storage engines that support transactions include InnoDB and BDB. InnoDB storage engine transactions are mainly implemented through UNDO logs and REDO logs. MyISAM storage engine does not support transactions.

Expansion: Any kind of database will have various logs to record the running status, daily operations, error messages, etc. of the database, and MySQL is no exception. For example, when user root logs in to the MySQL server, the user's login time, execution operations, etc. will be recorded in the log file.

In order to maintain the MySQL server, it is often necessary to perform log operations in the MySQL database:

  • UNDO log: Copies the data before the transaction is executed and is used to roll back the data when an exception occurs in the transaction.
  • REDO log: records every operation that updates data during transaction execution. When the transaction is committed, the content will be flushed to disk.

Mysql database basic skills full practice icon-default.png?t=N7T8https://edu.csdn.net/course/detail/36210
Under the default settings, each SQL statement is a transaction, that is, it is automatically submitted after executing the SQL statement. In order to combine several operations as a whole, you need to use BEGIN or START TRANSACTION to start a transaction, or disable automatic submission of the current session.

For information about the automatic submission of transactions, you can read the section  " MySQL Setting Automatic Transaction Submission ".

Syntax and process for executing transactions

SQL uses the following statements to manage transactions.

1) Start transaction
BEGIN;

 or

START TRANSACTION;

This statement explicitly marks the starting point of a transaction.

2) Submit transaction

MySQL uses the following statement to commit a transaction:

COMMIT;

COMMIT means committing a transaction, that is, committing all operations of the transaction. Specifically, all updates to the database in the transaction are written to the physical database on the disk, and the transaction ends normally.

Committing a transaction means that all data executed since the beginning of the transaction will be modified and become a permanent part of the database, thus also marking the end of a transaction. Once this command is executed, the transaction cannot be rolled back. This operation is performed only when all modifications are ready to be committed to the database.

3) Rollback (undo) transaction

MySQL rolls back the transaction using the following statement:

ROLLBACK;

ROLLBACK means to cancel the transaction, that is, some kind of failure occurs during the transaction running and the transaction cannot continue to be executed. The system will undo all completed operations on the database in the transaction and roll back to the state at the beginning of the transaction. The operation here refers to the update operation on the database.

When an error is encountered during transaction execution, use the ROLLBACK statement to roll the transaction back to the starting point or a specified hold point. At the same time, the system will clear all data modifications made from the starting point of the transaction or to a certain save point, and release the resources controlled by the transaction. Therefore, this statement also marks the end of the transaction.

Summarize

The update operations of the database data by the SQL statements following the BEGIN or START TRANSACTION statement will be recorded in the transaction log until the ROLLBACK statement or COMMIT statement is encountered. If an operation in the transaction fails and a ROLLBACK statement is executed, all updated data after opening the transaction statement can be rolled back to the state before the transaction started. If all operations in the transaction are completed correctly and the COMMIT statement is used to submit updated data to the database, the data at this time is in a new consistent state.

Example demonstration

Below are two examples to demonstrate the specific usage of MySQL transactions.

Example 1

The following simulates the scenario where other sessions access the data table after Zhang San's account decreases by 500 yuan but Li Si's account has not increased by 500 yuan. Since the code needs to be executed in two windows, for the convenience of reading, we call them A window and B window here.

1) Open a transaction in window A and update the data of the bank table in the mybank database. The SQL statement and running results are as follows:

mysql> USE mybank;
Database changed
mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)
mysql> UPDATE bank SET currentMoney = currentMoney-500
    -> WHERE customerName='张三';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1  Changed: 1  Warnings: 0

2) Query the data in the bank data table in window B. The SQL statement and running results are as follows:

mysql> SELECT * FROM mybank.bank;
+--------------+--------------+
| customerName | currentMoney |
+--------------+--------------+
| 张三         |      1000.00 |
| 李四         |         1.00 |
+--------------+--------------+
2 rows in set (0.00 sec)

It can be seen from the results that although the transaction in window A has changed the data in the bank table, the data is not updated immediately. At this time, other sessions still read the data before the update.

3) Continue to execute the transaction in window A and submit the transaction. The SQL statement and running results are as follows:

mysql> UPDATE bank SET currentMoney = currentMoney+500
    -> WHERE customerName='李四';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1  Changed: 1  Warnings: 0
mysql> COMMIT;
Query OK, 0 rows affected (0.07 sec)

4) Query the data of the bank data table again in window B. The SQL statement and running results are as follows:

mysql> SELECT * FROM mybank.bank;
+--------------+--------------+
| customerName | currentMoney |
+--------------+--------------+
| 张三         |       500.00 |
| 李四         |       501.00 |
+--------------+--------------+
2 rows in set (0.00 sec)

After executing COMMIT to commit the transaction in window A, the updates to the data will be submitted together, and other sessions will read the updated data. It can be seen from the results that the total account balance of Zhang San and Li Si remains consistent with that before the transfer, so that the data is updated from one consistency state to another.

As mentioned earlier, when a problem occurs during transaction execution, that is, when a complete transaction cannot be executed according to the normal process, you can use the ROLLBACK statement to roll back and use the data to restore to the initial state.

In Example 1, Zhang San's account balance has been reduced to 500 yuan. If another 1,000 yuan is transferred out, the balance will be negative, so it needs to be rolled back to the original state. As shown in Example 2.

Example 2

Reduce Zhang San's account balance by 1,000 yuan and roll back the transaction. The SQL statement and running results are as follows:

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)
 
mysql> UPDATE bank SET currentMoney = currentMoney-1000 WHERE customerName='张三';
Query OK, 1 row affected (0.04 sec)
Rows matched: 1  Changed: 1  Warnings: 0
 
mysql> ROLLBACK;
Query OK, 0 rows affected (0.07 sec)
 
mysql> SELECT * FROM mybank.bank;
+--------------+--------------+
| customerName | currentMoney |
+--------------+--------------+
| 张三         |       500.00 |
| 李四         |       501.00 |
+--------------+--------------+
2 rows in set (0.00 sec)

It can be seen from the results that after executing the transaction rollback, the account data is restored to the initial state, that is, the state before the transaction was executed.

expand

In database operations, in order to effectively ensure the correctness of concurrently read data, the isolation level of transactions is proposed. In the demonstrations of Example 1 and Example 2, the isolation level of the transaction is the default isolation level. In MySQL, the default isolation level of a transaction is REPEATABLE-READ (rereadable) isolation level, that is, when the transaction is not ended (COMMIT or ROLLBACK is not executed), other sessions can only read uncommitted data.

Please click on MySQL Transaction Isolation Levels to learn more.

Precautions

MySQL transaction is a very resource-consuming function. You should pay attention to the following points when using it.

1) Keep transactions as short as possible

From the start to the end of a transaction, a large amount of resources will be reserved in the database management system to ensure the atomicity, consistency, isolation, and durability of the transaction. If in a multi-user system, large transactions will occupy a large amount of system resources, making the system overwhelmed, affecting the running performance of the software, and even causing the system to crash.

2) The amount of data accessed in the transaction should be minimized.

When transactions are executed concurrently, the smaller the amount of data the transaction operates on, the fewer operations on the same data between transactions.

3) Try not to use transactions when querying data

Browsing and querying data will not update the data in the database, so you should try not to use transactions to query data to avoid occupying excessive system resources.

4) Try not to wait for user input during transaction processing.

During transaction processing, if you need to wait for the user to input data, the transaction will occupy resources for a long time and may cause system congestion.

Dachang senior database engineer mysql database practical training icon-default.png?t=N7T8https://edu.csdn.net/course/detail/39021 

Guess you like

Origin blog.csdn.net/m0_37449634/article/details/135554108