Connecting Python to PostgreSQL with psycopg2
Learn how to connect Python to a PostgreSQL database using psycopg2. This guide covers installation, connecting, running queries, and using parameterized statements safely.
Almost every real-world Python backend connects to a database. Python PostgreSQL integration is most commonly done with psycopg2, the most widely-used PostgreSQL adapter for Python. This guide walks you through getting connected and running your first queries safely.
Installing psycopg2
pip install psycopg2-binary
The -binary package includes pre-compiled binaries, so you don’t need PostgreSQL development headers installed. For production, prefer psycopg2 (non-binary) compiled against your system’s libpq.
Connecting to PostgreSQL
import psycopg2
conn = psycopg2.connect(
host="localhost",
database="myapp",
user="postgres",
password="yourpassword",
port=5432
)
cursor = conn.cursor()
In production, store your connection string in an environment variable — never hardcode credentials.
Running Queries
SELECT — Reading Data
cursor.execute("SELECT id, name, email FROM users WHERE active = %s", (True,))
rows = cursor.fetchall()
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Email: {row[2]}")
# Always close when done
cursor.close()
conn.close()
INSERT — Writing Data
cursor.execute(
"INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id",
("Kaikobud", "kai@kaiko.dev")
)
new_id = cursor.fetchone()[0]
conn.commit() # Don't forget to commit!
Why %s Instead of f-strings?
Always use parameterized queries (%s placeholders). Never build SQL strings with f-strings or concatenation:
# DANGEROUS — SQL injection vulnerability
cursor.execute(f"SELECT * FROM users WHERE name = '{user_input}'")
# SAFE — parameterized query
cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))
Using a Context Manager
Wrap connections in a with block to handle commits and rollbacks automatically:
with psycopg2.connect(DATABASE_URL) as conn:
with conn.cursor() as cur:
cur.execute("UPDATE users SET active = %s WHERE id = %s", (False, 42))
# conn.commit() is called automatically on exit
Conclusion
Connecting Python to PostgreSQL with psycopg2 is straightforward once you know the pattern. Always use parameterized queries to prevent SQL injection, always commit after writes, and use environment variables for credentials. These three habits cover 90% of database safety concerns.
Read next: Building a REST API with Python and Flask
External resource: psycopg2 Documentation
Related Articles
Docker for Backend Developers: A Practical Introduction
Learn how Docker works, why backend developers need it, and how to containerize your first Python or Go application in under 30 minutes.
Containerising a Backend Service: From Docker to Kubernetes
A practical walkthrough of containerising a Python backend service with Docker, deploying it to Kubernetes on ECS, and the production gaps that only show up once real traffic hits.
Environment Variables Explained: Keeping Secrets Out of Code
Learn what environment variables are and why every developer needs them. This guide covers how to use .env files, os.environ in Python, process.env in Node.js, and best practices.