Skip to content

Beginning of the lesson

Databases and ORMs in Python

From the raw sqlite3 DB-API up to SQLAlchemy models, sessions and migrations

Big Idea: A relational database gives you durable, queryable, concurrent storage that outlives your process. Python talks to it two ways: the low-level DB-API (sqlite3), where you write SQL by hand, and an ORM (SQLAlchemy), which maps table rows to Python objects so you mostly work in Python. Neither replaces the other — the ORM is built on top of the DB-API, and knowing both lets you choose deliberately.
By the end you will be able to:
  • open a connection, run SQL through a cursor, and commit a transaction with sqlite3,
  • use parameterized queries to stay safe from SQL injection,
  • explain what an ORM maps and why,
  • define a SQLAlchemy 2.0 model and drive a Session (the unit of work),
  • describe what migrations (Alembic) solve and the real trade-offs of an ORM.

1. Why a database instead of a file?

You already know how to read and write JSON and CSV. Files are perfect for small, single-writer data. A database earns its place when you need any of: querying ("all orders over 100 from last week" without loading everything into memory), concurrency (many readers and writers without corrupting the file), integrity (types, uniqueness, foreign keys enforced by the engine), and transactions (a group of changes that either all happen or none do).

SQLite is the gentlest on-ramp: it is a full SQL engine that lives inside a single file, ships with Python as the sqlite3 module, and needs no server. The same DB-API you learn here is the standard interface (PEP 249) that psycopg for PostgreSQL and drivers for MySQL also implement, so the shapes transfer.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers