python - 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 文件)。所以有人知道我做错了吗???
解决方案
找到了答案。原来它与路径无关。方法“populate_attributes()”试图在创建表之前从表中获取值,因为该方法被类 Data 的init()调用。
推荐阅读
- ubuntu - 如何将带有系统库的应用程序打包到 AppImage 中
- java - 如何使这个 testNG 测试动态但保持并行
- html - 选中复选框时更改样式 - Vue
- javascript - 烧瓶服务器从 JS 休息调用返回 400 错误代码
- python - 使用 for 循环来分隔表单集
只在表格之间,不在开头或结尾 - javascript - 向迭代器添加“return”方法的 JavaScript 无法正确关闭迭代器
- javascript - 如何使用正则表达式选择 CSS 文本?
- python - 如何使用熊猫获取单个标题列单元格值?
- python - 如何将目录的一部分复制到新目录中?
- python - OSError: [Errno 9] 安装 pip 时文件描述符错误