- SQLAlchemy Tutorial
- SQLAlchemy - Home
- SQLAlchemy - Introduction
- SQLAlchemy Core
- Expression Language
- Connecting to Database
- Creating Table
- SQL Expressions
- Executing Expression
- Selecting Rows
- Using Textual SQL
- Using Aliases
- Using UPDATE Expression
- Using DELETE Expression
- Using Multiple Tables
- Using Multiple Table Updates
- Parameter-Ordered Updates
- Multiple Table Deletes
- Using Joins
- Using Conjunctions
- Using Functions
- Using Set Operations
- SQLAlchemy ORM
- Declaring Mapping
- Creating Session
- Adding Objects
- Using Query
- Updating Objects
- Applying Filter
- Filter Operators
- Returning List and Scalars
- Textual SQL
- Building Relationship
- Working with Related Objects
- Working with Joins
- Common Relationship Operators
- Eager Loading
- Deleting Related Objects
- Many to Many Relationships
- Dialects
- SQLAlchemy Useful Resources
- SQLAlchemy - Quick Guide
- SQLAlchemy - Useful Resources
- SQLAlchemy - Discussion
SQLAlchemy ORM - Creating Session
In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier.
from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine)
The session object is then set up using its default constructor as follows −
session = Session()
Some of the frequently required methods of session class are listed below −
Sr.No. | Method & Description |
---|---|
1 | begin() begins a transaction on this session |
2 | add() places an object in the session. Its state is persisted in the database on next flush operation |
3 | add_all() adds a collection of objects to the session |
4 | commit() flushes all items and any transaction in progress |
5 | delete() marks a transaction as deleted |
6 | execute() executes a SQL expression |
7 | expire() marks attributes of an instance as out of date |
8 | flush() flushes all object changes to the database |
9 | invalidate() closes the session using connection invalidation |
10 | rollback() rolls back the current transaction in progress |
11 | close() Closes current session by clearing all items and ending any transaction in progress |