Course contentsShow
← Data Science
Lesson 1122 of 2,14528. Working with Databases from PythonFree lesson

Creating Tables and Session Management

Using metadata to create tables and managing database sessions for transactions.

Creating Tables and Session Management

What you'll learn: How to physically create your ORM model tables in the database and manage sessions to interact with them safely.


Now that you've defined your models with SQLAlchemy's Declarative Base and specified columns and relationships, you need to actually create those tables in your database and learn how to talk to them through sessions.

Creating Tables from Metadata

When you define models using Declarative Base, SQLAlchemy builds a metadata catalog behind the scenes—a blueprint of all your tables. To turn that blueprint into real database tables, you call:

Base.metadata.create_all(engine)

This examines all your model classes and executes the necessary CREATE TABLE statements. Think of it like hitting "build" after drawing architectural plans—your database structure comes to life. If tables already exist, SQLAlchemy skips them (it won't overwrite).

Session Management

Sessions are your workspace for database operations. Like transactions you learned earlier, sessions group multiple operations together and manage the connection for you. You create a session factory first:

from sqlalchemy.orm import sessionmaker

Session = sessionmaker(bind=engine)
session = Session()

Now session acts as your staging area. You add, query, modify, and delete objects through it. When ready, call session.commit() to save changes permanently, or session.rollback() if something goes wrong.

Always close sessions when done:

session.close()

Better yet, use a context manager pattern you saw with transactions to ensure cleanup happens automatically.

Key Takeaway: Use Base.metadata.create_all(engine) to build your database tables from ORM models, and manage all database operations through sessions that handle transactions and connection lifecycle.