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

SQLAlchemy中Connection对象无fetchall属性报错排查

问题原因分析

错误AttributeError: 'Connection' object has no attribute 'fetchall'的核心原因是调用对象错误:

  • 在SQLAlchemy中,db_connection.execute()执行查询后会返回一个Result对象(旧版本为ResultProxy),fetchall()是这个结果对象的专属方法,而非Connection连接对象的方法。
  • 你当前代码直接对db_connection(连接对象)调用fetchall(),但连接对象本身并不具备这个方法,因此触发了属性错误。

正确代码写法

需要先把execute()的返回结果保存为变量,再对这个结果变量调用fetchall():

# 先获取查询结果对象
result = db_connection.execute("select count(*) from table")
# 对结果对象调用fetchall()
query_result = result.fetchall()

额外说明(SQLAlchemy 2.0+版本)

如果使用SQLAlchemy 2.0及以上版本,推荐使用更规范的现代API写法:

from sqlalchemy import text

with db_engine.connect() as conn:
    result = conn.execute(text("select count(*) from table"))
    query_result = result.fetchall()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:30:56