Python Sqlite3 Get Sqlite Connection path

后端 未结 3 786
囚心锁ツ
囚心锁ツ 2021-02-18 17:59

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

3条回答
  •  死守一世寂寞
    2021-02-18 18:36

    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.

提交回复
热议问题