如何从 cx_Oracle 扩展 Oracle Cursor class
How to extend OracleCursor class from cx_Oracle
使用 Python 2.7.12 和包 cx_Oracle
我正在尝试创建包调用 OracleCursor 的扩展 class。我只是想继承 superclass 的方法并使用一些自定义方法进行扩展。
首先我通过
得到了OracleCursor
import cx_Oracle
conn = cx_Oracle.connect(username, password, dsn)
cursor = conn.cursor()
然后我有以下内容
>>> type(cursor)Out[6]:
OracleCursor
>>> isinstance(cursor, cx_Oracle.Cursor)
True
有人会认为它是通过
实现的
class ExtendedCursor(cx_Oracle.Cursor):
def hello_world(self):
print('Hello world')
extended = ExtendedCursor(cursor)
但我得到 TypeError: argument 1 must be cx_Oracle.Connection, not OracleCursor
。对我来说,这个错误没有意义。另外,我不能使用 OracleCursor
作为我的 superclass 因为它不被识别为 class.
游标是从连接对象返回的。您需要创建一个自定义连接,returns 您的 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 ...@127.0.0.1:1521/xe>>
[(2,)]
helloWorld
使用 Python 2.7.12 和包 cx_Oracle
我正在尝试创建包调用 OracleCursor 的扩展 class。我只是想继承 superclass 的方法并使用一些自定义方法进行扩展。
首先我通过
得到了OracleCursor
import cx_Oracle
conn = cx_Oracle.connect(username, password, dsn)
cursor = conn.cursor()
然后我有以下内容
>>> type(cursor)Out[6]:
OracleCursor
>>> isinstance(cursor, cx_Oracle.Cursor)
True
有人会认为它是通过
实现的class ExtendedCursor(cx_Oracle.Cursor):
def hello_world(self):
print('Hello world')
extended = ExtendedCursor(cursor)
但我得到 TypeError: argument 1 must be cx_Oracle.Connection, not OracleCursor
。对我来说,这个错误没有意义。另外,我不能使用 OracleCursor
作为我的 superclass 因为它不被识别为 class.
游标是从连接对象返回的。您需要创建一个自定义连接,returns 您的 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 ...@127.0.0.1:1521/xe>>
[(2,)]
helloWorld