[Java Advanced] Detailed explanation of MySQL transactions

Insert image description here

In database management, a transaction is the execution unit of a set of SQL statements, which are treated as a whole. The main goal of a transaction is to maintain the consistency and integrity of the database, that is, either all SQL statements are executed successfully, or all SQL statements are not executed. In MySQL, transactions play a very important role, especially in applications that need to ensure data integrity and consistency.

This article will introduce in detail the concepts, characteristics, isolation levels, transaction control and sample code of MySQL transactions to help you better understand and apply MySQL transactions.

1. What is a transaction?

A transaction is an ordered execution collection of a set of SQL statements and is considered an indivisible unit of work. It will either execute successfully or roll back if all fail to maintain the consistency and integrity of the database. Transaction is a mechanism used to handle multiple database operations and is often used in the following scenarios:

  • Bank transfer: If you debit an amount from one account and deposit it into another account, you must ensure that both operations succeed or both fail to prevent loss of funds.

  • Order processing: When creating an order, inventory must be reduced and sales records must be increased simultaneously to maintain consistency in inventory and sales data.

  • Reservation system: When booking air tickets or hotels, you need to lock seats or rooms at the same time and reduce the available number to avoid double bookings.

2. Characteristics of transactions (ACID)

Transactions must have the following four properties, often called ACID properties:

2.1 Atomicity

Atomicity means that transactions are indivisible units of work, and either all of them are executed successfully or all of them fail and are rolled back. If a transaction contains multiple operations and any one of them fails, the entire transaction should be rolled back to maintain database consistency.

2.2 Consistency

Consistency ensures that the integrity of the database is not compromised at the beginning and end of a transaction. After a transaction is executed, the database should be in a consistent state that satisfies all constraints and rules.

2.3 Isolation

Isolation means that when multiple transactions are executed concurrently, each transaction should feel that it is operating the database independently, that is, the execution of one transaction should not affect the execution of other transactions. MySQL provides multiple isolation levels for controlling visibility between transactions.

2.4 Durability

Durability ensures that once a transaction is committed, its results are permanently saved in the database and will not be lost even if a system failure occurs.

3. Transaction isolation level

MySQL supports multiple transaction isolation levels to control visibility between different transactions. The isolation levels from low to high are:

3.1 Read Uncommitted

At this level, transactions can read data that other transactions have not yet committed. This is the lowest isolation level and does not provide any isolation.

3.2 Read Committed

At this level, transactions can only read committed data. Data being executed by other transactions is not visible to the current transaction. This is MySQL's default isolation level.

3.3 Repeatable Read

At this level, transactions can read data that other transactions have committed, but data being executed by other transactions is not visible to the current transaction. This level ensures that the data seen during transaction execution is consistent and that dirty data or non-repeatable reads will not occur. However, it still allows phantom reads to occur.

3.4 Serializable

At this level, transactions are executed serially and concurrent execution is not allowed. This provides the highest level of isolation, but may reduce performance.

4. Control of transactions

In MySQL, you can use the following SQL statements to control the start, commit, and rollback of a transaction:

4.1 Start transaction

To start a transaction, use the START TRANSACTIONor BEGINstatement:

START TRANSACTION; -- 或者使用 BEGIN;

4.2 Submit transaction

To commit a transaction, use COMMITthe statement:

COMMIT;

Commit the transaction to make all changes permanent to the database.

4.3 Rollback transaction

To roll back a transaction, use ROLLBACKthe statement:

ROLLBACK;

Rolling back a transaction will undo all uncommitted changes.

5. Example of transaction

Below is a simple example demonstrating how to perform transactions in MySQL.

Suppose there is a bank database that contains two tables: accountsused to store account information and transactionsused to store transaction records. We want to perform a transaction that debits an amount from one account and deposits it into another account.

-- 开始事务
START TRANSACTION;

-- 扣除金额
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;

-- 增加金额
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;

-- 提交事务
COMMIT;

In the above example, the transaction starts first, then executes two UPDATEstatements, one to deduct the amount and the other to increase the amount, and finally COMMITcommits the transaction through the statement.

If an error occurs during the execution of this transaction, you can use ROLLBACKthe statement to roll back the transaction to ensure that the consistency and integrity of the database are not affected.

6. Summary

Transactions are an important concept in database management and are used to ensure data consistency and integrity. MySQL provides different transaction isolation levels to meet the needs of different applications. Database operations can be managed efficiently by controlling the start, commit, and rollback of transactions. Understanding and using transactions is a critical step in writing reliable and performant database applications. I hope this article can help you better understand the concept and use of MySQL transactions.

Author information

Author: Fanyi
CSDN: https://techfanyi.blog.csdn.net
Nuggets: https://juejin.cn/user/4154386571867191

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/133443999