From Python's sqlite3 library, how can we determine if a connection belongs to a in-memory database?
import sqlite3
conn = sqlite3.connect(':memory:')
def is_in_memory_connection(conn):
# How to check if `conn` is an in-memory connection?
Is it possible to check the filename of an on-disk database? If so, I would presume that it would return None
for an in-memory database.
CodePudding user response:
This is the closest I could come up with:
import sqlite3
def is_in_memory_connection(conn):
local_cursor = conn.cursor()
local_cursor.execute('pragma database_list')
rows = local_cursor.fetchall()
print(rows[0][2])
return rows[0][2] == ''
#database = 'test.sqlite'
database = ':memory:'
conn = sqlite3.connect(database)
result = is_in_memory_connection(conn)
print(result)
If you have an in-memory database, database_list will show equivalent of this:
sqlite> pragma database_list;
seq name file
--- ---- ----
0 main
If you are opening a file that's on disk, it'll show the path of the file equivalent of this:
sqlite> pragma database_list;
seq name file
--- ---- --------------------------
0 main /home/testing/test.sqlite
Taking advantage of this, you could call pragma database_list
to show the file. If the path is empty, the database is not associated with a file.