You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 4.8中SqliteConnection无CreateFile方法报错CS0117

解决CS0117: SqliteConnection 不包含 CreateFile 定义的问题

问题原因

你当前使用的是Microsoft.Data.Sqlite库,但SqliteConnection.CreateFile是System.Data.SQLite库独有的静态方法,两者是不同的SQLite实现,因此会出现该错误。另外你安装的sqlite-net是轻量级ORM库,和这两个ADO.NET实现并不兼容。

解决方案

方案1:继续使用Microsoft.Data.Sqlite(推荐)

SQLite会自动创建不存在的数据库文件,完全不需要手动调用CreateFile。直接移除创建文件的代码即可,连接打开时若文件不存在会自动生成:

[TestMethod]
public void TestMethod1()
{
    string connectionString = "Data Source=MyDatabase.sqlite;Version=3;";
    using (SqliteConnection m_dbConnection = new SqliteConnection(connectionString))
    {
        m_dbConnection.Open();

        string sql = "Create Table highscores (name varchar(20), score int)";
        using (SqliteCommand command = new SqliteCommand(sql, m_dbConnection))
        {
            command.ExecuteNonQuery();
        }

        sql = "Insert into highscores (name, score) values ('Me', 9001)";
        using (SqliteCommand command = new SqliteCommand(sql, m_dbConnection))
        {
            command.ExecuteNonQuery();
        }
    }
}

注:改用using语句自动释放连接和命令对象,比手动调用Close()更安全,符合.NET最佳实践。

方案2:手动创建空数据库文件(特殊需求场景)

如果确实需要提前创建空文件,可使用.NET原生File类实现,无需依赖SQLite库:

[TestMethod]
public void TestMethod1()
{
    string dbPath = "MyDatabase.sqlite";
    // 文件不存在时创建空文件
    if (!File.Exists(dbPath))
    {
        using (File.Create(dbPath)) { }
    }

    string connectionString = $"Data Source={dbPath};Version=3;";
    using (SqliteConnection m_dbConnection = new SqliteConnection(connectionString))
    {
        m_dbConnection.Open();

        string sql = "Create Table highscores (name varchar(20), score int)";
        using (SqliteCommand command = new SqliteCommand(sql, m_dbConnection))
        {
            command.ExecuteNonQuery();
        }

        sql = "Insert into highscores (name, score) values ('Me', 9001)";
        using (SqliteCommand command = new SqliteCommand(sql, m_dbConnection))
        {
            command.ExecuteNonQuery();
        }
    }
}

方案3:改用System.Data.SQLite库

若你坚持要使用SqliteConnection.CreateFile方法,可卸载Microsoft.Data.Sqlite,安装System.Data.SQLite NuGet包,原代码的CreateFile调用即可正常工作。

单元测试额外建议

为避免测试间相互干扰,建议在测试结束后清理数据库文件:

[TestCleanup]
public void Cleanup()
{
    string dbPath = "MyDatabase.sqlite";
    if (File.Exists(dbPath))
    {
        File.Delete(dbPath);
    }
}

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 17:42:22