How to Fix psycopg2 Database Connection Error in Python
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_timeoutto avoid hanging. - Use environment variables for database credentials.
- Verify PostgreSQL is running before connecting.
- Check
pg_hba.conffor authentication settings. - Use connection pooling for production applications.
Common Mistakes with psycopg2 error
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- 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
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro