cursor.fetchall() vs list(cursor) in Python

后端 未结 5 1083
面向向阳花
面向向阳花 2020-11-30 01:59

Both methods return a list of the returned items of the query, did I miss something here?
Or they have identical usages indeed?
Any differences performance-wise?

5条回答
  •  悲&欢浪女
    2020-11-30 02:18

    list(cursor) works because a cursor is an iterable; you can also use cursor in a loop:

    for row in cursor:
        # ...
    

    A good database adapter implementation will fetch rows in batches from the server, saving on the memory footprint required as it will not need to hold the full result set in memory. cursor.fetchall() has to return the full list instead.

    There is little point in using list(cursor) over cursor.fetchall(); the end effect is then indeed the same, but you wasted an opportunity to stream results instead.

提交回复
热议问题