Merge pull request #139 from Szczepanov/feature/138-with-statement-pep-343

Support 'with' statement
master
baztian 2020-05-22 20:56:39 +02:00 committed by GitHub
commit 7c86c18f8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 1 deletions

View File

@ -451,6 +451,12 @@ class Connection(object):
def cursor(self): def cursor(self):
return Cursor(self, self._converters) return Cursor(self, self._converters)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
# DB-API 2.0 Cursor Object # DB-API 2.0 Cursor Object
class Cursor(object): class Cursor(object):
@ -604,6 +610,12 @@ class Cursor(object):
def setoutputsize(self, size, column=None): def setoutputsize(self, size, column=None):
pass pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def _unknownSqlTypeConverter(rs, col): def _unknownSqlTypeConverter(rs, col):
return rs.getObject(col) return rs.getObject(col)

View File

@ -207,6 +207,17 @@ class IntegrationTestBase(object):
cursor.execute("select * from ACCOUNT") cursor.execute("select * from ACCOUNT")
self.assertEqual(cursor.rowcount, -1) self.assertEqual(cursor.rowcount, -1)
def test_connection_with_statement(self):
with self.connect() as conn:
self.assertEqual(conn._closed, False)
self.assertEqual(conn._closed, True)
def test_cursor_with_statement(self):
with self.conn.cursor() as cursor:
cursor.execute("select 1 from ACCOUNT")
self.assertIsNotNone(cursor._connection)
self.assertIsNone(cursor._connection)
class SqliteTestBase(IntegrationTestBase): class SqliteTestBase(IntegrationTestBase):
def setUpSql(self): def setUpSql(self):