This example shows how to create a table, insert data, and select from the database using the SQLAlchemy ORM. For information re: SQLAlchemy Core, see here.
First things first, we need to connect to our database, which is identical to how we would connect using SQLAlchemy Core (Core).
from sqlalchemy import create_engine
engine = create_engine('sqlite://')
After connecting and creating our engine, we need to define and create our tables. This is where the SQLAlchemy ORM language starts to differ greatly from Core. In ORM, the table creation and definition process begins by defining the tables and the classes we'll use to map to those tables. This process is done in one step in ORM, which SQLAlchemy calls the Declarative system.
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
Now that our base mapper is declared, we can subclass from it to build our declarative mappings, or models
.
from sqlalchemy import Column, Integer, String
class Message(Base):
__tablename__ = 'messages'
id = Column(Integer, primary_key=True)
message = Column(String)
Using the declarative base class, we end up creating a Table
and Mapper
object. From the docs:
The Table object is a member of a larger collection known as MetaData. When using Declarative, this object is available using the .metadata attribute of our declarative base class.
With that in mind, to create all tables that do not yet exist, we can call the below command, which utilizes SQLAlchemy Core's MetaData registry.
Base.metadata.create_all(engine)
Now that our tables are mapped and created, we can insert data! Inserting is done through the creation of mapper instances.
message = Message(message="Hello World!")
message.message # 'Hello World!
At this point, all we have is an instance of message at the level of the ORM abstraction level, but nothing has been saved to the database yet. To do this, first we need to create a session.
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
This session object is our database handler. As per the SQLAlchemy docs:
it retrieves a connection from a pool of connections maintained by the Engine, and holds onto it until we commit all changes and/or close the session object.
Now that we have our session, we can add our new message to the session and commit our changes to the database.
session.add(message)
session.commit()
Now that we have data, we can take advantage of the ORM query language to pull up our data.
query = session.query(Message)
instance = query.first()
print (instance.message) # Hello World!
But thats just the beginning! There are much more features that can be used to compose queries, like filter
, order_by
, and much more. See the SQLAlchemy ORM Tutorial for more examples and information.