From c87956001003831536daa9fdc091a09e362b47f7 Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Fri, 29 Nov 2019 19:03:26 +0900 Subject: [PATCH 1/2] Add Context Manager Interface to Connection. Fixes #400. --- MySQLdb/connections.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/MySQLdb/connections.py b/MySQLdb/connections.py index 27a04770..020b4a99 100644 --- a/MySQLdb/connections.py +++ b/MySQLdb/connections.py @@ -207,6 +207,12 @@ def unicode_literal(u, dummy=None): self.autocommit(autocommit) self.messages = [] + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + def autocommit(self, on): on = bool(on) if self.get_autocommit() != on: From 81fdf9a8c3b0e1cce48578a119b3ab75f507d7ae Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Fri, 29 Nov 2019 19:44:08 +0900 Subject: [PATCH 2/2] Add test for the context manager API. --- tests/test_MySQLdb_nonstandard.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/test_MySQLdb_nonstandard.py b/tests/test_MySQLdb_nonstandard.py index fa4692ef..c5cacbec 100644 --- a/tests/test_MySQLdb_nonstandard.py +++ b/tests/test_MySQLdb_nonstandard.py @@ -99,3 +99,8 @@ def test_client_flag(self): def test_fileno(self): self.assertGreaterEqual(self.conn.fileno(), 0) + + def test_context_manager(self): + with connection_factory() as conn: + self.assertFalse(conn.closed) + self.assertTrue(conn.closed)