Using SQLAlchemy
Let's use SQLAlchemy in Python's interactive mode to understand how it works.
Creating a Session
Activate the environment, navigate to model.py, and open interactive mode.
$ python -i model.py
Import SessionFactory from connection.py and create a session:
>>> from connection import SessionFactory
>>> session = SessionFactory()
Assign the new session to session. We can use it to save and retrieve posts.
Creating Data
To insert data with the ORM, first create a model object. Pass a title and content to Post:
>>> post = Post(title="First post", content="Hello!")
>>> print(post.id)
None
We did not provide an ID, so post.id is None at this point.
Constructing the object does not save it. Its data is still only in Python memory. Add it with session.add(post). A session acts as a temporary workspace collecting changes for the database. session.commit() saves the post.
>>> session.add(post)
>>> session.commit()
INSERT INTO posts (title, content) VALUES (?, ?) RETURNING id
After committing, look for INSERT INTO posts in the terminal. The database assigns an ID while saving. The example's RETURNING id clause retrieves that ID, and SQLAlchemy assigns it to post automatically.
If this was the first insert into an empty table, its ID is 1.
>>> post.id
1
The ORM lets us work with database data through Python objects. Here we inserted a post by creating an object rather than writing SQL.
Reading Data
Let's retrieve all stored posts. Express the SQL query in Python using SQLAlchemy's select() and the desired columns.
statement holds the query statement to execute.
>>> from sqlalchemy import select
>>> statement = select(Post.id, Post.title, Post.content)
Pass it to session.execute() and receive the result in result.
>>> result = session.execute(statement)
result is a SQLAlchemy Result object that provides access to the query data. Its methods let you retrieve that data in different forms. Call result.all() to collect all rows in a list.
We stored one post, so rows contains one row. It is still a list even for a single result. Printing rows[0] shows the three values in tuple form.
>>> rows = result.all()
>>> print(rows[0])
(1, 'First post', 'Hello!')
mappings() exposes rows as dictionary-like values keyed by column name. Once all() consumes a result, you cannot read those rows from it again. Execute the statement again to obtain a fresh result.
>>> result = session.execute(statement)
>>> rows = result.mappings().all()
>>> print(rows[0])
{'id': 1, 'title': 'First post', 'content': 'Hello!'}
You can also retrieve Post objects. Rebuild the query using select(Post), which returns a Post object for each retrieved post.
>>> statement = select(Post)
>>> result = session.execute(statement)
>>> posts = result.scalars().all()
>>> print(posts[0].title)
First post
scalars() extracts the first value from each result row. For select(Post), that value is a Post object, so scalars().all() returns a list of them.
Result provides these methods to retrieve query data in the form you need.
Closing a Session
Call session.close() when finished:
>>> session.close()
A session may retain a connection after your work is done. Think of hanging up after a phone call so the line is available again. Closing the session returns its connection to the engine for reuse.
Check Your Understanding
Decide whether each statement is true or false.
- Constructing an ORM object and adding it to a session immediately commits it.
- You can build a query with select and run it with a session's execute method.
- After consuming all rows, you can read them again from the same result object.
- The scalars method extracts the first value from each row by default.
- Closing a session returns its connection to the engine.
Answers and Explanations
- False — Adding registers the object; committing finalizes the changes.
- True — One constructs a statement and the other executes it.
- False — Execute the query again to obtain a fresh result.
- True — Even when selecting multiple columns, it defaults to only the first value per row.
- True — The connection becomes available for reuse.