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/pwd@schema.db') 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.
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.]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.