Python
Summary - SQLAlchemy
Combine Engine, Session and query to write a user repository.
Summary - SQLAlchemy
In this group you learned the core concepts of SQLAlchemy. The Engine manages the connection, the Session manages operations, declarative_base defines models, Column defines columns, and session.query runs queries.
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
session.add(User(name="Ayşe"))
session.commit()
print(len(session.query(User).all()))
In the final step you will combine all of these to write a user repository.
Exercise User repository
Start with from sqlalchemy import create_engine, Column, Integer, String and from sqlalchemy.orm import declarative_base, sessionmaker. Define Base = declarative_base() and class User(Base): with __tablename__ = "users", id = Column(Integer, primary_key=True) and name = Column(String). Create the engine with engine = create_engine("sqlite:///:memory:") and tables with Base.metadata.create_all(engine). Open a session with Session = sessionmaker(bind=engine) and session = Session(). Add two records with session.add(User(name="Ayşe")) and session.add(User(name="Ali")), then session.commit(). Print the count with print(len(session.query(User).all())).
Show example solution
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String)
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
session.add(User(name="Ayşe"))
session.add(User(name="Ali"))
session.commit()
print(len(session.query(User).all()))
Test yourself
-
Which one brings all records from the session?
- session.commit()
- session.query(User).all()
- session.add(User)
- session.close()
Show answer
session.query(User).all() — session.query(User).all() brings all User records.
-
Match the group tools
- create_engine
- Creates the engine
- sessionmaker
- Is a session factory
- declarative_base
- Gives the base class
- session.query
- Starts a query
Next lesson: FastAPI app