Transactions are the mechanism in MySQL to ensure data consistency, and have ACID characteristics (atomicity, consistency, isolation, and persistence). The core is to ensure that a set of SQL operations are either successful or all failed. commit is used to confirm all changes in the transaction and write to the database, and rollback is used to undo operations in the transaction and restore to the initial state. Note when using: 1. The default automatic commit needs to be closed for manual control; 2. Transactions cannot be nested, but partial rollback can be simulated by save points; 3. Long transactions affect performance should be as short as possible; 4. DDL statements will implicitly submit transactions; 5. Forgot to commit or the exception is not processed may cause lock waiting or data inconsistency; 6. Multi-connection operations need to pay attention to transaction independence. Mastering these key points will help to correctly manage transaction processes and improve the stability and reliability of database operations.
MySQL transaction processing is a very critical part of database operations, especially when data modifications involving multiple steps. If you are not familiar with transaction commits and rollbacks, it is easy to get stuck in actual use. Simply put, a transaction is a set of SQL operations, either all succeed or all fail .

What is a transaction?
Transactions are the mechanism used in MySQL to ensure data consistency. It has four basic characteristics, which are commonly referred to as ACID:
- A (atomicity) : A transaction is an inseparable unit of work.
- C (consistency) : Before and after the transaction is executed, the database changes from one consistent state to another consistent state.
- I (isolation) : The transactions do not affect each other.
- D (Permanence) : Once a transaction is committed, changes to the database are permanent.
These four features jointly ensure the security of our data when performing complex operations.

The role of commit and rollback
These two commands are at the heart of transaction control:
-
COMMIT
: Acknowledge all operations in the transaction and write them to the database. -
ROLLBACK
: Revoke an operation that has been executed in the transaction and restore it to the state before the transaction begins.
For example, you are doing a transfer operation, and A transfers 100 yuan to B:

START TRANSACTION; UPDATE accounts SET balance = balance - 100 WHERE user_id = 'A'; UPDATE accounts SET balance = balance 100 WHERE user_id = 'B';
If everything works fine, execute:
COMMIT;
If an error occurs in the middle, such as B's account does not exist, execute:
ROLLBACK;
In this way, A will not be deducted money and avoid data errors.
What should you pay attention to when using transactions?
Although transactions are practical, if you don't pay attention to some details, problems may arise:
Default automatic commit (autocommit)
MySQL is automatically submitted by default, which means that each statement will be submitted automatically. If you want to manually control transactions, you must first turn off automatic commit:SET autocommit = 0;
Or set connection parameters in the code to disable automatic submission.
Transactions cannot be nested
MySQL does not support true nested transactions. You can use a savepoint (SAVEPOINT) to simulate partial rollback:START TRANSACTION; SAVEPOINT before_update; -- Do some operations ROLLBACK TO before_update;
Too long transactions will affect performance
Transactions that have not been committed for a long time will occupy resources, lock tables or rows, affecting concurrency performance. Therefore, it is recommended that transactions be as short as possible and submit or roll back in time.DDL operations implicitly submit transactions
For example, when executingCREATE TABLE
,ALTER TABLE
and other statements, the current transaction will be automatically submitted. This should be taken with special care to avoid mixing DDL and DML in transactions.- Forgot COMMIT
- Causes transactions to hang, which may cause locks to wait or even deadlocks.
- No exception handling caused ROLLBACK to be executed
- Especially when calling transactions in a program, if there is no try-catch processing error, the transaction may be stuck in the intermediate state.
- Different client connections interfere with each other
- If you operate transactions at the same time in both terminals, be sure to note that each connection is an independent transaction context.
Frequently Asked Questions in Actual Development
Basically that's it. Mastering the use of transactions can help you write more stable and reliable database logic. The key is to understand when to commit, when to roll back, and how to properly manage transaction flows in your code.
The above is the detailed content of mysql transaction commit rollback. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The default user name of MySQL is usually 'root', but the password varies according to the installation environment; in some Linux distributions, the root account may be authenticated by auth_socket plug-in and cannot log in with the password; when installing tools such as XAMPP or WAMP under Windows, root users usually have no password or use common passwords such as root, mysql, etc.; if you forget the password, you can reset it by stopping the MySQL service, starting in --skip-grant-tables mode, updating the mysql.user table to set a new password and restarting the service; note that the MySQL8.0 version requires additional authentication plug-ins.

GTID (Global Transaction Identifier) ??solves the complexity of replication and failover in MySQL databases by assigning a unique identity to each transaction. 1. It simplifies replication management, automatically handles log files and locations, allowing slave servers to request transactions based on the last executed GTID. 2. Ensure consistency across servers, ensure that each transaction is applied only once on each server, and avoid data inconsistency. 3. Improve troubleshooting efficiency. GTID includes server UUID and serial number, which is convenient for tracking transaction flow and accurately locate problems. These three core advantages make MySQL replication more robust and easy to manage, significantly improving system reliability and data integrity.

MySQL main library failover mainly includes four steps. 1. Fault detection: Regularly check the main library process, connection status and simple query to determine whether it is downtime, set up a retry mechanism to avoid misjudgment, and can use tools such as MHA, Orchestrator or Keepalived to assist in detection; 2. Select the new main library: select the most suitable slave library to replace it according to the data synchronization progress (Seconds_Behind_Master), binlog data integrity, network delay and load conditions, and perform data compensation or manual intervention if necessary; 3. Switch topology: Point other slave libraries to the new master library, execute RESETMASTER or enable GTID, update the VIP, DNS or proxy configuration to

There are three ways to modify or reset MySQLroot user password: 1. Use the ALTERUSER command to modify existing passwords, and execute the corresponding statement after logging in; 2. If you forget your password, you need to stop the service and start it in --skip-grant-tables mode before modifying; 3. The mysqladmin command can be used to modify it directly by modifying it. Each method is suitable for different scenarios and the operation sequence must not be messed up. After the modification is completed, verification must be made and permission protection must be paid attention to.

The steps to connect to the MySQL database are as follows: 1. Use the basic command format mysql-u username-p-h host address to connect, enter the username and password to log in; 2. If you need to directly enter the specified database, you can add the database name after the command, such as mysql-uroot-pmyproject; 3. If the port is not the default 3306, you need to add the -P parameter to specify the port number, such as mysql-uroot-p-h192.168.1.100-P3307; In addition, if you encounter a password error, you can re-enter it. If the connection fails, check the network, firewall or permission settings. If the client is missing, you can install mysql-client on Linux through the package manager. Master these commands

InnoDB implements repeatable reads through MVCC and gap lock. MVCC realizes consistent reading through snapshots, and the transaction query results remain unchanged after multiple transactions; gap lock prevents other transactions from inserting data and avoids phantom reading. For example, transaction A first query gets a value of 100, transaction B is modified to 200 and submitted, A is still 100 in query again; and when performing scope query, gap lock prevents other transactions from inserting records. In addition, non-unique index scans may add gap locks by default, and primary key or unique index equivalent queries may not be added, and gap locks can be cancelled by reducing isolation levels or explicit lock control.

Toalteralargeproductiontablewithoutlonglocks,useonlineDDLtechniques.1)IdentifyifyourALTERoperationisfast(e.g.,adding/droppingcolumns,modifyingNULL/NOTNULL)orslow(e.g.,changingdatatypes,reorderingcolumns,addingindexesonlargedata).2)Usedatabase-specifi

IndexesinMySQLimprovequeryspeedbyenablingfasterdataretrieval.1.Theyreducedatascanned,allowingMySQLtoquicklylocaterelevantrowsinWHEREorORDERBYclauses,especiallyimportantforlargeorfrequentlyqueriedtables.2.Theyspeedupjoinsandsorting,makingJOINoperation
