Python db-api:fetchone、fetchmany 和 fetchall

发布于 2024-10-20 18:45:46 字数 643 浏览 0 评论 0原文

我今天刚刚和一些同事讨论了 python 的 db-api fetchone、fetchmany 和 fetchall。

我确信每个用例的用例都取决于我正在使用的 db-api 的实现,但一般来说 fetchone、fetchmany 和 fetchall 的用例是什么?

换句话说,下面的内容是等价的吗?或者其中是否有一个比其他的更受青睐?如果是的话,在什么情况下?

cursor.execute("SELECT id, name FROM `table`")
for i in xrange(cursor.rowcount):
    id, name = cursor.fetchone()
    print id, name


cursor.execute("SELECT id, name FROM `table`")
result = cursor.fetchmany()
while result:
    for id, name in result:
        print id, name
    result = cursor.fetchmany()


cursor.execute("SELECT id, name FROM `table`")
for id, name in cursor.fetchall():
    print id, name

I just had a discussion today with some coworkers about python's db-api fetchone vs fetchmany vs fetchall.

I'm sure the use case for each of these is dependent on the implementation of the db-api that I'm using, but in general what are the use cases for fetchone vs fetchmany vs fetchall?

In other words are the following equivalent? or is there one of these that is preferred over the others? and if so in which situations?

cursor.execute("SELECT id, name FROM `table`")
for i in xrange(cursor.rowcount):
    id, name = cursor.fetchone()
    print id, name


cursor.execute("SELECT id, name FROM `table`")
result = cursor.fetchmany()
while result:
    for id, name in result:
        print id, name
    result = cursor.fetchmany()


cursor.execute("SELECT id, name FROM `table`")
for id, name in cursor.fetchall():
    print id, name

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

依 靠 2024-10-27 18:45:46

根据 官方 psycopg2 文档

fetchone()

获取查询结果集的下一行,返回单个元组,或者当没有更多数据可用时返回 None:

>>> cur.execute("SELECT * FROM test WHERE id = %s", (3,))
>>> cur.fetchone()

(3, 42, 'bar')

如果先前对execute*() 的调用未生成任何结果集或尚未发出任何调用,则会引发编程错误。

fetchmany([size=cursor.arraysize])

获取查询结果的下一组行,返回元组列表。当没有更多行可用时,将返回空列表。

每次调用要获取的行数由参数指定。如果未给出,则游标的数组大小决定要获取的行数。该方法应尝试获取大小参数指示的尽可能多的行。如果由于指定的行数不可用而无法实现此操作,则可能会返回更少的行:

>>> cur.execute("SELECT * FROM test;")
>>> cur.fetchmany(2)
[(1, 100, "abc'def"), (2, None, 'dada')]
>>> cur.fetchmany(2)
[(3, 42, 'bar')]
>>> cur.fetchmany(2)
[]

如果先前对execute*() 的调用未生成任何结果集或尚未发出任何调用,则会引发编程错误。

请注意,大小参数涉及性能考虑因素。为了获得最佳性能,通常最好使用 arraysize 属性。如果使用 size 参数,那么最好在一次 fetchmany() 调用到下一次调用中保留相同的值。

列表项

fetchall()

获取查询结果的所有(剩余)行,并将它们作为元组列表返回。如果没有更多记录可供获取,则返回空列表。

>>> cur.execute("SELECT * FROM test;")
>>> cur.fetchall()
[(1, 100, "abc'def"), (2, None, 'dada'), (3, 42, 'bar')]

如果先前对execute*()的调用没有产生任何结果集或者尚未发出任何调用,则会引发编程错误。

As per official psycopg2 documentation

fetchone()

Fetch the next row of a query result set, returning a single tuple, or None when no more data is available:

>>> cur.execute("SELECT * FROM test WHERE id = %s", (3,))
>>> cur.fetchone()

(3, 42, 'bar')

A ProgrammingError is raised if the previous call to execute*() did not produce any result set or no call was issued yet.

fetchmany([size=cursor.arraysize])

Fetch the next set of rows of a query result, returning a list of tuples. An empty list is returned when no more rows are available.

The number of rows to fetch per call is specified by the parameter. If it is not given, the cursor’s arraysize determines the number of rows to be fetched. The method should try to fetch as many rows as indicated by the size parameter. If this is not possible due to the specified number of rows not being available, fewer rows may be returned:

>>> cur.execute("SELECT * FROM test;")
>>> cur.fetchmany(2)
[(1, 100, "abc'def"), (2, None, 'dada')]
>>> cur.fetchmany(2)
[(3, 42, 'bar')]
>>> cur.fetchmany(2)
[]

A ProgrammingError is raised if the previous call to execute*() did not produce any result set or no call was issued yet.

Note there are performance considerations involved with the size parameter. For optimal performance, it is usually best to use the arraysize attribute. If the size parameter is used, then it is best for it to retain the same value from one fetchmany() call to the next.

List item

fetchall()

Fetch all (remaining) rows of a query result, returning them as a list of tuples. An empty list is returned if there is no more record to fetch.

>>> cur.execute("SELECT * FROM test;")
>>> cur.fetchall()
[(1, 100, "abc'def"), (2, None, 'dada'), (3, 42, 'bar')]

A ProgrammingError is raised if the previous call to execute*() did not produce any result set or no call was issued yet.

み零 2024-10-27 18:45:46

我认为这确实取决于实现,但是您可以通过查看 MySQLdb 源代码来了解差异。根据选项,mysqldb fetch* 将当前行集保留在内存或服务器端,因此 fetchmany 与 fetchone 在这里具有一定的灵活性,可以知道哪些内容保留在(python 的)内存中以及哪些内容保留在数据库服务器端。

PEP 249 没有提供太多细节,所以我猜这是根据数据库优化事物,而确切的语义是实现定义的。

I think it indeed depends on the implementation, but you can get an idea of the differences by looking into MySQLdb sources. Depending on the options, mysqldb fetch* keep the current set of rows in memory or server side, so fetchmany vs fetchone has some flexibility here to know what to keep in (python's) memory and what to keep db server side.

PEP 249 does not give much detail, so I guess this is to optimize things depending on the database while exact semantics are implementation-defined.

岁月苍老的讽刺 2024-10-27 18:45:46

这些是特定于实现的。

  • fetchall

会从表中获取所有结果。当表尺寸较小时,此方法效果更好。如果表大小较大,在这种情况下 fetchall 将失败。

将使用大部分内存。

如果在网络上进行查询,则会导致出现一些问题。

  • fetchmany

fetchmany 将仅获得所需数量的结果。您可以得出结果和过程。 fetchmany 实现的简单片段。

   while True:
    results = cursor.fetchmany(arraysize)
    if not results:
        break
    for result in results:
        yield result

These are implementation specific.

  • fetchall

Will get all the results from the table. This will work better when size of the table is small. If the table size is bigger, fetchall will fail in those cases.

Will use most of the memory.

Will cause some issues will can occur if the queries is done on network.

  • fetchmany

fetchmany will get only required number of results. You can yield the results and process. Simple Snippet of implementation of fetchmany.

   while True:
    results = cursor.fetchmany(arraysize)
    if not results:
        break
    for result in results:
        yield result
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文