SQLite 是一個(gè)輕量級(jí)的嵌入式數(shù)據(jù)庫(kù),它適用于小型到中型的應(yīng)用場(chǎng)景。SQLite在C#中的應(yīng)用非常廣泛,支持跨平臺(tái)開(kāi)發(fā),并且非常易于使用。下面我們將詳細(xì)介紹如何在C#中使用SQLite,并提供詳細(xì)的例子。
特點(diǎn)
輕量級(jí):SQLite 是一個(gè)嵌入式數(shù)據(jù)庫(kù),不需要獨(dú)立的服務(wù)器進(jìn)程,它是一個(gè)C庫(kù),可以集成到主程序中。
跨平臺(tái):SQLite 支持包括Windows、Linux、macOS在內(nèi)的多個(gè)平臺(tái)。
自包含:SQLite 的數(shù)據(jù)庫(kù)是單個(gè)文件,非常適合移動(dòng)應(yīng)用和其他需要便攜性的應(yīng)用。
豐富的功能:支持事務(wù)、跨多個(gè)表的復(fù)雜查詢(xún)、視圖、觸發(fā)器等。
環(huán)境配置
安裝SQLite NuGet包
dotnet add package System.Data.SQLite.Core
基礎(chǔ)操作示例
1. 創(chuàng)建并連接SQLite數(shù)據(jù)庫(kù)
首先,我們需要?jiǎng)?chuàng)建一個(gè)SQLite數(shù)據(jù)庫(kù),并連接到該數(shù)據(jù)庫(kù)。
private void btnCreateDb_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=demo.db;Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
MessageBox.Show("SQLite database connection open.");
}
}
2. 創(chuàng)建表
創(chuàng)建一個(gè)名為 users
的表,用于存儲(chǔ)用戶(hù)信息。
private void btnCreateTable_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=demo.db;Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)";
using (var command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
MessageBox.Show("Table 'users' created.");
}
}
}
3. 插入數(shù)據(jù)
往 users
表中插入用戶(hù)數(shù)據(jù)。
private void btnInsert_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=demo.db;Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = "INSERT INTO users (name, age) VALUES ('Alice', 30)";
using (var command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
MessageBox.Show("Data inserted into 'users' table.");
}
}
}
4. 查詢(xún)數(shù)據(jù)
從 users
表中查詢(xún)數(shù)據(jù),并打印輸出。
private void btnQuery_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=demo.db;Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = "SELECT * FROM users";
using (var command = new SQLiteCommand(sql, connection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
MessageBox.Show($"ID: {reader["id"]}, Name: {reader["name"]}, Age: {reader["age"]}");
}
}
}
}
}
5. 更新數(shù)據(jù)
更新 users
表中的數(shù)據(jù)。
using System;
using System.Data.SQLite;
class Program
{
static void Main()
{
string connectionString = "Data Source=demo.db;Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = "UPDATE users SET age = 31 WHERE name = 'Alice'";
using (var command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Data updated in 'users' table.");
}
}
}
}
6. 刪除數(shù)據(jù)
從 users
表中刪除數(shù)據(jù)。
using System;
using System.Data.SQLite;
class Program
{
static void Main()
{
string connectionString = "Data Source=demo.db;Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = "DELETE FROM users WHERE name = 'Alice'";
using (var command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Data deleted from 'users' table.");
}
}
}
}
一個(gè)簡(jiǎn)單倉(cāng)儲(chǔ)類(lèi)
用戶(hù)模型類(lèi)
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
我們創(chuàng)建一個(gè)用戶(hù)倉(cāng)儲(chǔ)類(lèi),包含基本的CRUD(Create, Read, Update, Delete)操作:
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppSqlLite
{
public class UserRepository
{
private string _connectionString;
public UserRepository(string connectionString)
{
_connectionString = connectionString;
InitializeDatabase();
}
private void InitializeDatabase()
{
using (var connection = new SQLiteConnection(_connectionString))
{
connection.Open();
string sql = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)";
using (var command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
}
}
}
public void AddUser(User user)
{
using (var connection = new SQLiteConnection(_connectionString))
{
connection.Open();
string sql = "INSERT INTO users (name, age) VALUES (@name, @age)";
using (var command = new SQLiteCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", user.Name);
command.Parameters.AddWithValue("@age", user.Age);
command.ExecuteNonQuery();
}
}
}
public User GetUser(int id)
{
using (var connection = new SQLiteConnection(_connectionString))
{
connection.Open();
string sql = "SELECT * FROM users WHERE id = @id";
using (var command = new SQLiteCommand(sql, connection))
{
command.Parameters.AddWithValue("@id", id);
using (SQLiteDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
return new User
{
Id = Convert.ToInt32(reader["id"]),
Name = reader["name"].ToString(),
Age = Convert.ToInt32(reader["age"])
};
}
}
}
}
return null;
}
public List<User> GetAllUsers()
{
List<User> users = new List<User>();
using (var connection = new SQLiteConnection(_connectionString))
{
connection.Open();
string sql = "SELECT * FROM users";
using (var command = new SQLiteCommand(sql, connection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
users.Add(new User
{
Id = Convert.ToInt32(reader["id"]),
Name = reader["name"].ToString(),
Age = Convert.ToInt32(reader["age"])
});
}
}
}
}
return users;
}
public void UpdateUser(User user)
{
using (var connection = new SQLiteConnection(_connectionString))
{
connection.Open();
string sql = "UPDATE users SET name = @name, age = @age WHERE id = @id";
using (var command = new SQLiteCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", user.Name);
command.Parameters.AddWithValue("@age", user.Age);
command.Parameters.AddWithValue("@id", user.Id);
command.ExecuteNonQuery();
}
}
}
public void DeleteUser(int id)
{
using (var connection = new SQLiteConnection(_connectionString))
{
connection.Open();
string sql = "DELETE FROM users WHERE id = @id";
using (var command = new SQLiteCommand(sql, connection))
{
command.Parameters.AddWithValue("@id", id);
command.ExecuteNonQuery();
}
}
}
}
}
private void btnRepository_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=demo.db;Version=3;";
UserRepository userRepository = new UserRepository(connectionString);
// 添加用戶(hù)
User user = new User { Name = "Alice", Age = 30 };
userRepository.AddUser(user);
MessageBox.Show("User added.");
// 獲取用戶(hù)
User retrievedUser = userRepository.GetUser(1);
MessageBox.Show($"Retrieved User: ID={retrievedUser.Id}, Name={retrievedUser.Name}, Age={retrievedUser.Age}");
// 更新用戶(hù)
retrievedUser.Age = 31;
userRepository.UpdateUser(retrievedUser);
MessageBox.Show("User updated.");
// 獲取所有用戶(hù)
var users = userRepository.GetAllUsers();
MessageBox.Show("All users:");
foreach (var u in users)
{
MessageBox.Show($"ID={u.Id}, Name={u.Name}, Age={u.Age}");
}
// 刪除用戶(hù)
userRepository.DeleteUser(1);
MessageBox.Show("User deleted.");
}
結(jié)論
本文介紹了如何在C#中使用SQLite以及一些常見(jiàn)的數(shù)據(jù)庫(kù)操作。SQLite 是一個(gè)強(qiáng)大的嵌入式數(shù)據(jù)庫(kù),適用于各種應(yīng)用場(chǎng)景。希望通過(guò)本文的介紹,您能夠輕松地在C#項(xiàng)目中使用SQLite進(jìn)行數(shù)據(jù)庫(kù)操作。
該文章在 2024/8/1 9:01:56 編輯過(guò)