MySQL的事务嵌套

在使用MySQL时,印象中Innodb表无法进行事务之间的嵌套,其实是有条件的:同一个连接里的事务无法嵌套,但不同连接之间的事务却可以嵌套。

<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'root';
$password = 'root12';

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh2 = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage() . "\n";
}

try {
    $dbh->beginTransaction();
    if (true) {
        $dbh2->beginTransaction();
        $dbh2->commit();
    }
    $dbh->commit();
    echo "It's OK.\n";
} catch (Exception $e) {
    echo "Transaction Faild: " . $e->getMessage() . "\n";
}

?>

当然,如果使用不同的用户名连接数据库,也是一种方法。

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options