AI Hints
Home›PostgreSQL Tutorial›Postgres from Python
PostgreSQL · Lesson 82 of 120

psycopg Basics

Postgres from Python.

⏱ 2 min read▶ Video at 1:13:46🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Apps talk to Postgres through a driver. For Python, the standard one is psycopg, version three. It sends your SQL, and hands back rows as Python tuples.

  • Python app
  • psycopg 3
  • Rows back

Connect and query

Connect takes a connection URL. Execute runs a query, and fetch all returns the rows as a list of tuples. The with block closes the connection for us. Run it. Three books, as Python data.

basics.pypython
import psycopg

URL = "postgresql://postgres:postgres@localhost:5432/riverside"

with psycopg.connect(URL) as conn:
    rows = conn.execute(
        "SELECT title, price FROM books ORDER BY price DESC LIMIT 3"
    ).fetchall()

for title, price in rows:
    print(f"{title:<26} {price}")
Output
Python for Curious Minds   34.99
Data for Everyone          31.99
SQL in a Weekend           29.99

Fetching rows

Fetch one returns a single row, or none. Fetch all returns every row. And looping over the cursor streams rows one by one. Numeric columns arrive as Python decimals, so money stays exact.

keyvalue
fetchone()one row
fetchall()all rows
for row in curstream
numericDecimal

Summary

Psycopg connects Python to Postgres, runs queries, and returns rows. Next, passing values safely.

Key takeaways
  • psycopg.connect
  • execute
  • fetchall
Next up: Parameters and SQL Injection — never glue strings