我期待在出现错误时使用事务和回滚(如重复键或其他)。
当我禁用自动提交并且出现错误时,即使不应该提交事务也已提交。
这是我的代码:
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
谢谢你的帮助。