跳转到主要内容
Python · Python第三方库教程集合

Python的数据库工具包SQLAlchemy详细介绍

最后核对于 2026-07-26推断

1. SQLAlchemy 概述

SQLAlchemy 是 Python 中一个功能强大的关系型数据库工具包和对象关系映射(ORM)系统,它为应用程序开发人员提供了完整的 SQL 功能和灵活性。

1.1 SQLAlchemy 的核心特点

  • 双重API设计:同时提供 ORM 和 Core 两种使用方式
  • 数据库无关性:支持多种数据库后端(PostgreSQL, MySQL, SQLite, Oracle, MS-SQL 等)
  • 成熟的ORM系统:完整的对象关系映射实现
  • SQL表达式语言:提供比原始SQL更Pythonic的查询构建方式
  • 连接池管理:高效的数据库连接管理
  • 事务管理:支持复杂的事务操作
  • 高度可扩展:允许自定义数据类型、SQL构造等

1.2 SQLAlchemy 的架构层次

SQLAlchemy 由多个层次组成,从高到低依次为:

  1. ORM:高级对象关系映射层
  2. SQL Expression Language:SQL表达式语言层
  3. Core:核心数据库操作层
  4. DBAPI:Python数据库API接口层

2. 安装与基本配置

2.1 安装 SQLAlchemy

SHELL
pip install sqlalchemy

对于特定数据库,可能需要额外安装驱动程序:

SHELL
# PostgreSQL
pip install psycopg2

# MySQL
pip install mysql-connector-python  # 或 pymysql

# SQLite (Python 标准库已包含)

2.2 创建引擎(Engine)

PYTHON
from sqlalchemy import create_engine

# 基本格式: dialect+driver://username:password@host:port/database

# SQLite 示例
engine = create_engine('sqlite:///example.db')

# PostgreSQL 示例
engine = create_engine('postgresql://user:password@localhost/mydatabase')

# MySQL 示例
engine = create_engine('mysql+pymysql://user:password@localhost/mydatabase')

2.3 配置引擎参数

PYTHON
engine = create_engine(
    'postgresql://user:password@localhost/mydatabase',
    echo=True,  # 输出SQL日志
    pool_size=5,  # 连接池大小
    max_overflow=10,  # 连接池最大溢出数
    pool_timeout=30,  # 获取连接超时时间(秒)
    pool_recycle=3600  # 连接回收时间(秒)
)

3. SQLAlchemy Core

SQLAlchemy Core 提供了比ORM更接近SQL的接口,适合需要直接控制SQL的场景。

3.1 定义表结构

PYTHON
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey

metadata = MetaData()

users = Table('users', metadata,
              Column('id', Integer, primary_key=True),
              Column('name', String(50)),
              Column('fullname', String(50)),
              )

addresses = Table('addresses', metadata,
                  Column('id', Integer, primary_key=True),
                  Column('user_id', None, ForeignKey('users.id')),
                  Column('email_address', String(100), nullable=False)
                  )

# 创建所有表
metadata.create_all(engine)

3.2 基本CRUD操作

插入数据

PYTHON
# 获取连接
conn = engine.connect()

# 单条插入
ins = users.insert().values(name='jack', fullname='Jack Jones')
result = conn.execute(ins)

# 批量插入
conn.execute(addresses.insert(), [
    {'user_id': 1, 'email_address': 'jack@example.com'},
    {'user_id': 1, 'email_address': 'jack@gmail.com'},
])

查询数据

PYTHON
from sqlalchemy import select

# 简单查询
s = select(users)
result = conn.execute(s)
for row in result:
    print(row)

# 带条件查询
s = select(users).where(users.c.name == 'jack')
result = conn.execute(s)
print(result.fetchone())

# 多表连接查询
s = select([users, addresses]).where(users.c.id == addresses.c.user_id)
result = conn.execute(s)
for row in result:
    print(row)

更新数据

PYTHON
# 更新操作
stmt = users.update().where(users.c.name == 'jack').values(fullname='Jack Smith')
conn.execute(stmt)

删除数据

PYTHON
# 删除操作
stmt = addresses.delete().where(addresses.c.email_address == 'jack@example.com')
conn.execute(stmt)

3.3 事务管理

PYTHON
# 手动事务管理
conn = engine.connect()
trans = conn.begin()
try:
    conn.execute(users.insert(), name='user1', fullname='User One')
    conn.execute(users.insert(), name='user2', fullname='User Two')
    trans.commit()
except:
    trans.rollback()
    raise