sqlite python数据库错误 - 没有这样的表

时间:2017-07-26 20:59:03

标签: python database sqlite

我用一个名为product的表创建了一个数据库。当我运行下面的代码时,我收到一个错误 - sqlite3.OperationalError:没有这样的表:产品。我使用数据库浏览器进行检查,表格确实存在。有任何想法吗?代码和文件都在同一个文件夹中。谢谢

from tkinter import *
from tkinter import ttk
import sqlite3
import os.path

class Product:
    db_name = 'database.db'

    def __init__(self, wind):
        self.wind = wind
        self.wind.title('IT Products')

        frame = LabelFrame (self.wind, text = 'Add new record')
        frame.grid (row = 0, column = 1)

        Label (frame, text = 'Name: ').grid (row = 1, column = 1)
        self.name = Entry (frame)
        self.name.grid(row = 1, column = 2)

        Label (frame, text = 'Price: ').grid (row = 2, column = 1)
        self.price = Entry (frame)
        self.price.grid(row = 2, column = 2)

        ttk.Button (frame, text= 'Add record').grid (row = 3, column =2 )
        self.message = Label (text = '',fg = 'red')
        self.message.grid (row = 3, column = 0)

        self.tree = ttk.Treeview (height = 10, colum =2)
        self.tree.grid(row = 4, column = 0, columnspan = 2)
        self.tree.heading('#0', text = 'Name', anchor = W)
        self.tree.heading(2, text = 'Price', anchor = W)

        ttk.Button (text = 'Delete record').grid (row = 5, column = 0)
        ttk.Button (text = 'Edit record').grid (row = 5, column = 1)

        self.viewing_records ()



    def run_query (self, query, parameters = ()): # database connection
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            query_result = cursor.execute (query, parameters)
            conn.commit()
        return query_result


    def viewing_records(self):
        records = self.tree.get_children()
        for element in records:
            self.tree.delete (element)
        query = 'SELECT * FROM product ORDER BY name DESC'
        db_rows = self.run_query (query)
        for row in db_rows:
            self.tree.insert ('', 0, text = row[1], values = row[2])

if __name__ == '__main__':
    wind = Tk()
    application = Product (wind)
    wind.mainloop()

2 个答案:

答案 0 :(得分:3)

...
db_path = os.path.join(BASE_DIR, "database.db")
with sqlite3.connect('db_path') as conn:
...

您正在创建名为'db_path'的新数据库文件。

而不是

with sqlite3.connect('db_path') as conn:

你应该

with sqlite3.connect(db_path) as conn:

或者换句话说,使用变量db_path而不是文字字符串'db_path'

为了完整起见,您可能还想使用已经定义的Product.db_name而不是硬编码'database.db'

...
db_path = os.path.join(BASE_DIR, self.db_name)
with sqlite3.connect(db_path) as conn:
...

答案 1 :(得分:1)

这将创建一个名为db_path的变量,其中包含文件database.db

的路径
db_path = os.path.join(BASE_DIR, "database.db")

但是这使用文字字符串db_path作为要连接的数据库的名称,您刚刚创建的变量的内容:

with sqlite3.connect('db_path') as conn:

要使用该变量,请删除引号:

with sqlite3.connect(db_path) as conn: