You need to enable JavaScript to run this app. 如何将自定义方法绑定到sqlite3的cursor实例上实现直接调用?
优惠活动
大模型
产品
解决方案
定价
更多

如何将自定义方法绑定到sqlite3的cursor实例上实现直接调用?

实现自定义方法挂载到sqlite3 Cursor类的方案

你要的cursor.fetch(xxx)调用形式可以通过两种主流方式实现:

方案1:猴子补丁(全局生效,实现最简单)

直接修改sqlite3内置的Cursor类,给它新增自定义方法,所有后续创建的cursor实例都会自动带有这个方法:

import sqlite3

# 第一个参数自动对应cursor实例本身,改名为self更符合类方法命名习惯
def fetch(self, tableName, target = "*", condition = None, fetchType = "all"):
    "Fetches data from a table in a database\nExecutes 'SELECT {target} FROM {tableName} WHERE {condition}' on the cursor\nExample: user1Name = fetch(cursor, 'tblUser', target = 'userName', condition = 'userId = 1', fetchType = 'one')"
    if condition != None:
        self.execute(f"SELECT {target} FROM {tableName} WHERE {condition}")
    else:
        self.execute(f"SELECT {target} FROM {tableName}")
    if fetchType == "all":
        return self.fetchall()
    elif fetchType == "one":
        return self.fetchone()
    else:
        raise Exception("Invalid fetchType.")

# 把自定义方法挂载到sqlite3的Cursor类上
sqlite3.Cursor.fetch = fetch

# 使用示例
conn = sqlite3.connect("your_db.db")
cursor = conn.cursor()
# 直接调用你要的形式
res = cursor.fetch('tblUser', target = 'userName', condition = 'userId = 1', fetchType = 'one')

注意:该方案会全局修改sqlite3的Cursor类,如果你项目中其他模块也用到了sqlite3,会受到影响,适合个人小项目快速开发使用。

方案2:子类化自定义Cursor(无侵入,生产环境推荐)

继承原生Cursor类实现自定义子类,创建连接时指定使用你自定义的Cursor类即可,不会污染全局原生类:

import sqlite3

class CustomCursor(sqlite3.Cursor):
    # 直接把fetch作为类方法实现
    def fetch(self, tableName, target = "*", condition = None, fetchType = "all"):
        "Fetches data from a table in a database\nExecutes 'SELECT {target} FROM {tableName} WHERE {condition}' on the cursor\nExample: user1Name = fetch(cursor, 'tblUser', target = 'userName', condition = 'userId = 1', fetchType = 'one')"
        if condition != None:
            self.execute(f"SELECT {target} FROM {tableName} WHERE {condition}")
        else:
            self.execute(f"SELECT {target} FROM {tableName}")
        if fetchType == "all":
            return self.fetchall()
        elif fetchType == "one":
            return self.fetchone()
        else:
            raise Exception("Invalid fetchType.")

# 创建连接时指定使用自定义的Cursor类
conn = sqlite3.connect("your_db.db", cursor_factory=CustomCursor)
cursor = conn.cursor()
# 调用方式完全一致
res = cursor.fetch('tblUser', target = 'userName', condition = 'userId = 1', fetchType = 'one')

该方案只会影响你指定了cursor_factory的连接实例,对其他sqlite3的使用无任何影响,可控性更高。

安全提示

当前实现中直接用f-string拼接SQL语句存在SQL注入风险,建议调整为参数化查询实现,避免恶意输入导致的数据库安全问题。

内容的提问来源于stack exchange,提问作者TheAngriestCrusader

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 08:15:00