Using with statement on cursor in cx_Oracle
Asked Answered
F

1

10

cx_Oracle contains __enter__ and __exit__ on Connection objects, but not on Cursor objects. Thus, 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 a cursor

with CursorWrapper(cnx) as cursor:
    cursor.execute("whatever sql statement")

It suits my needs fairly well.

However, I was then wondering what could prevent __enter__ and __exit__ methods to be added directly in cx_Oracle ?

Or is there a better way to use cursors with context managements, which would explain why it is not defined in the module ?

Frech answered 11/12, 2015 at 16:15 Comment(0)
T
0

Solution moved from @MathieuC.'s question post.

I can just use contextlib.closing.

import contextlib
with contextlib.closing(cnx.cursor()) as cursor:
Thriller answered 25/1, 2023 at 18:55 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.