Skip to content

Commit 6432209

Browse files
authored
Add Context Manager Interface to Connection. (PyMySQL#413)
Fixes PyMySQL#400.
1 parent 8fd628e commit 6432209

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

MySQLdb/connections.py

+6
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,12 @@ def unicode_literal(u, dummy=None):
207207
self.autocommit(autocommit)
208208
self.messages = []
209209

210+
def __enter__(self):
211+
return self
212+
213+
def __exit__(self, exc_type, exc_value, traceback):
214+
self.close()
215+
210216
def autocommit(self, on):
211217
on = bool(on)
212218
if self.get_autocommit() != on:

tests/test_MySQLdb_nonstandard.py

+5
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,8 @@ def test_client_flag(self):
9999

100100
def test_fileno(self):
101101
self.assertGreaterEqual(self.conn.fileno(), 0)
102+
103+
def test_context_manager(self):
104+
with connection_factory() as conn:
105+
self.assertFalse(conn.closed)
106+
self.assertTrue(conn.closed)

0 commit comments

Comments
 (0)