Menu

SQLAlchemy

Introduction

SQLAlchemy is Python's most popular database toolkit. While Django has its own ORM, SQLAlchemy is the go-to choice for non-Django Python projects (Flask, FastAPI, etc.).

ORM basics

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False)
    email = Column(String(255), unique=True)

# Connect to database
engine = create_engine('sqlite:///app.db')
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

# Create
new_user = User(name='Alice', email='alice@example.com')
session.add(new_user)
session.commit()

# Read
users = session.query(User).all()
user = session.query(User).filter_by(name='Alice').first()

# Update
user.name = 'Alice Smith'
session.commit()

# Delete
session.delete(user)
session.commit()

Assignment

  1. Install SQLAlchemy: pip install sqlalchemy
  2. Create a small project that uses SQLAlchemy to manage a to-do list with SQLite.
  3. Practice relationships (one-to-many, many-to-many).

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!