Home > Database > Mysql Tutorial > How can we perform ROLLBACK transaction in MySQL stored procedure?

How can we perform ROLLBACK transaction in MySQL stored procedure?

WBOY
Release: 2023-08-23 20:17:02
forward
1440 people have browsed it

我们如何在 MySQL 存储过程中执行 ROLLBACK 事务?

We know that ROLLBACK will revert any changes made to the database after the transaction started. To execute ROLLBACK within a MySQL stored procedure, we must declare an EXIT handler. We can use handlers for sqlException or SQL warnings. It can be understood with the help of an example, where a stored procedure of ROLLBACK is created for a table with the following details -

mysql> SHOW CREATE table gg\G
*************************** 1. row ***************************
       Table: gg
Create Table: CREATE TABLE `gg` (
   `Id` int(11) NOT NULL AUTO_INCREMENT,
   `Name` varchar(30) NOT NULL,
   PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
Copy after login

We can see that the column "name" cannot have NULL value and the table has the following data -

mysql> Select * from employee.tbl;
+----+---------+
| Id | Name    |
+----+---------+
|  1 | Mohan   |
|  2 | Gaurav  |
|  3 | Sohan   |
|  4 | Saurabh |
|  5 | Yash    |
|  6 | Rahul   |
+----+---------+
6 rows in set (0.00 sec)
Copy after login

Example

mysql> Delimiter //
mysql> Create Procedure st_transaction_Rollback()
    -> BEGIN
    -> DECLARE exit handler for sqlexception
    -> BEGIN
    -> ROLLBACK;
    -> END;
    -> DECLARE exit handler for sqlwarning
    -> BEGIN
    -> ROLLBACK;
    -> END;
    -> START TRANSACTION;
    -> INSERT INTO employee.tbl(name) values();
    -> UPDATE employee.tbl set name = 'YashPal' where id = 5;
    -> COMMIT;
    -> END //
Query OK, 0 rows affected (0.02 sec)

mysql> Delimiter ;
mysql> CALL st_transaction_Rollback ()
Query OK, 0 rows affected (0.00 sec)

mysql> Select * from employee.tbl;
+----+---------+
| Id | Name    |
+----+---------+
|  1 | Mohan   |
|  2 | Gaurav  |
|  3 | Sohan   |
|  4 | Saurabh |
|  5 | Yash    |
|  6 | Rahul   |
+----+---------+
6 rows in set (0.00 sec)
Copy after login

From the above result set we can see that the changes made by the UPDATE statement have been ROLLBACKED because the first query of INSERT threw an error (trying to insert a NULL value) .

The above is the detailed content of How can we perform ROLLBACK transaction in MySQL stored procedure?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template