PDO使用案例

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值