cdb connection连接数据库失败 什么原因
发布网友
发布时间:2022-04-07 07:07
我来回答
共4个回答
懂视网
时间:2022-04-07 11:28
首先,先来看一下问题代码:
1、控制器代码如下:
public function actionIndex()
{
$query = Country::find();
$pagination = new Pagination([
'defaultPageSize' => 5,
'totalCount' => $query->count()
]);
$countries = $query->orderBy('name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('index', [
'countries' => $countries,
'pagination' => $pagination,
]);
}
(推荐教程:yii框架)
2、数据库配置文件db.php代码如下:
<?php
return [
'class' => 'yiidbConnection',
'dsn' => 'mysql:host=localhost;dbname=yii2basic',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
// Schema cache options (for production environment)
//'enableSchemaCache' => true,
//'schemaCacheDuration' => 60,
//'schemaCache' => 'cache',
];
解决方法:
将PDO连接中的dsn的host由“localhost”改为“127.0.0.1”即可,打开文件DB.PHP,修改如下:
<?php
return [
'class' => 'yiidbConnection',
'dsn' => 'mysql:host=127.0.0.1;dbname=yii2basic',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
// Schema cache options (for production environment)
//'enableSchemaCache' => true,
//'schemaCacheDuration' => 60,
//'schemaCache' => 'cache',
];
更多编程相关内容,请关注Gxlcms编程入门栏目!
热心网友
时间:2022-04-07 08:36
先将yii框架的debug模式打开,
[root@xyhz /xyhz/bugfree3.0.3 ]#vim index.php
<?php
// change the following paths if necessary
$yii=dirname(__FILE__).'/lib/yii.php';
$config=dirname(__FILE__).'/protected/config/main.php';
if(!file_exists($config))
{
header( 'Location: install' ) ;
}
// remove the following lines when in proction mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
require_once($yii);
Yii::createWebApplication($config)->run();
然后你会看到一些报错:如下:
CDbConnection 无法开启数据库连线: SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
/xyhz/bugfree3.0.3/lib/db/CDbConnection.php(364)352 throw new CDbException(Yii::t('yii','CDbConnection.connectionString cannot be empty.'));
353 try
354 {
355 Yii::trace('Opening DB connection','system.db.CDbConnection');
356 $this->_pdo=$this->createPdoInstance();
357 $this->initConnection($this->_pdo);
358 $this->_active=true;
359 }
360 catch(PDOException $e)
361 {
362 if(YII_DEBUG)
363 {
364 throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection: {error}',
365 array('{error}'=>$e->getMessage())),(int)$e->getCode(),$e->errorInfo);
366 }
367 else
368 {
369 Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
370 throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'),(int)$e->getCode(),$e->errorInfo);
371 }
372 }
373 }
374 }
375376 /**
重点是在: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)这句话了,这说明你的mysql不是默认安装的,这时你在做个软链接过去就行了
热心网友
时间:2022-04-07 09:54
贴出链接数据库的代码看看 你是怎么链接的
热心网友
时间:2022-04-07 11:29
能贴出你连接数据库的代码么?连接数据库失败的原因可能很多种,得看你代码