在 C 中使用 SQLite 创建简单的 CRUD

首先,我们需要为我们的应用程序添加 SQLite 支持。有两种方法可以做到这一点

  • SQLite 下载页面下载适合你系统的 DLL,然后手动添加到项目中
  • 通过 NuGet 添加 SQLite 依赖项

我们将采取第二种方式

首先打开 NuGet 菜单

StackOverflow 文档

并搜索 System.Data.SQLite ,选择它并单击 Install

StackOverflow 文档

也可以使用 Package Manager Console 进行安装

PM> Install-Package System.Data.SQLite

或仅限核心功能

PM> Install-Package System.Data.SQLite.Core 

这就是下载,所以我们可以直接进行编码。

首先使用此表创建一个简单的 SQLite 数据库,并将其作为文件添加到项目中

CREATE TABLE User(
  Id INTEGER PRIMARY KEY AUTOINCREMENT,
  FirstName TEXT NOT NULL,
  LastName TEXT NOT NULL
);

另外不要忘记设置复制到输出目录文件的属性是否有更新的复制拷贝始终,根据你的需求

StackOverflow 文档

创建一个名为 User 的类,它将是我们数据库的基本实体

private class User
{
    public string FirstName { get; set; }
    public string Lastname { get; set; }
}

我们将编写两种查询执行方法,第一种用于插入,更新或从数据库中删除

private int ExecuteWrite(string query, Dictionary<string, object> args)
{
    int numberOfRowsAffected;

    //setup the connection to the database
    using (var con = new SQLiteConnection("Data Source=test.db"))
    {
        con.Open();
        
        //open a new command
        using (var cmd = new SQLiteCommand(query, con))
        {
            //set the arguments given in the query
            foreach (var pair in args)
            {
                cmd.Parameters.AddWithValue(pair.Key, pair.Value);
            }

            //execute the query and get the number of row affected
            numberOfRowsAffected = cmd.ExecuteNonQuery();
        }

        return numberOfRowsAffected;
    }
}

第二个是从数据库中读取的

private DataTable Execute(string query)
{
    if (string.IsNullOrEmpty(query.Trim()))
        return null;

    using (var con = new SQLiteConnection("Data Source=test.db"))
    {
        con.Open();
        using (var cmd = new SQLiteCommand(query, con))
        {
            foreach (KeyValuePair<string, object> entry in args)
            {
                cmd.Parameters.AddWithValue(entry.Key, entry.Value);
            }

            var da = new SQLiteDataAdapter(cmd);

            var dt = new DataTable();
            da.Fill(dt);

            da.Dispose();
            return dt;
        }
    }
}

现在让我们进入我们的 CRUD 方法

添加用户

private int AddUser(User user)
{
    const string query = "INSERT INTO User(FirstName, LastName) VALUES(@firstName, @lastName)";

    //here we are setting the parameter values that will be actually 
    //replaced in the query in Execute method
    var args = new Dictionary<string, object>
    {
        {"@firstName", user.FirstName},
        {"@lastName", user.Lastname}
    };

    return ExecuteWrite(query, args);
}

编辑用户

private int EditUser(User user)
{
    const string query = "UPDATE User SET FirstName = @firstName, LastName = @lastName WHERE Id = @id";

    //here we are setting the parameter values that will be actually 
    //replaced in the query in Execute method
    var args = new Dictionary<string, object>
    {
        {"@id", user.Id},
        {"@firstName", user.FirstName},
        {"@lastName", user.Lastname}
    };

    return ExecuteWrite(query, args);
}

删除用户

private int DeleteUser(User user)
{
    const string query = "Delete from User WHERE Id = @id";

    //here we are setting the parameter values that will be actually 
    //replaced in the query in Execute method
    var args = new Dictionary<string, object>
    {
        {"@id", user.Id}
    };

    return ExecuteWrite(query, args);
}

通过 Id 获取用户

private User GetUserById(int id)
{
    var query = "SELECT * FROM User WHERE Id = @id";

    var args = new Dictionary<string, object>
    {
        {"@id", id}
    };

    DataTable dt = ExecuteRead(query, args);

    if (dt == null || dt.Rows.Count == 0)
    {
        return null;
    }

    var user = new User
    {
        Id = Convert.ToInt32(dt.Rows[0]["Id"]),
        FirstName = Convert.ToString(dt.Rows[0]["FirstName"]),
        Lastname = Convert.ToString(dt.Rows[0]["LastName"])
    };

    return user;
}