我的 Python (TKinter) 程式根據存盤在 SQLite 資料庫中的命名約定重命名檔案。fetch_db()只能執行一次,第二次報錯
“無法打開資料庫檔案”
出現。這是由于path = os.chdir(folder_selection.get()),沒有它fetch_db()可以執行多次。
相關代碼:
import sqlite3
import os
from tkinter import *
def fetch_db():
connection = sqlite3.connect("database/database.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM employees")
emp_rows = cursor.fetchall()
connection.commit()
connection.close()
return emp_rows
def rename():
db_data = fetch_db()
#print(db_data)
path = os.chdir(folder_selection.get())
#TKINTER UI
root = Tk()
root.title("Lohnabrechnung hochladen")
root.geometry("600x600")
# Select folder & Button
folder_selection = Entry(root, width=80)
folder_selection.grid(row=6, column=0, sticky=W, padx=10)
select_f = Button(root, text="Rename", command=rename)
select_f.grid(row=7,column=0, sticky=W, padx=10)
root.mainloop()
圖片
os 模塊與 SQLite 資料庫結合是否會導致問題?
uj5u.com熱心網友回復:
問題不在于 os 模塊,而在于您使用的是資料庫檔案的相對路徑。當您更改作業目錄時,相對路徑不再有效,因為它是相對于作業目錄的。
您應該在程式啟動時計算絕對路徑并將其保存在變數中。這樣,當您更改作業目錄時,絕對路徑將繼續有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/510175.html
上一篇:如何插入strftime的輸出?
