From bd29e7ef968ec82774cc869c60a1e9c9809e6f51 Mon Sep 17 00:00:00 2001 From: INADA Naoki Date: Sun, 1 Mar 2015 03:37:20 +0900 Subject: [PATCH] Add context manager to cursor. --- pymysql/cursors.py | 7 +++++++ pymysql/tests/test_basic.py | 5 +---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/pymysql/cursors.py b/pymysql/cursors.py index d22af59..05efb43 100644 --- a/pymysql/cursors.py +++ b/pymysql/cursors.py @@ -53,6 +53,13 @@ class Cursor(object): finally: self.connection = None + def __enter__(self): + return self + + def __exit__(self, *exc_info): + del exc_info + self.close() + def _get_db(self): if not self.connection: raise err.ProgrammingError("Cursor closed") diff --git a/pymysql/tests/test_basic.py b/pymysql/tests/test_basic.py index d410b31..579d7fd 100644 --- a/pymysql/tests/test_basic.py +++ b/pymysql/tests/test_basic.py @@ -93,13 +93,10 @@ class TestConversion(base.PyMySQLTestCase): self.safe_create_table( conn, "test_blob", "create table test_blob (b blob)") - c = conn.cursor() - try: + with conn.cursor() as c: c.execute("insert into test_blob (b) values (%s)", (data,)) c.execute("select b from test_blob") self.assertEqual(data, c.fetchone()[0]) - finally: - c.close() def test_untyped(self): """ test conversion of null, empty string """