首页 > 解决方案 > sqlite3的路径有问题吗?

问题描述

我使用 lubuntu 创建了我的第一个 tkinter+sqlite 应用程序,它运行良好,但是当我在 Windows 上运行它时,我不断收到找不到数据库的错误。

这是我的代码:

class App():
    ...

class Data():

    def __init__(self, username=None, password=None, inst=None):
        self.serverlist = []
        self.username = username
        self.password = password
        self.inst = inst
        self.populate_serverlist()
        self.populate_attributes()
        print(self.username + self.password + self.inst)

    def populate_serverlist(self):
        ...

    def populate_attributes(self):
        ...

    def add_new_profile(self, username, password, inst):
        ...

    def get_profile(self):
        ...

    @staticmethod
    def run_query(sql, data=None, receive=False):
        conn = sqlite3.connect("profile.db")
        cursor = conn.cursor()
        if data:
            cursor.execute(sql, data)
        else:
            cursor.execute(sql)

        if receive:
            return cursor.fetchall()
        else:
            conn.commit()

        conn.close()

    u/staticmethod
    def first_timeDB():
        create_table = "CREATE TABLE profile (username text, password text, inst text)"
        Data.run_query(create_table)


if __name__ == '__main__':
    app = App()

    if not os.path.isfile("profile.db"):
        app.data.first_timeDB()

    app.mainloop()

我尝试将“profile.db”替换为完整路径('C:\User\Doc\profile.db'),但仍然找不到。

然后我也尝试了这个技巧但也没有用,这是修改后的代码:

class Data():
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(BASE_DIR, "profile.db")

    ...
    def run_query(sql, data=None, receive=False):
        conn = sqlite3.connect(db_path)

我收到“NameError: name 'db_path' is not defined”错误(即使它根据我的代码创建了 profile.db 文件)。所以有人知道我做错了吗???

标签: python

解决方案


找到了答案。原来它与路径无关。方法“populate_attributes()”试图在创建表之前从表中获取值,因为该方法被类 Data 的init()调用。


推荐阅读