SQLAlchemy 是 Python 生态中最流行的 ORM 框架之一,它提供了高效且灵活的数据库操作方式。本文将介绍如何使用 SQLAlchemy ORM 进行数据库操作。
安装
bash
pip install sqlalchemy
如果需要连接特定数据库,还需安装相应的驱动程序:
bash
PostgreSQL
pip install psycopg2-binary
MySQL
pip install mysql-connector-python
SQLite (Python 标准库已包含,无需额外安装)
核心概念
- Engine:数据库连接的引擎,负责与数据库通信
- Session:数据库会话,管理所有持久化操作
- Model:数据模型类,对应数据库中的表
- Query:查询对象,用于构建和执行数据库查询
连接数据库
python
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker
创建数据库连接引擎
SQLite 示例
engine = create_engine('sqlite:///example.db', echo=True)
PostgreSQL 示例
engine = create_engine('postgresql://username:password@localhost:5432/mydatabase')
MySQL 示例
engine = create_engine('mysql+mysqlconnector://username:password@localhost:3306/mydatabase')
创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
创建会话实例
session = SessionLocal()
定义数据模型
python
from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.orm import relationship, declarative_base
创建基类
Base = declarative_base()
class User(Base): tablename = 'users' id = Column(Integer, primary_key=True, index=True) name = Column(String(50), nullable=False) email = Column(String(100), unique=True, index=True) # 定义一对多关系 posts = relationship("Post", back_populates="author")
class Post(Base): tablename = 'posts' id = Column(Integer, primary_key=True, index=True) title = Column(String(100), nullable=False) content = Column(String(500)) author_id = Column(Integer, ForeignKey('users.id')) # 定义多对一关系 author = relationship("User", back_populates="posts") # 定义多对多关系(通过关联表) tags = relationship("Tag", secondary="post_tags", back_populates="posts")

