One thing you can do is use a sentence finally. Another option (which may be redundant, but useful for familiarization) is to create a class that works with the operator 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)
source
share