How to tell if sqlite database file is valid or not

前端 未结 3 658
天涯浪人
天涯浪人 2021-02-19 02:06

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

3条回答
  •  醉话见心
    2021-02-19 02:48

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

提交回复
热议问题