PDO的事物处理机制

Mysql的事务处理:

    1.MySQL目前只有InnoDB 和BDB两个数据表类型才支持事务。

  2.在默认条件下,MySQL是以自动提交(autocommit)模式运行的,这就意味着所执行的每一个语句都将立即写入数据库中。但是事务中是不希望有自动提交的行为的。set autocommit = 0; //在当前的会话中关闭自动提交。

 3.start transaction;//开始一个事务;

 4.commit ; //提交一个事务

 5.roolback ; //事务回滚,所有的操作都将被取消。

使用PDO编程的实例如下:

<?php
/*
 * 
 * @Authors peng--jun 
 * @Email   1098325951@qq.com
 * @Date    2016-01-22 14:12:03
 * @Link    http://www.cnblogs.com/xs-yqz/
 * @version $Id$
 ==========================================
 */
 header("Content-type: text/html; charset=UTF-8"); 
 
$pdo = new PDO("mysql:host=localhost;dbname=test","root","jun");
$pdo -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT,0);

try {
    $price = 80;
    $pdo -> beginTransaction();
    $sql = "update account set cash = cash-{$price} where name = 'UserA'";
    $affected_rows = $pdo -> exec($sql);
    if ($affected_rows>0) {
        echo "userA 成功转出{$price}元人民币<br />";
    } else {
        throw new PDOException("UserA 转出失败".$sql);
    }

    $sqlB = "update account set cash = cash+{$price} where name = 'UserB'";
    $affected_rows = $pdo -> exec($sqlB);
    if ($affected_rows>0) {
        echo "成功向userB转入{$price}元人民币";
    } else {
        throw new PDOException("UserB 转入失败");
    }

    echo "交易成功!!!";
    $pdo -> commit();
} catch (PDOException $e) {
    echo "交易失败".$e -> getMessage();
    $pdo -> rollback();
}

$pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT,1);
?>
原文地址:https://www.cnblogs.com/xs-yqz/p/5151237.html