如何在 db beginTransaction 中提供 db 连接 [英] How to give db connection in db beginTransaction

查看:45
本文介绍了如何在 db beginTransaction 中提供 db 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$transaction = Yii::app()->db->beginTransaction();



                        try {


                           $transaction=$connection->beginTransaction();

                           $model   = new UserRole();
                           $model->role_name="new";
                           $model->save();

                            $transaction->commit();
                            Yii::log('Done', 'trace', 'stripe');
                       } 
               catch (Exception $e) {
                     $transaction->rollback();
                        }

为什么在 yii 中的 begintransaction 之后将数据插入 db,什么是 $connection?我不知道 $connection 是什么意思.在 My config.php My Db 连接中,如下所示.

Why data's are insert in db after that begintransaction in yii,What is $connection?i dont exactly what is meaning of $connection. In My config.php My Db connection like below.

'db' => require(dirname(__FILE__) . '/database.php'),
 $connection = array(
'connectionString' => "mysql:host=localhost;dbname=xxx",
'username' => "root",
'password' => "",
'charset' => 'utf8',
'emulatePrepare' => true,
'tablePrefix' => 'tbl_',
);

我在另一个文件 database.php 中的数据库连接

My databse connection in another file database.php

我得到了类似的错误,

Call to a member function beginTransaction() on a non-object.

为什么在 beginTransaction 之后没有插入数据?

Why data's are not insert after that beginTransaction?

推荐答案

1.在您的配置文件中设置正确的数据库连接参数:

1. set correct db connection params in your config file:

'db' => array(
    'connectionString' => "mysql:host=localhost;dbname=xxx",
    'username' => "root",
    'password' => "",
    'charset' => 'utf8',
    'emulatePrepare' => true,
    'tablePrefix' => 'tbl_',
)

或者在database.php中写入连接数据并包含在主配置中:

or write connection data in database.php and include it in main config:

database.php

return array(
    'connectionString' => "mysql:host=localhost;dbname=xxx",
    'username' => "root",
    'password' => "",
    'charset' => 'utf8',
    'emulatePrepare' => true,
    'tablePrefix' => 'tbl_',
);

ma​​in.php(或其他配置文件)

'db' => require(dirname(__FILE__) . '/database.php'),

2.使用前定义 $connection 变量:

2. define $connection varaible before using:

$connection = Yii::app()->db;

try {
    $transaction = $connection->beginTransaction();

    $model = new UserRole();
    $model->role_name = "new";
    $model->save();

    $transaction->commit();
    Yii::log('Done', 'trace', 'stripe');
} catch (Exception $e) {
    if (isset($transaction)) {
        $transaction->rollback();
    }   
    Yii::log('Error', 'trace', 'stripe');
}

这篇关于如何在 db beginTransaction 中提供 db 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆