What is SQLAlchemy and how does it differ from raw SQL?
SQLAlchemy is a Python SQL toolkit and ORM that provides two main layers:
SQLAlchemy Core - A SQL abstraction layer that lets you write SQL using Python expressions. It provides a
Table,Column, andselect()API that compiles to SQL for any supported database.SQLAlchemy ORM - A full Object-Relational Mapper built on top of Core. It maps Python classes to database tables and Python objects to rows, allowing you to work with data as native Python objects instead of raw tuples.
Key differences from raw SQL:
- Portability: Same Python code works across PostgreSQL, MySQL, SQLite, etc.
- Security: Parameterized queries by default prevent SQL injection.
- Abstraction: Work with Python objects instead of result tuples.
- Relationship management: Automatic JOIN generation through relationship definitions.
- Session/Unit of Work: Changes are batched and committed together, providing transactional integrity.
1. Import create_engine and declarative_base
2. Define engine with connection URL
3. Create a Base class for models
4. Define model classes that inherit from Base
5. Create tables with Base.metadata.create_all(engine)
6. Create a Session to interact with the database
7. Use session.add(), session.query(), session.commit()
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, Session
# Core: create engine
engine = create_engine('sqlite:///example.db', echo=True)
# ORM: declarative base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
email = Column(String(120), unique=True)
def __repr__(self):
return f"<User(name='{self.name}', email='{self.email}')>"
# Create tables
Base.metadata.create_all(engine)
# Use the ORM
with Session(engine) as session:
user = User(name='Alice', email='alice@example.com')
session.add(user)
session.commit()
# Query
found = session.query(User).filter_by(name='Alice').first()
print(found) # <User(name='Alice', email='alice@example.com')>
- •SQLAlchemy has two layers: Core (SQL expression language) and ORM (object mapping)
- •The engine manages database connections and connection pooling
- •declarative_base() creates a base class that links Python classes to database tables
- •The Session is the primary interface for persistence operations in ORM
- •SQLAlchemy automatically parameterizes queries to prevent SQL injection
- •echo=True in create_engine logs all SQL, which is useful for debugging but noisy in production
- •Forgetting session.commit() means your changes are never written to the database
- •SQLAlchemy 2.0 uses declarative_base from sqlalchemy.orm, not sqlalchemy.ext.declarative