1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#入門 第14章】SQLiteでデータベース連携!ローカルDBの基本操作まとめ

Last updated at Posted at 2025-08-11

【C#入門 第14章】SQLiteでデータベース連携!ローカルDBの基本操作まとめ

こんにちは、 CSharpTimes の一之瀬シィよ💠
今回はC#アプリに“記憶力”を与えるための武器―― SQLiteデータベース との連携方法を教えてあげるわ!


🧠 SQLiteってなに?

  • 軽量&組み込み型 のデータベース
  • サーバー不要、ファイル1つで完結!
  • C#でも簡単に使えるから、ローカルアプリにピッタリ✨

🛠 準備:NuGetでライブラリ追加

  1. Visual Studio の「ソリューションエクスプローラー」からプロジェクトを右クリック
  2. 「NuGet パッケージの管理」を開く
  3. System.Data.SQLite を検索してインストール!

📦 SQLiteファイルを作成&接続

using System.Data.SQLite;

string dbPath = "Data Source=mydata.db;";
SQLiteConnection conn = new SQLiteConnection(dbPath);
conn.Open();
  • mydata.db というファイルが自動で作られる
  • 接続は .Open() を忘れずに!

🧱 テーブルを作成する

string sql = @"CREATE TABLE IF NOT EXISTS People (
    Id INTEGER PRIMARY KEY AUTOINCREMENT,
    Name TEXT,
    Age INTEGER
)";
SQLiteCommand cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();

✍️ データを追加する

string insert = "INSERT INTO People (Name, Age) VALUES (@name, @age)";
SQLiteCommand cmd = new SQLiteCommand(insert, conn);
cmd.Parameters.AddWithValue("@name", "シィ");
cmd.Parameters.AddWithValue("@age", 20);
cmd.ExecuteNonQuery();

📖 データを読み込む

string select = "SELECT * FROM People";
SQLiteCommand cmd = new SQLiteCommand(select, conn);
SQLiteDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
    Console.WriteLine($"{reader["Id"]}: {reader["Name"]}{reader["Age"]}歳)");
}

✅ 接続を閉じる

conn.Close();

または using を使って自動で閉じるのもスマートね。


📌 まとめ

  • SQLiteはC#で使いやすいローカルDB
  • テーブル作成・データ追加・取得の基本構文はマスターすべし
  • デスクトップアプリに“記憶力”を持たせられるようになる!

次回は、 「第15章:WPFアプリとの違い」 よ。
WinFormsじゃ物足りないって?じゃあWPFの世界も見せてあげるわ💢

1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?