From 1c818f8034882c6a4dfc471a3564c5ecfd962d3c Mon Sep 17 00:00:00 2001 From: INADA Naoki Date: Wed, 25 Feb 2015 11:26:39 +0900 Subject: [PATCH] Cursor supports context manager interface --- MySQLdb/cursors.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/MySQLdb/cursors.py b/MySQLdb/cursors.py index ed2df17..d177f20 100644 --- a/MySQLdb/cursors.py +++ b/MySQLdb/cursors.py @@ -85,13 +85,22 @@ class BaseCursor(object): def close(self): """Close the cursor. No further queries will be possible.""" - if self.connection is None or self.connection() is None: - return - while self.nextset(): - pass - self.connection = None - self.errorhandler = None - self._result = None + try: + if self.connection is None or self.connection() is None: + return + while self.nextset(): + pass + finally: + self.connection = None + self.errorhandler = None + self._result = None + + def __enter__(self): + return self + + def __exit__(self, *exc_info): + del exc_info + self.close() def _check_executed(self): if not self._executed: