How to tell if sqlite database file is valid or not

生来就可爱ヽ(ⅴ<●) 提交于 2020-02-20 06:36:28

问题


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
}

回答1:


sqlite opens databases lazily. Just do something immediately after opening that requires it to be a database.

The best is probably pragma schema_version;.

  • 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.

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.

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.




回答2:


For anyone needing to do this in C# with System.Data.SQLite you can start a transaction, and then immediately roll it back as follows:-

    private bool DatabaseIsValid(string filename)
    {
        using (SQLiteConnection db = new SQLiteConnection(@"Data Source=" + filename + ";FailIfMissing=True;"))
        {
            try
            {
                db.Open();
                using (var transaction = db.BeginTransaction())
                {
                    transaction.Rollback();
                }
            }
            catch (Exception ex)
            {
                log.Debug(ex.Message, ex);
                return false;
            }
        }
        return true;
    }

If the file is not a valid database the following SQLiteException is thrown - file is encrypted or is not a database (System.Data.SQLite.SQLiteErrorCode.NotADb). If you aren't using encrypted databases then this solution should be sufficient. (Only the 'db.Open()' was required for version 1.0.81.0 of System.Data.SQLite but when I upgraded to version 1.0.91.0 I had to insert the inner using block to get it to work).




回答3:


I think a pragma integrity_check could do it.



来源:https://stackoverflow.com/questions/3888529/how-to-tell-if-sqlite-database-file-is-valid-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!