[PYTHON] OperationalError in SQLAlchemy + SQLite3

Thing you want to do

--I want to use SQLite3 with SQLAlchemy --I want to specify the DB file with an absolute path

environment

Python3.8.1 on alpine linux 3.11 on Docker

What happened

I wrote the following code, expecting a DB file to be created in / var / data

engine = create_engine("sqlite:///var/data/project.sqlite3")
...

When I ran it, I was angry that I couldn't open the database file

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file

Investigation

/ var / data mounts the directory on the host OS side to the container, but the testfile created by the operation on the host OS side also looks correct.

# ls -la /var/data/
total 16
drwxrwxr-x    2 1006     1006          4096 Apr 11 00:41 .
drwxr-xr-x    1 root     root          4096 Apr 11 00:41 ..
-rw-r--r--    1 root     root             0 Apr 11 00:41 testfile

Solution

I doubted how to specify the path and checked the official documentation.

SQLite — SQLAlchemy 1.3 Documentation

This means that the actual filename to be used starts with the characters to the right of the third slash.

relative path

e = create_engine('sqlite:///path/to/database.db')



 Relative paths are slashes ** 3 **.


> An absolute path, which is denoted by starting with a slash, means you need **four** slashes

> ```python
# absolute path
e = create_engine('sqlite:////path/to/database.db')

If you want to use an absolute path, there are ** 4 slashes **.

orz...

What I wanted to do was specify the ** absolute path ** to /var/data/project.sqlite3, so

sqlite:///var/data/project.sqlite3

Instead, it had to be specified as follows

sqlite:////var/data/project.sqlite3

engine = create_engine("sqlite:////var/data/project.sqlite3")
...

Congratulations on fixing the code and it now works correctly.

Recommended Posts

OperationalError in SQLAlchemy + SQLite3
Sqlite in python
In python + sqlite3 "OperationalError: no such column:"
Table definition in SQLAlchemy
Save Time type in SQLAlchemy
How to handle session in SQLAlchemy
How to use SQLite in Python
(sqlalchemy) Display text in select field
Start SQLite in a programming language
Foreign Key in Python SQLite [Note]
sqlalchemy
Code required for API conversion in sqlalchemy