Home > OS >  Not possible to access SQLite database a second time when using os.chdir
Not possible to access SQLite database a second time when using os.chdir

Time:09-28

My program in Python (TKinter) renames files based on naming conventions which are stored in an SQLite database. fetch_db() can only be executed once, second time the error message

"unable to open database file"

appears. It is due to path = os.chdir(folder_selection.get()), without it fetch_db() can be executed multiple times.

Relevant code :

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()

Image

Does the os module lead to problems in combination with SQLite databases?

CodePudding user response:

The problem isn't the os module, it's that you're using a relative path to the database file. when you change the working directory, the relative path is no longer valid since it's relative to the working directory.

You should compute the absolute path when the program starts up and save it in a variable. That way, when you change the working directory the absolute path will continue to work.

  • Related