Syl*_*ain 31 python mysql optimization cursor
我必须处理一个大的结果集(可能是数十万行,有时更多).
不幸的是,它们需要一次性检索(启动时).
我试图通过使用尽可能少的内存来做到这一点.
通过查看,我发现使用SSCursor可能是我正在寻找的,但我仍然不知道如何正确使用它们.
fetchall()从基本游标或SScursor 做一个相同的(在内存使用方面)?
我可以从sscursor我的行逐个"流动"(或几个),如果是,
那么最好的方法是什么?
unu*_*tbu 32
我同意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)
Run Code Online (Sandbox Code Playgroud)
Ott*_*ger 11
在获取大结果集时,一定要使用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()
Run Code Online (Sandbox Code Playgroud)
现在您可以cursor.execute()使用光标作为迭代器来执行查询.
编辑:删除不必要的本土迭代器,谢谢丹尼斯!