如何从cx_Oracle扩展OracleCursor类 [英] How to extend OracleCursor class from cx_Oracle

查看:70
本文介绍了如何从cx_Oracle扩展OracleCursor类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python 2.7.12和程序包 cx_Oracle ,我正在尝试创建程序包调用的扩展类

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.

首先,我获得

OracleCursor

First I get the OracleCursor by

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:参数1必须是cx_Oracle.Connection,而不是OracleCursor .对我来说,这个错误是没有道理的.另外,由于无法将 OracleCursor 用作超类,因此无法使用它.

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.

推荐答案

游标从Connection对象返回.您需要创建一个自定义连接,以返回您的ExtendedCursor.

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()

返回:

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

这篇关于如何从cx_Oracle扩展OracleCursor类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆