TP5TP6中,如何实现完整事务异常处理在分布式单库多库环境下的示例?
- 内容介绍
- 文章标签
- 相关推荐
本文共计395个文字,预计阅读时间需要2分钟。
plaintext
1.操作数据库单库
// 启动事务 Db::startTrans(); try { // 抛出数据插入失败异常 throw new \Exception('数据插入失败!'); $code=200; $msg='成功'; // 提交事务 Db::commit(); } catch (\Exception $e) { // 回滚事务 Db::rollback(); $code=-200; }1、操作数据库的[单库]
// 启动事务Db::startTrans();
try {
throw new \Exception('插入数据失败!');
$code=200;$msg="成功";
// 提交事务
Db::commit();
} catch (\Exception $e) {
// 回滚事务
Db::rollback();
$code=-200;
$msg=$e->getMessage();
}
return array('code'=>$code,'msg'=>$msg);
事务里边不能用db()数据库助手
2、操作数据库的[多个数据库](分布式)
// 启动事务Db::connect('mysql')->startTrans();
try {
throw new \Exception('插入数据失败!');
$code=200;$msg="成功";
// 提交事务
Db::connect('mysql')->commit();
} catch (\Exception $e) {
// 回滚事务
Db::connect('mysql')->rollback();
$code=-200;
$msg=$e->getMessage();
}
return array('code'=>$code,'msg'=>$msg);
注意:
Db::connect('mysql')->startTrans();
mysql名称是根据数据库配置文件(config/database.php)来的
3、异常操作
TP6 一定要引用use think\facade\Env;
try {//主体
} catch (\Exception $e) {
// 这是进行异常捕获
return ['code'=>-200,'msg'=>$e->getMessage()];
}
return json(['code' => $code,'msg' =>$msg]); public function UserLogin($username,$password)
{
try {
if(empty($username) || empty($password)){
throw new \Exception("用户名/密码为空!");
}
$code=200;$msg='成功';
} catch (\Exception $e) {
// 这是进行异常捕获
$code=-200;$msg=$e->getMessage();
}
return ['code' => $code,'msg' =>$msg];
}
本文共计395个文字,预计阅读时间需要2分钟。
plaintext
1.操作数据库单库
// 启动事务 Db::startTrans(); try { // 抛出数据插入失败异常 throw new \Exception('数据插入失败!'); $code=200; $msg='成功'; // 提交事务 Db::commit(); } catch (\Exception $e) { // 回滚事务 Db::rollback(); $code=-200; }1、操作数据库的[单库]
// 启动事务Db::startTrans();
try {
throw new \Exception('插入数据失败!');
$code=200;$msg="成功";
// 提交事务
Db::commit();
} catch (\Exception $e) {
// 回滚事务
Db::rollback();
$code=-200;
$msg=$e->getMessage();
}
return array('code'=>$code,'msg'=>$msg);
事务里边不能用db()数据库助手
2、操作数据库的[多个数据库](分布式)
// 启动事务Db::connect('mysql')->startTrans();
try {
throw new \Exception('插入数据失败!');
$code=200;$msg="成功";
// 提交事务
Db::connect('mysql')->commit();
} catch (\Exception $e) {
// 回滚事务
Db::connect('mysql')->rollback();
$code=-200;
$msg=$e->getMessage();
}
return array('code'=>$code,'msg'=>$msg);
注意:
Db::connect('mysql')->startTrans();
mysql名称是根据数据库配置文件(config/database.php)来的
3、异常操作
TP6 一定要引用use think\facade\Env;
try {//主体
} catch (\Exception $e) {
// 这是进行异常捕获
return ['code'=>-200,'msg'=>$e->getMessage()];
}
return json(['code' => $code,'msg' =>$msg]); public function UserLogin($username,$password)
{
try {
if(empty($username) || empty($password)){
throw new \Exception("用户名/密码为空!");
}
$code=200;$msg='成功';
} catch (\Exception $e) {
// 这是进行异常捕获
$code=-200;$msg=$e->getMessage();
}
return ['code' => $code,'msg' =>$msg];
}

