gpt4 book ai didi

MySQL 回滚重复键

转载 作者:行者123 更新时间:2023-11-29 03:09:27 26 4
gpt4 key购买 nike

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

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

这是我的代码的一部分:

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

感谢您的帮助。

最佳答案

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

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

关于MySQL 回滚重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10602866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com