Yii2无法连接到postgresql

时间:2016-03-03 13:49:45

标签: php database postgresql pdo yii2

当我使用yii2和postgresql数据库时,我收到此错误。

SQLSTATE[HY000] [2002] No such file or directory

Caused by: PDOException

SQLSTATE[HY000] [2002] No such file or directory

我将文件main-local.php配置为:

<?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=127.0.0.1;port=5432;dbname=dbname',
            'username' => 'user',
            'password' => 'pass',
            'charset' => 'utf8',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
    ],
];

顺便说一句,当我使用mysql时,它正在工作。

1 个答案:

答案 0 :(得分:3)

这显然是配置问题。

  1. 调用yii2提供的requirements page并检查是否安装了 PDO Postgresql 扩展程序。
  2. 让您的配置正确。 PostgreSQL与MySQL不同。每个数据库群集至少包含一个名为的数据库。数据库至少包含一个命名的架构,而架构又包含表格。
  3. 有了这些知识,你的main-local.php应该是这样的:

    <?php
    return [
        'components' => [
            'db' => [
                'class' => 'yii\db\Connection',
                'dsn' => 'pgsql:host=localhost;dbname=YOURDATABASE',
                'username' => 'YOURPOSTGRESUSERNAME',
                'password' => 'YOURPOSTGRESPASSWORD',
                'charset' => 'utf8',
                'schemaMap' => [
                    'pgsql' => [
                      'class' => 'yii\db\pgsql\Schema',
                      'defaultSchema' => 'public' //specify your schema here, public is the default schema
                    ]
                ], // PostgreSQL
            ],
            'mailer' => [
                'class' => 'yii\swiftmailer\Mailer',
                'viewPath' => '@common/mail',
                // send all mails to a file by default. You have to set
                // 'useFileTransport' to false and configure a transport
                // for the mailer to send real emails.
                'useFileTransport' => true,
            ],
        ],
    ];