YII 错误 SQLSTATE[HY000] [2002] No such file or directory

时间:2022-03-17 20:33:29

在使用yii的yii\db\Connnection时发生错误

<?php
namespace app\controllers;

use yii\web\Controller;
use yii\db\Connection;
use Yii;

class MyController extends Controller
{
    public function actionIndex()
    {
        $country = Yii::$app -> db -> createCommand("select * from country") -> queryAll();
        print_r($country);
    }
}

错误:

YII 错误 SQLSTATE[HY000] [2002] No such file or directory

解决方法:将config目录下的db.php配置文件中的localhost改为127.0.0.1即可

<?php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii',
    'username' => 'root',
    'password' => '12',
    'charset' => 'utf8',
];

当主机填写为localhost时mysql会采用 unix domain socket连接

当主机填写为127.0.0.1时mysql会采用tcp方式连接

这是linux套接字网络的特性,win平台不会有这个问题