12. Transaction Control

1. Introduction
Transaction (Transaction) refers to a series of operations performed as a logical unit of work, these operations either all succeed or all fail. The transaction ensures that the modification of multiple data is processed as a unit.
For example, Zhang San transfers 100 yuan to Li Si on an ATM machine. In the bank's business system, two steps of data change operations are mainly performed. One is to subtract 100 yuan from Zhang San's account, and the other is to add 100 yuan to Li Si's account. Let me ask, what happens if operation 1 is executed successfully and operation 2 fails? At this time, transaction control is needed to avoid such a situation.

In MySQL, only databases or tables that use the Innodb storage engine support transactions.
Transactions are used to maintain the integrity of the database to ensure that batches of SQL statements are either executed or not executed.
The transaction is used to manage insert, update and delete statements.

2. Features
If a database claims to support transactions, then the database must have four ACID features, namely Atomicity (atomicity), Consistency (consistency), Isolation (isolation) and Durability (persistence).

  • Atomicity: The transaction must be an atomic unit of work. All operations contained in the transaction are either done or not done.
  • Consistency: When the transaction is completed, all data must be kept in a consistent state.
  • Isolation: Transactions run independently, and multiple transactions are isolated from each other without interfering with each other. 100% isolation of transactions will sacrifice speed.
  • Persistence: After the transaction is completed, its impact on the system is permanent.

3. Transaction control
By default, MySQL automatically commits transactions, that is, every SQL statement of insert, update, and delete will immediately execute the commit operation after it is submitted. In addition, you can use start transaction or begin to start a transaction, or set the value of autocommit to 0. For a transaction, either roll back or commit.

Transaction submission
As shown in the figure below, transfer 100 yuan from the test user account to the admin account for submission.
Insert picture description here

Transaction rollback
As shown in the figure below, transfer 100 yuan from the test user account to the admin account for rollback operation.Insert picture description here

Guess you like

Origin blog.csdn.net/Jgx1214/article/details/107496150