问题描述
这两种方法都返回查询返回项的列表,我在这里错过了什么吗?或者他们有相同的用法吗?任何差异性能明智?
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?
推荐答案
如果你使用默认游标,一个 c> cursor.execute()时,整个结果集将存储在客户端 code>已完成。
If you are using the default cursor, a MySQLdb.cursors.Cursor, the entire result set will be stored on the client side (i.e. in a Python list) by the time the cursor.execute() is completed.
因此,即使您使用
for row in cursor:
您不会获得任何减少的内存占用。整个结果集已经存储在一个列表中(参见MySQLdb / cursors.py中的 self._rows )。
you will not be getting any reduction in memory footprint. The entire result set has already been stored in a list (See self._rows in MySQLdb/cursors.py).
但是,如果你使用SSCursor或SSDictCursor:
However, if you use an SSCursor or SSDictCursor:
import MySQLdb import MySQLdb.cursors as cursors conn = MySQLdb.connect(..., cursorclass=cursors.SSCursor)
然后结果集存储在服务器,mysqld。现在你可以写
then the result set is stored in the server, mysqld. Now you can write
cursor = conn.cursor() cursor.execute('SELECT * FROM HUGETABLE') for row in cursor: print(row)
从服务器逐个获取,因此不需要Python首先构建一个庞大的元组列表,从而节省内存。
and the rows will be fetched one-by-one from the server, thus not requiring Python to build a huge list of tuples first, and thus saving on memory.
否则,因为其他人已经说明, cursor.fetchall()和列表(光标)本质上是相同的。
Otherwise, as others have already stated, cursor.fetchall() and list(cursor) are essentially the same.
这篇关于cursor.fetchall()vs list(cursor)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!