MySQL中是否允许嵌套事务?

时间:2009-08-20 15:14:23

标签: mysql transactions nested-transactions

MySQL是否允许使用嵌套事务?

3 个答案:

答案 0 :(得分:70)

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
---

答案 1 :(得分:24)

来自MySQL文档:

  

无法嵌套交易。这是当您发出START TRANSACTION语句或其中一个同义词时对任何当前事务执行的隐式提交的结果。   https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html

答案 2 :(得分:-5)

如果您使用的是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());