SQLAlchemy
SQLAlchemy
After learning what an ORM is, the next step is using one of the most popular Python database tools: SQLAlchemy.
SQLAlchemy is widely used in professional Python projects.
It can work with SQLite, PostgreSQL, MySQL, and more.
What Is SQLAlchemy?
SQLAlchemy is a Python library for working with databases.
It provides:
- ORM features
- SQL tools
- database connections
- flexible query building
You can use it with multiple database systems.
Install:
pip install sqlalchemy
Why SQLAlchemy Matters
It helps you:
- write cleaner database code
- use Python classes as tables
- avoid repeating raw SQL
- switch databases more easily
- build real applications
Basic ORM Workflow
You usually:
- Create engine
- Define model class
- Create tables
- Add data
- Query data
- Update data
- Delete data
Step 1: Import Tools
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker
Step 2: Create Database Engine
Using SQLite:
engine = create_engine("sqlite:///school.db")
This creates or connects to:
school.db
Step 3: Create Base Class
Base = declarative_base()
Models will inherit from this base.
Step 4: Define a Model
class Student(Base):
__tablename__ = "students"
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
This class maps to a database table.
Step 5: Create Tables
Base.metadata.create_all(engine)
Creates tables if they do not exist.
Step 6: Create Session
A session is used to talk to the database.
Session = sessionmaker(bind=engine)
session = Session()
CREATE (Insert Data)
student = Student(name="Maya", age=22)
session.add(student)
session.commit()
READ (Query Data)
Get all rows:
students = session.query(Student).all()
for student in students:
print(student.name, student.age)
Filter One Row
student = session.query(Student).filter_by(name="Maya").first()
print(student.age)
UPDATE Data
student.age = 23
session.commit()
DELETE Data
session.delete(student)
session.commit()
Full Example
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker
engine = create_engine("sqlite:///school.db")
Base = declarative_base()
class Student(Base):
__tablename__ = "students"
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
student = Student(name="Tom", age=25)
session.add(student)
session.commit()
for s in session.query(Student).all():
print(s.name, s.age)
Why Session Matters
The session tracks changes and sends them to the database when you commit.
Common Beginner Errors
Forgetting commit()
Changes may not save.
Wrong Database URL
Check:
sqlite:///school.db
Missing Package
Install SQLAlchemy first.
Using Wrong Column Types
Choose types carefully.
Code Along
Build:
library.db
Create model:
Book(id, title, year)
Insert two books and print them.
Mini Challenge
Build a product app.
Tasks:
-
Create SQLite database
-
Create model
Product- id
- name
- price
-
Insert:
- Pen, 2
- Bag, 20
- Print all products
Real World Use Case
SQLAlchemy is used in APIs, dashboards, admin systems, SaaS tools, and business applications.
Quiz
- What is SQLAlchemy?
- What does
create_engine()do? - What is a session?
- Why call
commit()? - What does a model class represent?
Assignment
Create your own SQLAlchemy model with 4 columns and perform CRUD operations.
Summary
You learned how SQLAlchemy connects Python classes to databases and performs CRUD operations using ORM style.