Skip to content

Commit 4e11478

Browse files
committed
MSSQLConnection: Add with (context manager) support
1 parent 545f86d commit 4e11478

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

_mssql.pyx

+6
Original file line numberDiff line numberDiff line change
@@ -569,6 +569,12 @@ cdef class MSSQLConnection:
569569
log("_mssql.MSSQLConnection.__dealloc__()")
570570
self.close()
571571

572+
def __enter__(self):
573+
return self
574+
575+
def __exit__(self, exc_type, exc_value, traceback):
576+
self.close()
577+
572578
def __iter__(self):
573579
assert_connected(self)
574580
clr_err(self)

tests/test_context_managers.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import unittest
99

1010
from pymssql import InterfaceError
11-
from .helpers import pymssqlconn
11+
from .helpers import pymssqlconn, mssqlconn
1212

1313

1414
class TestContextManagers(unittest.TestCase):
@@ -35,3 +35,10 @@ def test_pymssql_Cursor_with(self):
3535
cursor.execute("SELECT @@version AS version")
3636

3737
self.assertEqual(str(context.exception), "Cursor is closed.")
38+
39+
def test_mssql_Connection_with(self):
40+
with mssqlconn() as conn:
41+
conn.execute_query("SELECT @@version AS version")
42+
self.assertTrue(conn.connected)
43+
44+
self.assertFalse(conn.connected)

0 commit comments

Comments
 (0)