In MySQL, transactions allow you to group multiple SQL statements into a single unit of work. This ensures that the changes made by those statements are executed together, and if something goes wrong, the transaction can be rolled back to maintain data integrity. Transactions are especially useful when you need to perform a series of operations that should either all succeed or all fail.
Basic Commands for MySQL Transactions
Start a Transaction
To start a transaction, you use theSTART TRANSACTION
orBEGIN
command.
To save all the changes made during the transaction, you use the
COMMIT
command. Once a transaction is committed, the changes become permanent.3 Rollback a Transaction
If something goes wrong during the transaction (e.g., a constraint violation), you can use the ROLLBACK
command to undo all the changes made since the transaction started.
ROLLBACK;
4 Savepoints
A savepoint allows you to create a point within a transaction to which you can roll back without affecting the entire transaction.
SAVEPOINT savepoint_name;
By default, MySQL runs in autocommit mode, meaning every SQL statement is treated as a transaction. If you want to disable autocommit for your session (so you can manually manage transactions), use the following command:
In the above example:
- We start a transaction with
START TRANSACTION
. - We perform some
INSERT
operations. - If everything is successful, we use
COMMIT
to save the changes to the database. - If an error occurs during the transaction (e.g., inserting invalid data), we could roll back the transaction with
ROLLBACK
to ensure the database stays in a consistent state.
Isolation Levels in MySQL
MySQL supports different transaction isolation levels, which control the visibility of changes made within a transaction to other transactions. The isolation level can be set as follows:
Here are the available isolation levels:
- READ UNCOMMITTED: Transactions can see uncommitted changes made by other transactions.
- READ COMMITTED: Transactions can only see committed changes from other transactions.
- REPEATABLE READ: Ensures that if a transaction reads a value, it will see the same value if it reads it again later. This is the default isolation level in MySQL.
- SERIALIZABLE: The highest isolation level. It ensures no other transactions can read, write, or even lock the same rows.
Example:
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
No hay comentarios:
Publicar un comentario