Is there a formal way to check if a file selected is a database in sqlite3 for python?

Viewed 63

I am using sqlite3 in python. Currently I am using this following code

try:
    con = sqlite3.connect(filename)
    cur = con.cursor()

    # run a fake query to test if the file selected is really a database
    cur.execute("SELECT DISTINCT id FROM handle ORDER BY id DESC")
except:
    eel.invalidFile()
else:
    ExamineTable.printPhoneNum(con)

and it works fine. I am running a fake query to test for a real database, because I found that without this line users could select files that aren't databases and no exception would be thrown when sqlite3 tries to connect. Which might be by design, but I'm wondering if there's a more formal way of checking without running a dummy query?

1 Answers

PRAGMA integrity_check or PRAGMA quick_check can be used to verify that the file is a valid SQLite database. This will raise sqlite3.DatabaseError if the file is not a valid SQLite database or if it has any of the problems described in the documentation.

con = sqlite3.connect(filename)
cur = con.cursor()

try:
    cur.execute("PRAGMA integrity_check")
except sqlite3.DatabaseError:
    eel.invalidFile()
    con.close()
else:
    ExamineTable.printPhoneNum(con)

See also: How to tell if sqlite database file is valid or not?

Related