用MySQL允许使用嵌套事务的?
Answer 1:
InnoDB
支持SAVEPOINTS
。
你可以做到以下几点:
CREATE TABLE t_test (id INT NOT NULL PRIMARY KEY) ENGINE=InnoDB;
START TRANSACTION;
INSERT
INTO t_test
VALUES (1);
SELECT *
FROM t_test;
id
---
1
SAVEPOINT tran2;
INSERT
INTO t_test
VALUES (2);
SELECT *
FROM t_test;
id
---
1
2
ROLLBACK TO tran2;
SELECT *
FROM t_test;
id
---
1
ROLLBACK;
SELECT *
FROM t_test;
id
---
Answer 2:
从MySQL文档:
交易不能嵌套。 这是隐含的后果对于任何当前事务,当你发出START TRANSACTION语句或其同义词之一提交执行。 https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
Answer 3:
如果你使用PHP,那么你可以是有趣的https://github.com/Enelar/phpsql它支持MySQL和pgsql的,并可延伸到其它连接器。
function TransferMoney()
{ // Nested transaction code could not even know that he nested
$trans3 = db::Begin();
if (!db::Query("--Withdraw money from user", [$uid, $amount], true))
return $trans3->Rollback();
db::Query("--Deposit money to system");
return $trans3->Commit();
}
$trans = db::Begin();
db::Query("--Give item to user inventory");
$trans2 = $trans->Begin();
$trans2->Query("--Try some actions and then decide to rollback");
$trans2->Rollback();
// Commit or rollback depending on money transfer result
return $trans->Finish(TransferMoney());
文章来源: Are nested transactions allowed in MySQL?