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.
Yes, the
Connectionobject can act as a context manager.