LoginSignup
2
2

More than 1 year has passed since last update.

SQLite-net-pclで直接SQL文を実行してみる

Posted at

動機

大きなプロジェクト書くときにお世話になる内部データベース
中でも多くの人が使うであろうSQLite-net-pclについて直接SQL文を実行する方法が日本語で紹介されておらず苦労したので紹介する

メリット

中には「直接SQL文実行させなくてもInsertとかDeleteで扱えばいいじゃん」と思うかもしれない
しかし条件を絞って消したいときはどうしたらよいだろう
例えば1回入力でIn,もう一回入力でOutのような簡単なログインアプリを想像しよう
当然アプリを閉じてもIn状態をキープしておきたいので内部デタベの中にIn状態のデータを格納する
しかしOutにするときユーザーごとに内部データを削除したい、実際条件付きでDeleteすることはできるのだが直接SQL文を実行した方が行数が少なくまた簡素に仕上がる
当然単純なデーターベース操作ならいいが複雑になればなるほどSQL文を実行させてあげたほうが良い

書き方

書き方は非常に簡単だ
string型の文字列にSQL文を格納する
今回は例として名前が太郎というデータを削除してみよう
Nugetパッケージの管理にて以下のパッケージを追加する
image.png

Mainwindow.xaml.cs
//参照の追加
using SQLite;
//データベース
public class DatabaseTable
        {
            public DatabaseTable() { }
            public DatabaseTable(
                        string? time, 
                        string? id, 
                        string? name)
            {
                this.Time = time;
                this.evac_id = id;
                this.first_name = name;
                }
            [AutoIncrement, PrimaryKey]
            public int? ID { get; set; } //主キー
            public string? Time { get; set; } //時間
            public string? id { get; set; } //ID
            public string? name { get; set; } //名前
            }


//SQLite操作
public MainWindow()
    {
    string SQLiteCommand = "DELETE FROM DatabaseTable WHERE name == '太郎';
    using (SQLiteConnection connection = new SQLiteConnection(データベースのPATH))
    {
        SQLiteCommand cmd = connection.CreateCommand("?");
        cmd.CommandText = SQLiteCommand;
        cmd.ExecuteNonQuery();
    }
}

SQLiteデータベースの管理には次のGUIアプリケーションがオススメだ
注意点としてprogramfileなど管理者権限が必要な場所にファイルがおかれている場合管理者権限でアプリを立ち上げる必要がある

実行環境

VisualStudio2022Community
.NetCore3.1(LTS)
アプリ種WPFアプリケーション

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2