.NET中輕松應用SQLite:零配置數據庫引擎的完美指南
SQLite 是一種輕量級的嵌入式數據庫引擎,它在 .NET 中被廣泛使用。SQLite 是一個零配置的數據庫引擎,不需要服務器,可以直接在應用程序中使用。下面是一個簡單的示例,演示如何在 .NET 中使用 SQLite,并提供了常見的查詢、增加、修改和刪除功能。
首先,你需要在項目中安裝 System.Data.SQLite 包。你可以使用 NuGet 包管理器或通過 Package Manager Console 執行以下命令:
Install-Package System.Data.SQLite
接下來,創建一個 C# 文件,例如 SQLiteExample.cs,并添加以下代碼:
using System;
using System.Data.SQLite;
class Program
{
static void Main()
{
// 指定數據庫文件路徑
string dbFilePath = "sample.db";
// 連接字符串
string connectionString = $"Data Source={dbFilePath};Version=3;";
// 創建數據庫連接
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
// 創建表
CreateTable(connection);
// 插入數據
InsertData(connection, "John Doe", 30);
// 查詢數據
QueryData(connection);
// 更新數據
UpdateData(connection, 1, "Updated Name", 35);
// 查詢更新后的數據
QueryData(connection);
// 刪除數據
DeleteData(connection, 1);
// 查詢刪除后的數據
QueryData(connection);
}
}
static void CreateTable(SQLiteConnection connection)
{
using (SQLiteCommand command = new SQLiteCommand(
"CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INTEGER);", connection))
{
command.ExecuteNonQuery();
}
Console.WriteLine("Table created or already exists.");
}
static void InsertData(SQLiteConnection connection, string name, int age)
{
using (SQLiteCommand command = new SQLiteCommand(
"INSERT INTO Users (Name, Age) VALUES (@Name, @Age);", connection))
{
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@Age", age);
command.ExecuteNonQuery();
}
Console.WriteLine("Data inserted.");
}
static void QueryData(SQLiteConnection connection)
{
using (SQLiteCommand command = new SQLiteCommand(
"SELECT * FROM Users;", connection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
Console.WriteLine("Id\tName\tAge");
while (reader.Read())
{
Console.WriteLine($"{reader["Id"]}\t{reader["Name"]}\t{reader["Age"]}");
}
}
}
Console.WriteLine("Data queried.");
}
static void UpdateData(SQLiteConnection connection, int id, string name, int age)
{
using (SQLiteCommand command = new SQLiteCommand(
"UPDATE Users SET Name=@Name, Age=@Age WHERE Id=@Id;", connection))
{
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@Age", age);
command.Parameters.AddWithValue("@Id", id);
command.ExecuteNonQuery();
}
Console.WriteLine("Data updated.");
}
static void DeleteData(SQLiteConnection connection, int id)
{
using (SQLiteCommand command = new SQLiteCommand(
"DELETE FROM Users WHERE Id=@Id;", connection))
{
command.Parameters.AddWithValue("@Id", id);
command.ExecuteNonQuery();
}
Console.WriteLine("Data deleted.");
}
}
請注意,上述示例假設你已經安裝了 System.Data.SQLite 包,并且在項目目錄中創建了一個名為 sample.db 的 SQLite 數據庫文件。在實際應用中,你需要根據自己的需求修改數據庫文件路徑和連接字符串。
這個示例演示了如何創建表、插入數據、查詢數據、更新數據和刪除數據。你可以根據具體的應用場景和需求進行修改和擴展。