第一章:SQLAlchemy 简介¶
什么是 SQLAlchemy?¶
SQLAlchemy 是 Python 最强大的 SQL 工具包和对象关系映射(ORM)框架。
┌─────────────────────────────────────────────────────────────┐
│ SQLAlchemy 架构 │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ ORM 层 │ │
│ │ ┌───────────────────────────────────────────────┐ │ │
│ │ │ Session、Mapper、Declarative Base │ │ │
│ │ └───────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ SQL Expression Language │ │
│ │ ┌───────────────────────────────────────────────┐ │ │
│ │ │ select()、insert()、update()、delete() │ │ │
│ │ └───────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Engine 层 │ │
│ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ │
│ │ │ MySQL │ │PostgreSQL │ │ SQLite │ │ │
│ │ │ Dialect │ │ Dialect │ │ Dialect │ │ │
│ │ └───────────┘ └───────────┘ └───────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
安装¶
pip install sqlalchemy
# 安装数据库驱动
pip install pymysql # MySQL
pip install psycopg2-binary # PostgreSQL
pip install aiosqlite # SQLite (异步)
核心组件¶
1. Engine¶
from sqlalchemy import create_engine
# MySQL
engine = create_engine('mysql+pymysql://user:pass@localhost/db')
# PostgreSQL
engine = create_engine('postgresql://user:pass@localhost/db')
# SQLite
engine = create_engine('sqlite:///example.db')
2. Session¶
3. Declarative Base¶
快速示例¶
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 创建引擎
engine = create_engine('sqlite:///example.db')
# 创建基类
Base = declarative_base()
# 定义模型
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
email = Column(String(100))
def __repr__(self):
return f"<User(name='{self.name}')>"
# 创建表
Base.metadata.create_all(engine)
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
# 添加用户
user = User(name='Alice', email='alice@example.com')
session.add(user)
session.commit()
# 查询用户
users = session.query(User).all()
print(users)
小结¶
SQLAlchemy 基础概念:
- 架构:ORM → SQL Expression → Engine → Dialect
- 核心组件:Engine、Session、Declarative Base
- 安装:sqlalchemy + 数据库驱动
- 快速示例:定义模型、创建表、CRUD 操作
下一章我们将学习模型定义。