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 execute
You can use a context manager and the with
statement. contextlib provides 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
This will automatically call close()
on dbc
at the end of the with
block, even if an exception has been raised.