def __exit__(self, ext_type, exc_value, traceback):
    self.cursor.close()
if isinstance(exc_value, Exception):
    self.connection.rollback()
else:
    self.connection.commit()
self.connection.close()
with Cursor() as cursor:
    print(cursor)
connection = cursor.connection
print(connection)
Контекстный менеджер для Python MySQLdb