try{
$driver_opts = array(
PDO::ATTR_AUTOCOMMIT=>0,
PDO::ATTR_PERSISTENT=>true,//持久化连接
);
$pdo = new PDO('mysql:host=localhost;daname=test','root','',$driver_opts);
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,0);
$pdo->setAttribute(PDO::ATTR_PERSISTENT,true);
}catch(PDOException $e){//错误处理
echo '数据库连接失败:'.$e->getMessage();
exit;
}
/**
* int PDO::exec(string $statement)
* 执行一条SQL语句,并返回受影响的行数,没有受影响的行数就返回0
* 不会从一条Select语句中返回结果
*/
try{
$affected_rows = $pdo->exec("insert into table(cols) values('value')");
echo '最后插入的自动增长的ID:'.$pdo->lastInsertId();
}catch(PDOException $e){
echo $e->getMessage();
}
//设置错误报告模式 ERRMODE_SLIENT ERRMODE_WARNING
if(!$affected_rows){
echo $pdo->errorCode().'<br />';
print_r($pdo->errorInfo());
}
/**
* 使用query()来执行select语句
*/
try{
$result = $pdo->query('select * from table');
foreach ($result as $row) {
print_r($row);
echo '<br />';
}catch(PDOException $e){
echo $e->getMessage();
}
try{
//启动一个事务,关闭自动提交
$pdo->beginTransaction();
$price = 500;
$sql = "update zhanghao set price=price-{$price} where id=1";
$affected_rows = $pdo->exec($sql);
if(!affected_rows)
throw new PDOException("张三转出失败");
$sql = "update zhanghao set price=price+{$price} where id=3";
$affected_rows = $pdo->exec($sql);
if(!affected_rows)
throw new PDOException("向李四转入失败");
echo "交易成功";
//提交一个事务,数据库连接返回到自动提交模式知道下次调用PDO::beginTransactuin()开始一个新的事务
$pdo->commint();
}catch(PDOException $e){
echo $e->getMessage();
//识别出错误并回滚更改
$pdo->rollback();
}
//关闭连接
$pdo = null;