简体   繁体   English

是否有正式的方法来检查所选文件是否是 sqlite3 for python 中的数据库?

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

I am using sqlite3 in python.我在 python 中使用 sqlite3。 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.我正在运行一个假查询来测试一个真实的数据库,因为我发现如果没有这条线,用户可以选择不是数据库的文件,并且当 sqlite3 尝试连接时不会抛出异常。 Which might be by design, but I'm wondering if there's a more formal way of checking without running a dummy query?这可能是设计使然,但我想知道是否有更正式的检查方式而不运行虚拟查询?

PRAGMA integrity_check or PRAGMA quick_check can be used to verify that the file is a valid SQLite database. PRAGMA integrity_checkPRAGMA quick_check可用于验证文件是否为有效的 SQLite 数据库。 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.如果文件不是有效的 SQLite 数据库或者存在文档中描述的任何问题,这将引发sqlite3.DatabaseError

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?另请参阅:如何判断 sqlite 数据库文件是否有效?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM