【问题标题】:SQLite: unable to open database the first time, not the second?SQLite:第一次无法打开数据库,不是第二次?
【发布时间】:2020-11-29 19:18:46
【问题描述】:

我在 C# 中使用 SQLite,我首先使用 System.IO 创建一个数据库文件:

System.IO.File.Create(directoryLineEdit.Text + @"\" + nameLineEdit.Text + ".db");

现在,我尝试打开这个新创建的数据库:(其中 location 是存储文件的路径,不要介意 path 参数,即在这里不相关)

public void loadSpaceWalls(string path, string location)
{
    using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + location))
    {
        conn.Open();

        using (SQLiteCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table';";
            cmd.CommandType = System.Data.CommandType.Text;
            SQLiteDataReader rdr = cmd.ExecuteReader();

            Godot.Collections.Array wallsArray = new Godot.Collections.Array();

            while (rdr.Read())
                wallsArray.Add(rdr[0]);

            rdr.Close();
            GetNode(path).Call("updateSpaceWalls", wallsArray);
            wallsArray.Dispose();
        }

        conn.Close();
    }
}

程序因System.Data.SQLite.SQLiteException (0x800007FF): unable to open database file 而崩溃。现在,如果我重新打开我的程序,然后再次访问该文件(相同的代码,唯一的区别是该文件没有被程序“新创建”,它现在已经存在),它工作正常并且不崩溃。

这让我很困惑???? 关于为什么会这样的任何想法?

【问题讨论】:

    标签: c# database sqlite crash


    【解决方案1】:

    File.Create 返回一个FileStream,它保持打开状态。除非您处理该流,否则其他任何东西都无法打开该文件。

    所以我怀疑您需要做的就是将您的代码更改为:

    string dbPath = Path.Combine(directoryLineEdit.Text, $"{nameLineEdit.Text}.db");
    using (File.Create(dbPath))
    {
        // No-op - we just want to create the file and immediately close the stream.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-07
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      相关资源
      最近更新 更多