简体   繁体   English

如何在Mysql中回滚?

[英]How to roll back in Mysql?

I want to execute multiple command to update a customer database, but I want this command to execute in a transaction, and when an error occurs in one command all changes would be rolled backed. 我想执行多个命令来更新客户数据库,但是我希望此命令在事务中执行,并且当一个命令中发生错误时,所有更改都将被回滚。

When I run the code in this example, if test2 table has existed the rollback has not worked and the inserted row exists in test table. 在此示例中运行代码时,如果test2表已存在,则回滚将不起作用,并且插入的行将存在于测试表中。

What am I doing wrong? 我究竟做错了什么?

MySQL server is 5.1. MySQL服务器是5.1。 the engine of tables is Innodb. 表的引擎是Innodb。

code example: 代码示例:

set autocommit = 0;
drop procedure if EXISTS rollbacktest;
delimiter //

CREATE PROCEDURE rollbacktest ()
   BEGIN

   DECLARE CONTINUE HANDLER FOR SQLEXCEPTION,SQLWARNING  SET @x2 = 4; 
   SET autocommit = 0;
   start transaction;   

    SET @x2 = 0;

insert into test(t)values (800);

CREATE TABLE `test2` (
`t`  int(11) UNSIGNED NOT NULL 
    )
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_persian_ci ;


if @x2 = 4 THEN    ROLLBACK; else  commit;    end if;

   END;
//

CALL rollbacktest()

Your problem is that you're doing DDL ( CREATE TABLE ), which cannot be done in a transaction, so it'll implicitly commit the stuff you've done before. 您的问题是您正在执行DDL( CREATE TABLE ),这在事务中无法完成,因此它将隐式提交您之前完成的工作。

This will also be the case if you tro to do DROP TABLE , ALTER TABLE , or TRUNCATE TABLE , among other things. 如果您要执行DROP TABLEALTER TABLETRUNCATE TABLE等操作,也会出现这种情况。 Essentially any statement that cannot be rolled back will cause existing transactions to be auto- COMMIT ed 基本上,任何无法回滚的语句都会导致现有事务被自动COMMIT

If I remember correctly, the CREATE TABLE implicitly commits the transaction. 如果我没记错的话, CREATE TABLE隐式提交事务。

http://dev.mysql.com/doc/refman/5.1/en/implicit-commit.html http://dev.mysql.com/doc/refman/5.1/zh-CN/implicit-commit.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM