从数据库类调用execute方法

2024-10-01 13:42:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何理解这个错误。如何传递SQL语句而不引起此错误?我只能对SQL语句使用引号,因此无法更改数据类型

我试图重新格式化INSERT语句,但没有成功

class MD:    

    def __init__(self):
        self.conn = sqlite3.connect('Ex.db')
        self.cursor = self.conn.cursor()

        self.cursor.execute('''CREATE TABLE IF NOT EXISTS Exa (
                       Ex1 INTEGER PRIMARY KEY,
                       Ex2 TEXT NOT NULL,
                       );''')
        self.conn.commit()    

    def close(self):
        self.conn.close()
        self.cursor.close()

    def execute(self, exone, extwo):
        self.cursor.execute()    

    def fetchall(self):
        self.cursor.fetchall()

    def fetchone(self):
        self.cursor.fetchone()

    def commit(self):
        self.conn.commit()    

Ex1 = tk.StringVar
Ex2 = tk.StringVar
Entry = tk.Entry(textvariable=Ex1)
Entry1 = tk.Entry(textvariable=Ex2)
MD.execute('INSERT INTO INTO Exa(Ex1, Ex2) VALUES (?, ?)', exone=Ex1, extwo=Ex2)

错误是

Traceback (most recent call last):
  File "C:/Users/S/Code/FurtherTest.py", line 42, in <module>
    MD.execute('INSERT INTO INTO Exa(Ex1, Ex2) VALUES (?, ?)', exone=Ex1, extwo=Ex2)
  File "C:/Users/S/Code/FurtherTest.py", line 25, in execute
    self.cursor.execute()
AttributeError: 'str' object has no attribute 'cursor'

Tags: selfexecutedef错误语句connmdcursor
1条回答
网友
1楼 · 发布于 2024-10-01 13:42:25

您正在类(MD)上调用execute方法,该调用中的第一个参数将传递给self参数。由于第一个参数是字符串,因此会导致异常。首先创建类的实例:

...
md = MD()
md.execute('INSERT INTO INTO Exa(Ex1, Ex2) VALUES (?, ?)', exone=Ex1, extwo=Ex2)

通过调用实例上的方法,self参数成为实例本身,插入字符串被传递给exone参数

相关问题 更多 >