如何判断sqlite数据库文件是否有效 [英] How to tell if sqlite database file is valid or not
问题描述
在下面的代码中, pathToNonDatabase
是简单文本文件的路径,而不是真正的sqlite数据库。我希望 sqlite3_open
检测到,但它不( db
不是 NULL
和 result
是 SQLITE_OK
)。那么,如何检测文件不是有效的sqlite数据库?
In the code below, pathToNonDatabase
is the path to a simple text file, not a real sqlite database. I was hoping for sqlite3_open
to detect that, but it doesn't (db
is not NULL
, and result
is SQLITE_OK
). So, how to detect that a file is not a valid sqlite database?
sqlite3 *db = NULL;
int result = sqlite3_open(pathToNonDatabase, &db);
if((NULL==db) || (result!=SQLITE_OK)) {
// invalid database
}
推荐答案
sqlite懒惰地打开数据库。
sqlite opens databases lazily. Just do something immediately after opening that requires it to be a database.
最好的可能是 pragma schema_version;
。
- 如果尚未创建数据库,则报告为0(例如,空文件)。在这种情况下,它是安全的工作(和运行
CREATE TABLE
等) - 如果数据库已创建,模式已经经历了多少修订。
- 如果文件存在且不是数据库(或空),则会收到错误。
- This will report 0 if the database hasn't been created (for instance, an empty file). In this case, it's safe work with (and run
CREATE TABLE
, etc) - If the database has been created, it will return how many revisions the schema has gone through. This value might not be interesting, but that it's not zero is.
- If the file exists and isn't a database (or empty), you'll get an error.
如果你想要一个更彻底的检查,你可以使用 pragma quick_check;
。这是一个较轻的完整性检查,它会跳过检查表的内容与索引对齐。它仍然可能很慢。
If you want a somewhat more thorough check, you can use pragma quick_check;
. This is a lighter-weight integrity check, which skips checking that the contents of the tables line up with the indexes. It can still be very slow.
避免 integrity_check
。它不仅检查每个页面,而且根据索引验证表的内容。这在大型数据库上是积极的冰川。
Avoid integrity_check
. It not only checks every page, but then verifies the contents of the tables against the indexes. This is positively glacial on a large database.
这篇关于如何判断sqlite数据库文件是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!