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
相关产品推荐
相关产品推荐

