MySQL事务

应用的是TP5.0框架

 

首先要引入 Exception类

use think\Exception;

直接上代码
public function test(){
$upd = [
'status' => 1
];
// 启动事务
Db::startTrans();
try{
$res = Db::name('test')->where('id',1)->update($upd);
$res2 = Db::name('test')->where('id',2)->update($upd);
// id 为 2 的数据不存在
if($res && $res2){
echo "操作成功!";
}else{
throw new Exception("操作失败!");
}
// 提交事务
Db::commit();
} catch (Exception $e) {
// 回滚事务
Db::rollback();
echo $e->getMessage();
}
}
posted @ 2019-08-08 12:24  blange  阅读(132)  评论(0编辑  收藏  举报