5

我想编写一个生成器函数,它将在内存有限的系统上运行,该系统使用 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 将炸毁将要运行的系统,因为有数百万行。

4

1 回答 1

3

根据PyMySql 源,做

for row in self.cur:
   yield row

这意味着您在内部fetchone()重复执行,就像您的第一个示例一样:

class Cursor(object):
    '''
    This is the object you use to interact with the database.
    '''
    ...
    def __iter__(self):
        return iter(self.fetchone, None)

所以我希望这两种方法在内存使用和性能方面基本相同。您也可以使用第二个,因为它更清洁、更简单。

于 2014-07-02T20:14:03.687 回答