Skip to content

How to Fix psycopg2 Database Connection Error in Python

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix psycopg2 Database Connection Error in Python. We cover key concepts, practical examples, and best practices.

psycopg2 raises OperationalError when the connection to a PostgreSQL database fails due to network, authentication, or configuration issues.

The Wrong Way

import psycopg2

conn = psycopg2.connect(
    host="localhost",
    port=5432,
    user="admin",
    password="secret",
    database="mydb"
)

This produces:

psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed:
Connection refused
    Is the server running on that host and accepting TCP/IP connections?

The Right Way

Use a connection string and add error handling:

import psycopg2
from psycopg2 import OperationalError

try:
    conn = psycopg2.connect(
        host="localhost",
        port=5432,
        user="admin",
        password="secret",
        database="mydb",
        connect_timeout=5
    )
    print("Connection successful")
except OperationalError as e:
    print(f"Connection failed: {e}")

Step-by-Step Fix

1. Verify PostgreSQL is running

sudo systemctl status postgresql
# or
pg_isready

2. Check the connection parameters

import psycopg2

try:
    conn = psycopg2.connect(
        host="localhost",
        port=5432,
        user="postgres",
        password="postgres",
        database="postgres",
        connect_timeout=3
    )
except psycopg2.OperationalError as e:
    print(f"Cannot connect: {e}")

3. Use a connection URL

import psycopg2

database_url = "postgresql://admin:secret@localhost:5432/mydb"
try:
    conn = psycopg2.connect(database_url)
except psycopg2.OperationalError as e:
    print(f"Failed: {e}")

4. Handle authentication failures

import psycopg2
from psycopg2 import OperationalError

try:
    conn = psycopg2.connect(
        user="admin",
        password="wrong_password",
        host="localhost",
        port=5432,
        database="mydb"
    )
except OperationalError as e:
    if "password authentication failed" in str(e):
        print("Check your username and password in pg_hba.conf")
    elif "does not exist" in str(e):
        print("Database does not exist -- create it first")

5. Use a connection pool

from psycopg2 import pool

try:
    connection_pool = pool.SimpleConnectionPool(
        1, 10,
        user="admin",
        password="secret",
        host="localhost",
        port=5432,
        database="mydb"
    )
    conn = connection_pool.getconn()
except psycopg2.OperationalError as e:
    print(f"Pool creation failed: {e}")

Prevention Tips

  • Always set connect_timeout to avoid hanging.
  • Use environment variables for database credentials.
  • Verify PostgreSQL is running before connecting.
  • Check pg_hba.conf for authentication settings.
  • Use connection pooling for production applications.

Common Mistakes with psycopg2 error

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What does "Connection refused" mean?

PostgreSQL is not running on the specified host and port, or it is not configured to accept TCP connections. Start the service and check listen_addresses in postgresql.conf.

How do I fix "password authentication failed"?

The password in the connection does not match the PostgreSQL user's password. Reset the password with ALTER USER admin PASSWORD 'new_password'; and update pg_hba.conf to use md5 authentication.

How do I handle SSL connection errors?

Add sslmode='require' to the connection parameters for SSL connections. If the server does not support SSL, set sslmode='disable'. For self-signed certificates, use sslmode='prefer'.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro