Creating Session

Learn how to create a session and begin operating on it.

Intro to sessions

Once the ORM is defined, we typically create a session and begin operating on it. Here, we create new records and add them to the database. We may want to run this interactively after we import the ORM with from orm import *.

Creating session and create_all

First, we create a session.

Session = sessionmaker(db)
session = Session()

base.metadata.create_all(db)

This program begins by calling the create_all function. This is a useful function to use when experimenting with the ORM. It checks the DB to see if the tables already exist. If they do, it does nothing. If they don’t, it creates them.

Next, we create a session. The idea behind sessions is that they allow us to gracefully recover from errors without corrupting the data in the database.

Creating and adding records to the database

The following commands show how records can be added one by one, from a list, or any other iterable.

Get hands-on with 1200+ tech skills courses.