如何有效使用MySQLDB SScursor?
我需要处理一个很大的结果集(可能有成千上万行,有时甚至更多)。
不幸的是,这些数据必须在启动时一次性全部获取。
我正在尝试尽量减少内存的使用。
在StackOverflow上,我发现使用 SSCursor
可能是我需要的,但我还是不太清楚具体该怎么用。
从一个基本的游标(base cursor)或 SScursor 中使用 fetchall()
获取数据,在内存使用上是一样的吗?
我可以通过 SScursor 一行一行(或者几行几行)地获取数据吗?如果可以,
那么最有效的方式是什么呢?
3 个回答
2
另外,你可以在连接对象之外使用 SSCursor
(这点很重要,特别是当你已经定义了连接,并且不想让所有的连接都使用 SSCursor
作为游标类的时候)。
import MySQLdb
from MySQLdb.cursors import SSCursor # or you can use SSDictCursor
connection = MySQLdb.connect(
host=host, port=port, user=username, passwd=password, db=database)
cursor = SSCursor(connection)
cursor.execute(query)
for row in cursor:
print(row)
16
在获取大量数据时,绝对要使用SSCursor。这对我解决类似问题时帮助很大。你可以这样使用它:
import MySQLdb
import MySQLdb.cursors
connection = MySQLdb.connect(
host=host, port=port, user=username, passwd=password, db=database,
cursorclass=MySQLdb.cursors.SSCursor) # put the cursorclass here
cursor = connection.cursor()
现在你可以用 cursor.execute()
来执行你的查询,并且可以把游标当作一个迭代器来使用。
编辑: 去掉了不必要的自制迭代器,感谢Denis!
39
我同意Otto Allmendinger的回答,不过为了更清楚地说明Denis Otkidach的评论,这里有一种方法可以在不使用Otto的fetch()函数的情况下遍历结果:
import MySQLdb.cursors
connection=MySQLdb.connect(
host="thehost",user="theuser",
passwd="thepassword",db="thedb",
cursorclass = MySQLdb.cursors.SSCursor)
cursor=connection.cursor()
cursor.execute(query)
for row in cursor:
print(row)