MySQL重复键回滚

时间:2012-05-15 14:24:19

标签: mysql transactions innodb commit rollback

我期待在发生错误时使用事务和回滚(比如重复键或其他)。

当我禁用自动提交时以及错误发生时,即使不应该处理事务,也会提交事务。

这是我的代码:

CREATE TABLE `Users` (
  `user_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `Miscs` (
  `misc_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`misc_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

SET @@AUTOCOMMIT = 0;

BEGIN;
    INSERT INTO Miscs ( misc_id ) VALUES('1');
    INSERT INTO Users ( user_id ) VALUES('1');
    INSERT INTO Miscs ( misc_id ) VALUES('2');
COMMIT;

BEGIN;
    INSERT INTO Miscs ( misc_id ) VALUES('3');
    INSERT INTO Users ( user_id ) VALUES('2');
    INSERT INTO Miscs ( misc_id ) VALUES('4');
COMMIT;

BEGIN;
    INSERT INTO Miscs ( misc_id ) VALUES('5');
    INSERT INTO Users ( user_id ) VALUES('1');
    -- should stop, rollback the transaction and skip to the next/last
    INSERT INTO Miscs ( misc_id ) VALUES('6');
COMMIT;

-- last transaction
BEGIN;
    INSERT INTO Miscs ( misc_id ) VALUES('7');
    INSERT INTO Users ( user_id ) VALUES('4');
    INSERT INTO Miscs ( misc_id ) VALUES('8');
COMMIT;

SET @@AUTOCOMMIT = 1;

但结果很奇怪:

Users :
1
2
3

Miscs :
1
2
3
4
5
6
7
8

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

请参阅this link

  

如果未在语句中指定IGNORE选项,则重复键错误将回滚SQL语句。

答案 1 :(得分:0)

在应用程序中,我会写这样的东西 -

START TRANSACTION
TRY
  INSERT
  INSERT
  INSERT
  COMMIT
CATCH
  ROLLBACK

但MySQL没有TRY-CATCH子句。我可以用DECLARE EXIT HANDLER语句 -

这样建议你
  BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION  ROLLBACK;
    START TRANSACTION;
      INSERT INTO Miscs ( misc_id ) VALUES('1');
      INSERT INTO Users ( user_id ) VALUES('1');
      INSERT INTO Miscs ( misc_id ) VALUES('2');
    COMMIT;
  END;

  BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION  ROLLBACK;
    START TRANSACTION;
      INSERT INTO Miscs ( misc_id ) VALUES('3');
      INSERT INTO Users ( user_id ) VALUES('2');
      INSERT INTO Miscs ( misc_id ) VALUES('4');
    COMMIT;
  END;

  BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION  ROLLBACK;
    START TRANSACTION;
      INSERT INTO Miscs ( misc_id ) VALUES('5');
      INSERT INTO Users ( user_id ) VALUES('1');
      -- should stop, rollback the transaction and skip to the next/last
      INSERT INTO Miscs ( misc_id ) VALUES('6');
    COMMIT;
  END;

  BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION  ROLLBACK;
    START TRANSACTION;
      INSERT INTO Miscs ( misc_id ) VALUES('7');
      INSERT INTO Users ( user_id ) VALUES('4');
      INSERT INTO Miscs ( misc_id ) VALUES('8');
    COMMIT;
  END;

从存储过程运行此代码,因为在MySQL中,无法在脚本中使用DECLARE处理程序。