Most Python+Postgres tutorials drag you through SQLAlchemy sessions, engines, and models before you can run a single SELECT. For scripts, cron jobs, and quick data checks, that's overkill.
Here's the pattern I use daily — 6 lines, real dict results, automatic cleanup:
import psycopg
from psycopg.rows import dict_row
with psycopg.connect("postgresql://localhost/mydb", row_factory=dict_row) as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, email, created_at FROM users WHERE active = %s", (True,))
for row in cur.fetchall():
print(row["email"], row["created_at"])
Why this works well
-
dict_rowgives you{"id": 1, "email": "..."}instead of tuples — no morerow[0]guessing -
Both
withblocks auto-commit on success, auto-rollback on exception, and always close the connection -
%splaceholders are parameterized — no string formatting, no SQL injection -
psycopg(v3) is the modern driver;psycopg2is in maintenance mode
One gotcha
psycopg v3 needs the binary extra on some platforms:
pip install "psycopg[binary]"
Without it you'll get a confusing ImportError: no pq wrapper available.
What's your go-to for quick SQL from Python — raw psycopg, SQLAlchemy, or something like records / databases? Curious what's winning in 2026.
Tip tested with MonkeyCode, a free open-source AI coding assistant: https://ly.cyberserval.tech/iIETXiF
Top comments (0)