如何连接到Postgres数据库而不在PDO中指定数据库名称?

Cha*_*ari 6 php postgresql pdo

我使用以下连接来连接到没有数据库的Postgres SQL,因为我需要稍后获取所有数据库名称以进行配置

try{
    $this->connection = new \PDO($this->database.":host=".$this->host,$this->user,$this->password);
    $this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    return $this->connection;
}catch(\PDOException $e){
    echo $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误

SQLSTATE[08006] [7] FATAL: database "admin" does not exist
Run Code Online (Sandbox Code Playgroud)

以下是属性中设置的值:

$this->database = pgsql
$this->host = localhost
$this->user = admin
$this->password = admin
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我如何连接到Postgres SQL而无需使用PHP PDO进行任何数据库选择

小智 0

由于 PostgreSQL 上始终有一个名为 postgres 的默认数据库,因此默认情况下您可以像这样连接到它:

$dbh = new PDO($this->database.":host=".$this->host.";dbname=postgres",$this->user,$this->password);
Run Code Online (Sandbox Code Playgroud)

然后你会在做好的之后再做一张。