You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQLAlchemy 2.x+在MySQL中获取最后插入记录ID的新方法

SQLAlchemy 2.0+ 获取插入记录主键的正确方式

完全不需要手动执行SELECT 1175922;这类语句,SQLAlchemy 2.0提供了更规范的内置方案,以下是两种可行的实现方式:

方式1:使用returning()(推荐,跨数据库兼容)

在Insert语句中指定返回主键字段,执行后直接从结果中提取值,这是SQLAlchemy 2.0推荐的标准写法,适配绝大多数数据库:

with common.qry_engine.begin() as conn:
    # 替换成你表实际的主键字段名,比如tbl_application.c.id
    insert_stmt = common.tbl_application.insert(values=new_properties).returning(common.tbl_application.c.id)
    result = conn.execute(insert_stmt)
    self.app_id = result.scalar()  # scalar()获取单个返回值,多字段用result.one()

方式2:利用lastrowid(仅适用于MySQL等支持自增主键的数据库)

如果你的场景限定为MySQL,也可以直接通过结果对象的lastrowid属性获取自增主键值:

with common.qry_engine.begin() as conn:
    result = conn.execute(common.tbl_application.insert(values=new_properties))
    self.app_id = result.lastrowid

旧代码失效原因

SQLAlchemy 2.0对Core层的结果对象做了重构,原1.4版本中的inserted_primary_key属性已被移除,因此原有写法不再生效。

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 14:17:10