---
# System prepended metadata

title: C# SQLite
tags: [C#]

---

# C# SQLite
寫法上就很像[C# with SQL server](/HAolEMikSsmjez3_6CzAXA) 我就大概舉幾個例子就會懂
SQLite 不需要額外安裝資料庫伺服器，你可以直接建立一個 .sqlite 或 .db 檔案。
[TOC]

## 安裝 SQLite
在NuGet下載 
![image](https://hackmd.io/_uploads/B1l_ktos3yg.png=50%)
## 建立 SQLite 資料庫
```csharp=
using System;
using System.Data.SQLite;

class Program
{
    static void Main()
    {
        string dbPath = "Data Source=mydatabase.sqlite;Version=3;";
        
        using (SQLiteConnection conn = new SQLiteConnection(dbPath))
        {
            conn.Open();

            string sql = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY, Name TEXT, Age INTEGER)";
            using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
            {
                cmd.ExecuteNonQuery();
            }
            Console.WriteLine("資料庫建立完成");
        }
    }
}
```
這樣就建立了一個 mydatabase.sqlite 資料庫，並新增一個 Users 資料表。
## 插入資料
```csharp=
using System;
using System.Data.SQLite;

class Program
{
    static void Main()
    {
        string dbPath = "Data Source=mydatabase.sqlite;Version=3;";
        using (SQLiteConnection conn = new SQLiteConnection(dbPath))
        {
            conn.Open();
            string sql = "INSERT INTO Users (Name, Age) VALUES (@name, @age)";
            using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
            {
                cmd.Parameters.AddWithValue("@name", "Anna");
                cmd.Parameters.AddWithValue("@age", 25);
                cmd.ExecuteNonQuery();
            }
            Console.WriteLine("插入成功");
        }
    }
}
```
## 查詢資料
```csharp=
using System;
using System.Data.SQLite;

class Program
{
    static void Main()
    {
        string dbPath = "Data Source=mydatabase.sqlite;Version=3;";
        using (SQLiteConnection conn = new SQLiteConnection(dbPath))
        {
            conn.Open();
            string sql = "SELECT * FROM Users";
            using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
            {
                using (SQLiteDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine($"ID: {reader["Id"]}, Name: {reader["Name"]}, Age: {reader["Age"]}");
                    }
                }
            }
        }
    }
}
```
## 更新與刪除
### 更新資料
```csharp=
string sql = "UPDATE Users SET Age = @age WHERE Name = @name";
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
    cmd.Parameters.AddWithValue("@age", 30);
    cmd.Parameters.AddWithValue("@name", "Anna");
    cmd.ExecuteNonQuery();
}
```
### 刪除資料
```csharp=
string sql = "DELETE FROM Users WHERE Name = @name";
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
    cmd.Parameters.AddWithValue("@name", "Anna");
    cmd.ExecuteNonQuery();
}
```
## SQLite 內建在 C# 的優勢
✅ 無需安裝 SQL Server 或 MySQL
✅ 單一 .sqlite 檔案即可運行
✅ 適用於小型應用程式、桌面應用程式

如果你的應用程式不需要多人同時存取，SQLite 會是個很好的選擇！


