Are nested transactions allowed in MySQL?

2019-01-04 21:47发布

Does MySQL allow the use of nested transactions?

3条回答
淡お忘
2楼-- · 2019-01-04 22:27

InnoDB supports SAVEPOINTS.

You can do the following:

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
---
查看更多
虎瘦雄心在
3楼-- · 2019-01-04 22:30

From MySQL documentation:

Transactions cannot be nested. This is a consequence of the implicit commit performed for any current transaction when you issue a START TRANSACTION statement or one of its synonyms. https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html

查看更多
4楼-- · 2019-01-04 22:36

If you using php, then you could be interesting in https://github.com/Enelar/phpsql It support mysql and pgsql, and extendable to other connectors.

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());
查看更多
登录 后发表回答