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
Your version will run dbc.close()
as soon as d is None
, but not if an exception gets raised. You need a finally clause. This version is guaranteed to run dbc.close()
even if an exception gets raised:
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()