C# での SQLite の使用

# C# で SQLite を使用して単純な CRUD を作成する

まず、アプリケーションに SQLite サポートを追加する必要があります。それには 2 つの方法があります

  • お使いのシステムに適した DLL を SQLite ダウンロード ページからダウンロードし、プロジェクトに手動で追加します
  • NuGet を介して SQLite 依存関係を追加

2 番目の方法で行います

最初に NuGet メニューを開きます

System.Data.SQLite を検索します 、それを選択して [インストール] をクリックします

を使用してパッケージ マネージャー コンソールからインストールすることもできます。
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
);

また、出力ディレクトリにコピーを設定することを忘れないでください 新しい場合はコピーするファイルのプロパティ 常にコピー 、あなたのニーズに基づいて

データベースの基本エンティティとなる User というクラスを作成します

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

クエリを実行するための 2 つのメソッドを記述します。1 つ目は、データベースへの挿入、更新、またはデータベースからの削除です。

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

2 つ目はデータベースからの読み取り用です

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

# クエリの実行

using (SQLiteConnection conn = new SQLiteConnection(@"Data Source=data.db;Pooling=true;FailIfMissing=false"))
{
    conn.Open();
    using (SQLiteCommand cmd = new SQLiteCommand(conn))
    {
       cmd.CommandText = "query";
       using (SqlDataReader dr = cmd.ExecuteReader())
       {
           while(dr.Read())
           {
               //do stuff
           }
       }
    }
}

注意 :設定 FailIfMissing true にすると、ファイル data.db が作成されます 行方不明の場合。ただし、ファイルは空になります。そのため、必要なテーブルを再作成する必要があります。