cx_Oracle contains __enter__ and __exit__ Connection objects, but not Cursor objects. So I use this everywhere to wrap cursors:
class CursorWrapper(object): def __init__(self, connection): self.connection = connection self.cursor = None def __enter__(self): self.cursor = self.connection.cursor() return self.cursor def __exit__(self, exc_type, exc_value, traceback): self.cursor.close()
then when i want the cursor
with CursorWrapper(cnx) as cursor: cursor.execute("whatever sql statement")
It satisfies my needs quite well.
However, I then wondered what could interfere with the __enter__ and __exit__ methods that would be added directly to cx_Oracle?
Or is there a better way to use cursors with contextual controls, which explains why it is not defined in the module?
EDIT: Sorry, I just found the answer. I can just use contextlib.closing.
import contextlib with contextlib.closing(cnx.cursor()) as cursor:
source share