Reputation: 1837
In recent versions of python, one can use something like with open('abc.txt') as f:
to guarantee that the file is closed even if an exception occurs in the following (indented) code block. I was wondering if this technique would also work for cx_Oracle connection objects. For example, could I do something like this to guarantee the database connection gets closed if an error occurred in the subsequent code block:
with cx_Oracle.connect('uname/[email protected]') as conn:
c = conn.Cursor()
c.execute("Select * from table1")
#...etc
Currently I can accomplish this through the use of try...except...finally, but I prefer the with...as technique.
Upvotes: 1
Views: 2102
Reputation: 798626
Yes, the Connection
object can act as a context manager.
Upvotes: 8
Reputation: 353059
Even if the Connection object didn't do it itself (which apparently it does), as long as it provided a .close()
method it'd be easy to make your own wrapper, using contextlib.closing
>>> from contextlib import closing
>>>
>>> class FakeC(object):
... def close(self):
... print 'closing!'
... def execute(self, cmd):
... print cmd
...
>>> with closing(FakeC()) as c:
... c.execute("fred")
... raise Exception("something went wrong!")
...
fred
closing!
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
Exception: something went wrong!
And other variations are almost as easy.
[Wrote the above before the "Yes!" answer was posted and decided to publish it anyway.]
Upvotes: 4