4

I'm trying to write a generator function that gets rows out of a database and returns them one at a time. However, I'm not sure if the cleanup code marked ** below executes as I think it does. If it does not, what is the best way to put cleanup code inside a generator itself that executes after the last yield statement? I looked at catching StopIteration but that seems to be done from the caller, not within the generator.

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

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 に答える