How to Connect to PostgreSQL: Simple Steps and Examples
To connect to PostgreSQL, use the
psql command-line tool or a connection string with parameters like host, port, user, password, and dbname. For example, run psql -h localhost -U username -d dbname to start a connection.Syntax
The basic syntax to connect to PostgreSQL using the psql command-line tool is:
psql -h <host> -p <port> -U <user> -d <dbname>- host: The server address (e.g., localhost)
- port: The port number PostgreSQL listens on (default is 5432)
- user: Your PostgreSQL username
- dbname: The database name you want to connect to
You can also use a connection string format: postgresql://user:password@host:port/dbname.
bash
psql -h localhost -p 5432 -U myuser -d mydatabaseExample
This example shows how to connect to a PostgreSQL database named testdb on your local machine using the user testuser. You will be prompted for the password.
bash
psql -h localhost -U testuser -d testdb
Output
psql (14.5)
Type "help" for help.
testdb=>
Common Pitfalls
Common mistakes when connecting to PostgreSQL include:
- Using the wrong port number (default is 5432)
- Forgetting to specify the database name
- Incorrect username or password
- Not having PostgreSQL server running or accessible
- Missing required client tools like
psql
Always check your connection parameters and ensure the server is running.
bash
Wrong: psql -h localhost -U wronguser -d mydb Right: psql -h localhost -U correctuser -d mydb
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| -h | Host address of the PostgreSQL server | localhost |
| -p | Port number PostgreSQL listens on | 5432 |
| -U | Username to connect as | current system user |
| -d | Database name to connect to | same as username if omitted |
| Connection String | Full URI format for connection | N/A |
Key Takeaways
Use the psql command with -h, -p, -U, and -d options to connect to PostgreSQL.
The default port for PostgreSQL is 5432 unless configured otherwise.
Ensure the PostgreSQL server is running and accessible before connecting.
Use correct username and database names to avoid connection errors.
You can also connect using a full connection string URI format.