在 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;
}