我想编写一个生成器函数,它将在内存有限的系统上运行,该系统使用 PyMySql(或 MySQLDb)一次返回一个选择查询的结果。以下作品:
#execute a select query and return results as a generator
def SQLSelectGenerator(self,stmt):
#error handling code removed
cur.execute(stmt)
row = ""
while row is not None:
row = self.cur.fetchone()
yield row
然而,以下似乎也有效,但它是否正在执行 fetchall() 是神秘的。我在 Python DB API 中找不到将游标对象作为列表进行迭代时究竟发生了什么:
#execute a select query and return results as a generator
def SQLSelectGenerator(self,stmt):
#error handling code removed
cur.execute(stmt)
for row in self.cur:
yield row
在这两种情况下,以下内容都会成功打印所有行
stmt = "select * from ..."
for l in SQLSelectGenerator(stmt):
print(l)
所以我想知道第二个实现是更好还是更差,以及它是调用 fetchall 还是用 fetchone 做一些棘手的事情。Fetchall 将炸毁将要运行的系统,因为有数百万行。