2

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

当我禁用自动提交并且出现错误时,即使不应该提交事务也已提交。

这是我的代码:

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

谢谢你的帮助。

4

2 回答 2

1

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

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 处理程序。

于 2012-05-15T16:26:53.383 回答
1

看到这个链接

如果您没有在语句中指定 IGNORE 选项,则重复键错误会回滚 SQL 语句。

于 2015-10-02T23:51:33.460 回答