SQLAlchemy的`.fetchmany()`与`.limit()`的区别

5
假设query是一个已经定义好的查询。据我所知,connection.execute(query).fetchmany(n)connection.execute(query).limit(n).fetchall()似乎返回相同的结果集。我想知道它们中哪个更符合惯用方式,或者——更重要的是——哪个性能更好?

示例用法为:

query = select([census.columns.state, (census.columns.pop2008 - census.columns.pop2000).label("pop_change")]).group_by(census.columns.state).order_by(desc("pop_change"))
results_1 = query.limit(5).fetchall()
results_2 = connection.execute(query).fetchmany(n)    #`results_2` = `results_1`
2个回答

4

我发现fetchmany在需要从数据库中获取非常大的数据集但又不想将所有结果加载到内存中时非常有用。它允许您以较小的批次处理结果。

result = conn.execution_options(stream_results=True).execute(
  SomeLargeTable.__table__.select()
)
while chunk:= result.fetchmany(10000) ## only get 10K rows at a time
  for row in chunk:
    ## process each row before moving onto the next chunk

1
这是使用海象运算符的好方法!! - Matt

3

Limit将成为发送到数据库服务器的SQL查询的一部分。

使用fetchmany时,查询将在没有任何限制的情况下执行,但客户端(Python代码)仅请求某些行。

因此,在大多数情况下,使用limit应该更快。


2
不仅更快,而且更“安全”。根据DB-API层的不同,无限制的查询可能会将所有行都拉到客户端,而.fetchmany只会将这些行的子集拉入results_2列表中。 - Gord Thompson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接