我想连接YII框架和两个数据库,但是抛出了CDbConnection失败错误的数据库名称

xfyts7mz  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(150)

我已经使用这个教程连接YII与两个数据库
我在protected/config/main.php中添加了一个连接字符串,如下所示

'db2'=>array(
            'connectionString' => 'mysql:host=localhost;port=3306;dbname=db_name ',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'class' => 'CDbConnection'
    ),

我已在下创建了一个文件
protected/component/AltActiveRecord.php类文件,此文件中的代码为
`

abstract class AltActiveRecord extends CActiveRecord
    {
        const BELONGS_TO='CBelongsToRelation';
        const HAS_ONE='CHasOneRelation';
        const HAS_MANY='CHasManyRelation';
        const MANY_MANY='CManyManyRelation';
        const STAT='CStatRelation';     
        public static $db2;

        private static $_models=array();            

        private $_md;                               
        private $_new=false;                        

        private $_attributes=array();               

        private $_related=array();                  

        private $_c;                                

        private $_pk;                               

        public function getDbConnection()
        {
            if(self::$db2!==null)
                return self::$db2;
            else
            {

                self::$db2 = new CDbConnection();
                foreach(Yii::app()->db2 as $key => $value)
                    self::$db2->$key = $value;

                if(self::$db2 instanceof CDbConnection)
                {
                self::$db2->setActive(true);
                return self::$db2;
            }
            else
                throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
            }
            }
            }
`

我已经创建了一个扩展到这个类的模型,并试图在controller中创建这个模型的对象。但是它以一个错误结束,错误内容为
CDbConnection failed to open the DB connection: SQLSTATE[HY000] [1102] Incorrect database name "db_name"
我想知道为什么这个不起作用。是和php版本还是yii版本有关

von4xj4u

von4xj4u1#

在连接字符串中,行尾(db_name之后)有一个额外的空格:

'db2'=>array(
            'connectionString' => 'mysql:host=localhost;port=3306;dbname=db_name ',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'class' => 'CDbConnection'
    ),

应为:

'db2'=>array(
            'connectionString' => 'mysql:host=localhost;port=3306;dbname=db_name',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'class' => 'CDbConnection'
    ),

相关问题