Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

php - How do I connect to PostgreSQL without specifying a database name?

I need to connect to some PostgreSQL server providing some credentials, and print a list of available databases on that host for a given user.

I am trying:

<?php
    $connection = pg_connect("host=localhost user=testuser password=123 connect_timeout=5");
?>

And I get:

Warning: pg_connect() [function.pg-connect]: Unable to connect to PostgreSQL server: FATAL: database "testuser" does not exist in /var/www/test.php on line 56

I thought this must be possible because phpPgAdmin does it, but I looked at phpPpAdmin sources and found that they connect to a database named template1.

From http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html:

CREATE DATABASE actually works by copying an existing database. By default, it copies the standard system database named template1. Thus that database is the "template" from which new databases are made. If you add objects to template1, these objects will be copied into subsequently created user databases. This behavior allows site-local modifications to the standard set of objects in databases. For example, if you install the procedural language PL/pgSQL in template1, it will automatically be available in user databases without any extra action being taken when those databases are made.

Is there a way to connect without specifying any database?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to connect to a database. Which database you could use for a "maintenance database" depends on the installation and the subsequent administration. After a default installation there are 2 databases that could be used for the initial connection - "template1" and "postgres". It's wise to create a new user and a database with the same name and use those.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...