3

I am running Python3 on my Mac testing simple sql database. I have the below code

import sqlite3

# connecting to the database
connection = sqlite3.connect("myTable.db")
crsr = connection.cursor()

# SQL command to create a table in the database
sql_command = """CREATE TABLE emp (
staff_number INTEGER PRIMARY KEY,
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1),
joining DATE);"""

# execute the statement
crsr.execute(sql_command)

# SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUES (23, "Rishabh", "Bansal", "M", "2014-03-28");"""
crsr.execute(sql_command)

crsr.execute(sql_command)
connection.commit()
connection.close()

When I run this code, I am getting error:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    connection = sqlite3.connect("myTable.db")
sqlite3.OperationalError: unable to open database file

What am I missing? I tried replacing ("myTable.db") with (".myTable.db") and ("./myTable.db") but same issue. Please suggest.

1
  • 2
    One possibility is that the Python process's current working directory is not what you expect. Try adding print(os.getcwd()) to your script as a debugging aid. Commented Apr 17, 2018 at 20:03

1 Answer 1

4

Change permissions to SQLite db file.

Ubuntu

sudo chmod 775 /FolderOfSQLiteDBfile/
sudo chmod 664 /FolderOfSQLiteDBfile/sqlite.db

Windows

chmod 775 /FolderOfSQLiteDBfile/

Refer : sqlite-error-unable-to-open-database-file

Sign up to request clarification or add additional context in comments.

3 Comments

A database is a sensible thing. Make sure the permissions are set for minimal access. The permissions above allow quite extensive access (read access for all users).
I had the same issue for a couple of days. Since I was trying to access the database through Apache, I added www-data to the group and gave it the required permissions. It worked. But then I realised that it only works the first time after I have given it the permissions, then it reverts back to the original permissions. So I had to make www-data the owner
I think 770 for db and 660 for containing directories is enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.