Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Sqlite3 Get Sqlite Connection path

Tags:

Given an sqlite3 connection object, how can retrieve the file path to the sqlite3 file?

like image 705
omer bach Avatar asked Dec 17 '12 10:12

omer bach


People also ask

How fetch data from sqlite3 database in Python?

SQLite Python: Querying Data First, establish a connection to the SQLite database by creating a Connection object. Next, create a Cursor object using the cursor method of the Connection object. Then, execute a SELECT statement. After that, call the fetchall() method of the cursor object to fetch the data.


2 Answers

The Python connection object doesn't store this information.

You could store the path before you open 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 a connection URI (connecting with the sqlite3.connect() parameter uri=True), the filename will not include the URI parameters or the file:// prefix.

like image 53
Martijn Pieters Avatar answered Oct 01 '22 23:10

Martijn Pieters


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 (row[2]) is the file name of the database. Note that there could be more databases attached to SQLite engine.

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

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

like image 28
Jan Bodnar Avatar answered Oct 02 '22 00:10

Jan Bodnar