Home > Database > Mysql Tutorial > How to Automatically Roll Back MySQL Transactions on Exceptions?

How to Automatically Roll Back MySQL Transactions on Exceptions?

Mary-Kate Olsen
Release: 2024-11-23 03:24:10
Original
270 people have browsed it

How to Automatically Roll Back MySQL Transactions on Exceptions?

Rolling Back MySQL Transactions on Exceptions

When executing a series of MySQL commands, it is crucial to handle errors to ensure data integrity. One way to achieve this is to automatically roll back the entire transaction in case any command encounters an exception.

To set up automatic rollback, utilize the DECLARE ... HANDLER syntax:

DELIMITER $$

CREATE PROCEDURE `sp_fail`()
BEGIN
    DECLARE `_rollback` BOOL DEFAULT 0;
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET `_rollback` = 1;
    START TRANSACTION;
    INSERT INTO `tablea` (`date`) VALUES (NOW());
    INSERT INTO `tableb` (`date`) VALUES (NOW());
    INSERT INTO `tablec` (`date`) VALUES (NOW()); -- FAIL
    IF `_rollback` THEN
        ROLLBACK;
    ELSE
        COMMIT;
    END IF;
END$$

DELIMITER ;
Copy after login

This procedure defines a handler (CONTINUE HANDLER FOR SQLEXCEPTION) that sets the _rollback flag to 1 if an SQL exception occurs. After executing the individual commands within the transaction, it checks the _rollback flag to determine whether to roll back or commit the transaction.

By implementing this technique, any exception encountered during command execution will cause the entire transaction to be rolled back, ensuring that partial changes are not applied to the database.

The above is the detailed content of How to Automatically Roll Back MySQL Transactions on Exceptions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template