Python Sqlite3 Get Sqlite Connection Path

Given the sqlite3 connection object, how to get the path to sqlite3 file?

+13
source share
3 answers

The Python connection object does not store this information.

You can save the path before opening the connection:

path = '/path/to/database/file.db' conn = sqlite3.connect(path) 

or you can ask the database itself what connections it has using the database_list pragma :

 for id_, name, filename in conn.execute('PRAGMA database_list'): if name == 'main' and filename is not None: path = filename break 

If you used the connection URI (connection with the sqlite3.connect() parameter uri=True ), the file name will not include the URI parameters or the file:// prefix.

+13
source

We can use the PRAGMA database_list command.

 cur = con.cursor() cur.execute("PRAGMA database_list") rows = cur.fetchall() for row in rows: print(row[0], row[1], row[2]) 

The third parameter (line [2]) is the name of the database file. Please note that more databases can be added to the SQLite engine.

 $ ./list_dbs.py 0 main /home/user/dbs/test.db 2 movies /home/user/dbs/movies.db 

The above is an example of the output of a script that contains Python code.

+19
source

Link to Martijn Pieters, except that hard coding is mandatory, you must do this:

 path = os.path.dirname(os.path.abspath(__file__)) db = os.path.join(path, 'file.db') conn = sqlite3.connect(db) 
0
source

All Articles