SQLite:第一次无法打开数据库,不是第二次吗?

SQLite: unable to open database the first time, not the second?

我在 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。现在,如果我重新打开我的程序然后再次访问该文件(相同的代码,唯一的区别是该文件尚未被程序'newly created',它现在已经存在),它工作正常并且不崩溃了。

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

File.Createreturns一个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.
}