You need to specify the following parameters to connect to PostgreSQL:
- Host or host address
- Port
- Database name
- User
- Password (or other means of authentication, if any)
To connect, there must be a PostgreSQL server running on host, listening to port number port. On that server, a database named dbname and a user named user must also exist. The host must explicitly allow connections from your client (explained in the Enabling access for network/remote users recipe), and you must also pass authentication using the method the server specifies; for example, specifying a password won't work if the server has requested a different form of authentication.
Almost all PostgreSQL interfaces use the libpq interface library. When using libpq, most of the connection parameter handling is identical, so we can discuss that just once.
If you don't specify the preceding parameters, PostgreSQL looks for values set through environment variables, which are as follows:
- PGHOST or PGHOSTADDR
- PGPORT (set this to 5432 if it is not set already)
- PGDATABASE
- PGUSER
- PGPASSWORD (this is definitely not recommended)
If you somehow specify the first four parameters, but not the password, PostgreSQL looks for a password file, discussed in the Avoiding hardcoding your password recipe.
Some PostgreSQL interfaces use the client-server protocol directly, so the ways in which the defaults are handled may differ. The information we need to supply won't vary significantly, so check the exact syntax for that interface.
Connection details can also be specified using a Uniform Resource Identifier (URI) format, as follows:
psql postgresql://myuser:mypasswd@myhost:5432/mydb
This specifies that we will connect the psql client application to the PostgreSQL server at the myhost host, on the 5432 port, with the mydb database name, myuser user, and mypasswd password.
If you do not set mypasswd in the preceding URI, you will be prompted to enter the password.