How to extend OracleCursor class from cx_Oracle

857 views Asked by At

Using Python 2.7.12 and package cx_Oracle I'm trying to create an extended class of the what the package call OracleCursor. I simply want to inherit the methods from the superclass and extend with some custom methods.

First I get the OracleCursor by

import cx_Oracle

conn = cx_Oracle.connect(username, password, dsn)
cursor = conn.cursor()

and I then have the following

>>> type(cursor)Out[6]:
OracleCursor

>>> isinstance(cursor, cx_Oracle.Cursor)
True

One would think that it is achieved by

class ExtendedCursor(cx_Oracle.Cursor):

    def hello_world(self):
        print('Hello world')


extended = ExtendedCursor(cursor)

but I get TypeError: argument 1 must be cx_Oracle.Connection, not OracleCursor. To me that error doesn't make sense. Also, I can't use OracleCursor as my superclass since it isn't recognized as a class.

1

There are 1 answers

0
Maurice Meyer On BEST ANSWER

The cursor is returned from the Connection object. You need to create a custom connection that returns your ExtendedCursor.

import cx_Oracle as cxo

class MyCursor(cxo.Cursor):
    def helloWorld(self):
        print "helloWorld"

class MyConnection(cxo.Connection):
    def cursor(self):
        return MyCursor(self)



if __name__ == '__main__':
    conStr = '<user>/<password>@127.0.0.1:1521/xe'
    db = MyConnection(conStr)
    c = db.cursor()

    print c

    c.execute('select 1+1 from dual')
    print(c.fetchall())

    c.helloWorld()

returns:

<__main__.MyCursor on <__main__.MyConnection to [email protected]:1521/xe>>
[(2,)]
helloWorld