4

我正在尝试编写一个生成器函数,该函数从数据库中获取行并一次返回一个。但是,我不确定下面标记为 ** 的清理代码是否像我认为的那样执行。如果没有,将清理代码放入生成器本身的最佳方法是什么,该生成器在最后一个 yield 语句之后执行?我看着捕捉 StopIteration 但这似乎是从调用者那里完成的,而不是在生成器中。

def MYSQLSelectGenerator(stmt):
...
try:   
    myDB = MySQLdb.connect(host=..., port=..., user=..., passwd=..., db=...)   
    dbc=myDB.cursor()
    dbc.execute(stmt)
    d = "asdf"
    while d is not None:
        d = dbc.fetchone() #can also use fetchmany() to be more efficient
        yield d
    dbc.close() #** DOES THIS WORK AS I INTEND, MEANING AS SOON AS d = "None"
except MySQLdb.Error, msg:
    print("MYSQL ERROR!")
    print msg
4

3 回答 3

4

您可以做的一件事是使用finally子句。另一种选择(在这里可能有点矫枉过正,但了解一下很有用)是创建一个与with语句一起使用的类:

class DatabaseConnection:
    def __init__(self, statement):
        self.statemet = statement
    def __enter__(self): 
        self.myDB = MySQLdb.connect(host=..., port=...,user=...,passwd=...,db=...)
        self.dbc = myDB.cursor()
        self.dbc.execute(self.statement)
        self.d = "asdf"
    def __exit__(self, exc_type, exc_value, traceback):
        self.dbc.close()

    def __iter__(self):
        while self.d is not None:
            self.d = self.dbc.fetchone()
            yield self.d


with DatabaseConnection(stmnt) as dbconnection:
    for i in dbconnection:
        print(i)
于 2013-10-16T19:24:24.177 回答
3

您的版本将dbc.close()尽快运行d is None,但如果引发异常则不会。你需要一个finally从句。即使引发异常,此版本也可以保证运行:dbc.close()

try:   
    myDB = MySQLdb.connect(host=..., port=..., user=..., passwd=..., db=...)   
    dbc = myDB.cursor()
    dbc.execute(stmt)
    d = "asdf"
    while d is not None:
        d = dbc.fetchone() #can also use fetchmany() to be more efficient
        yield d
except MySQLdb.Error, msg:
    print("MYSQL ERROR!")
    print msg
finally:
    dbc.close()
于 2013-10-16T18:55:58.507 回答
1

您可以使用上下文管理器和with语句。contextlib提供closing

from contextlib import closing

myDB = MySQLdb.connect(host=..., port=..., user=..., passwd=..., db=...)   
with closing(myDB.cursor()) as dbc:
    dbc.execute(stmt)
    d = "asdf"
    while d is not None:
        d = dbc.fetchone() #can also use fetchmany() to be more efficient
        yield d

close()这将在块dbc的末尾自动调用with,即使已引发异常。

于 2015-12-28T00:02:02.923 回答