You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sqlite3数据库请求异常:自定义类执行查询报AttributeError

问题排查与解决

错误原因

你的报错是因为装饰器传递参数的顺序错误。some_query是Database类的实例方法,第一个参数必须是self,但你的装饰器db_connection在调用func时,把cursor作为第一个参数传入,导致原方法的self被当成了cursor参数,而cursor变量实际指向的是Database实例——自然会报“Database对象没有execute方法”的错误。

解决方法

修改db_connection装饰器的wrapper函数,调整参数传递顺序,确保实例方法的self排在第一位,cursor作为第二个参数传入目标方法:

import sqlite3

class DBConnection:
    def __enter__(self):
        self.conn = sqlite3.connect('main.db')
        self.cursor = self.conn.cursor()
        return self.cursor

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            if exc_type is None:
                self.conn.commit()  # 无异常时提交
            self.conn.close()
        return False  

def db_connection(func):
    def wrapper(*args, **kwargs):
        with DBConnection() as cursor:
            # 把实例self放在第一个参数,cursor作为第二个参数传入
            return func(args[0], cursor, *args[1:], **kwargs)
    return wrapper  

class Database:
    @db_connection
    def some_query(self, cursor, *args):
        # 这里的cursor现在才是真正的sqlite游标对象
        cursor.execute("SELECT * FROM your_table")  # 替换为你的实际查询语句

补充说明

  • 装饰器的wrapper中,args[0]就是Database的实例对象(即self),我们把它作为第一个参数传给func,再把cursor作为第二个参数,剩下的args[1:]是原方法的其他参数。
  • 确保some_query方法的参数顺序是self在前,cursor在后,这样就能正确拿到游标对象执行SQL了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:48:28