Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在内存高效生成器中使用PyMySql的正确方法_Python_Mysql_Mysql Python_Pymysql - Fatal编程技术网

Python 在内存高效生成器中使用PyMySql的正确方法

Python 在内存高效生成器中使用PyMySql的正确方法,python,mysql,mysql-python,pymysql,Python,Mysql,Mysql Python,Pymysql,我想编写一个生成器函数,它将在内存有限的系统上运行,该系统使用PyMySql(或MySQLDb)一次返回一个select查询的结果。以下工作: #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

我想编写一个生成器函数,它将在内存有限的系统上运行,该系统使用PyMySql(或MySQLDb)一次返回一个select查询的结果。以下工作:

#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将破坏系统,因为有数百万行

根据程序,正在执行

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

class Cursor(object):
    '''
    This is the object you use to interact with the database.
    '''
    ...
    def __iter__(self):
        return iter(self.fetchone, None)
因此,我希望这两种方法在内存使用和性能方面基本相同。你也可以用第二个,因为它更干净更简单

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