bibi45

2020-05-25 | Backend 中文

SQLAlchemy 2.x 查询:select 与 Session.scalars

bibi45

从旧式 Model.query 迁移到显式 select 和短生命周期 Session。

This article is currently available in Chinese. The language switch changes the site interface; the original text is shown below.

SQLAlchemy 2.x 以 select() 和 Session.execute() 或 Session.scalars() 为主。查询意图和事务边界因此更清晰。

statement = select(User).where(User.email == email)
with Session(engine) as session:
    user = session.scalar(statement)

所有外部输入都通过 SQLAlchemy 表达式绑定参数,不通过字符串拼接 SQL。列表查询还应设置排序和上限,避免无界扫描。

© 2026 bibi45. All rights reserved.

Built as a static, Git-owned site.