从数据库中删除列表框中的选择

时间:2019-03-22 13:52:23

标签: python sqlite

我基本上有2个python脚本,一个用于前端,另一个用于后端。在前端我有这个:

def delete_command():
    back.delete(selected_tuple[0])

因此,基本上单击列表框中的条目,然后在后端脚本上进行数据库调用(sqllite3)

def delete(id):
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(BASE_DIR, "AVDatabase.db")
    conn=sqlite3.connect(db_path)
    cur=conn.cursor()
    cur.execute('DELETE * FROM "Books"  where BookId=?',(BookId,))
    conn.commit()
    conn.close()

但是我不断收到错误消息:

cur.execute('DELETE * FROM "Books"  where BookId=?',(BookId,))
NameError: name 'BookId' is not defined

该数据库已经存在,因此无法动态创建数据库,不确定为什么它认为BookID列未定义,BookID是主Books表上的主键整数。

2 个答案:

答案 0 :(得分:1)

您没有定义BookId

delete()方法需要一个名为id的参数,并且您在定义中的任何地方都不会使用它。

在此处将BookId替换为idcur.execute('DELETE * FROM "Books" where BookId=?',(BookId,))cur.execute('DELETE * FROM "Books" where BookId=?',(id,))

def delete(id):
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(BASE_DIR, "AVDatabase.db")
    conn=sqlite3.connect(db_path)
    cur=conn.cursor()
    cur.execute('DELETE * FROM "Books"  where BookId=?',(id,))
    conn.commit()
    conn.close()

答案 1 :(得分:0)

这与数据库中的内容或SQL语句本身无关。您只是没有定义 BookId 。此代码会导致相同的错误:

class Cur:
    def execute(self, statement, values):
        pass

cur = Cur()
cur.execute('DELETE * FROM "Books"  where BookId=?',(BookId,))

结果:

Traceback (most recent call last):
  File "...", line 10, in <module>
    cur.execute('DELETE * FROM "Books"  where BookId=?',(BookId,))
NameError: name 'BookId' is not defined

如@Powertieke所说,将 BookId 更改为 id