Python:如何成功继承Sqlite3.Cursor并添加我的自定义方法

标签 python sqlite

我想制作自己的 MagicCursor 类。我希望它继承 sqlite3.Cursor() 的所有方法和属性。但在他的例子中,事情看起来并不那么容易。

通常我们创建一个这样的光标:

import sqlite3
conn = sqlite3.connect('test.db')
crs = conn.cursor()

因为两者之间存在联系。所以我想我必须定义我自己的连接类,然后定义我自己的游标。

这是我想要实现的:

import sqlite3
conn = MyConnect('test.db') ## this returns me a connect object, inherit from         sqlite3.Connection 
crs = conn.cursor() ## this returns me a MyCursor class,
                ## which inherit from sqlite3.Cursor() and has my customized method

这是我的代码,但失败了。

class MyConnect(sqlite3.Connection):
    def cursor(self):
        return MyCursor(self)

class MyCursor(sqlite3.cursor):
    def __init__(self, connect):
        self = connect.cursor()

    def mymethod1(self, argv)
         ...... return ...... ## what ever I defined

有人知道如何实现吗?

最佳答案

import sqlite3
class MyConnect(sqlite3.Connection):
    def cursor(self):
        return super(MyConnect, self).cursor(MyCursor)

class MyCursor(sqlite3.Cursor):
    def mymethod1(self, argv):
        print('Got here')

conn = sqlite3.connect(':memory:', factory=MyConnect)
print(conn)
# <__main__.MyConnect object at 0x90db66c>

cursor = conn.cursor()
print(cursor)
# <__main__.MyCursor object at 0x90d19dc>

cursor.mymethod1('foo')
# Got here

在此示例中,super(MyConnect, self).cursor(MyCursor) 调用 sqlite3.Connection.cursor(MyCursor)

sqlite3.Connection.cursor接受一个可选参数,cursorClass。当提供时,它是用于实例化光标的类。

关于Python:如何成功继承Sqlite3.Cursor并添加我的自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23683886/

相关文章:

sql - 将多个结果合并为列,而不是行

c++ - 如何确保 SqLite 中的只读事务?

Python 在脚本中记录导入模块版本的最佳方法

python - Django admin raw_id_field 没有按预期工作

python - 是最小堆函数

sql - 我可以根据 SQLite 中的查询插入不同的数据库吗?

c - 如何序列化内存中的 SQLite 数据库?

python - 初始化应用服务器 : Failed to locate pgAdmin4. py 时发生错误,终止服务器线程

python - 如何根据停止标准对排序的 DataFrame 进行分组?

来自 CursorWindow 的 java.lang.IllegalStateException : Couldn't read row 0, col 0