日常更新
This commit is contained in:
270
Ramitta/Database/SQLite.cs
Normal file
270
Ramitta/Database/SQLite.cs
Normal file
@@ -0,0 +1,270 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SQLite;
|
||||
|
||||
namespace Ramitta
|
||||
{
|
||||
public class SQLite : IDisposable
|
||||
{
|
||||
private SQLiteConnection db;
|
||||
private bool disposed = false;
|
||||
|
||||
// 构造函数,初始化数据库连接
|
||||
// 参数: connectionString - 数据库连接字符串
|
||||
// 例如: "Data Source=mydatabase.db;Version=3;"
|
||||
public SQLite(string connectionString)
|
||||
{
|
||||
db = new SQLiteConnection(connectionString);
|
||||
db.Open();
|
||||
}
|
||||
|
||||
// 创建表:根据表名和字段定义创建表
|
||||
// 参数: tableName - 表名
|
||||
// 参数: columns - 字段定义字典,键为字段名,值为字段类型
|
||||
// 例如: CreateTable("Users", new Dictionary<string, string> { {"Id", "INTEGER"}, {"Name", "TEXT"} });
|
||||
public void CreateTable(string tableName, Dictionary<string, string> columns)
|
||||
{
|
||||
// 构建列定义的字符串
|
||||
var columnsDefinition = string.Join(", ", columns.Select(c => $"{c.Key} {c.Value}"));
|
||||
string createTableQuery = $"CREATE TABLE IF NOT EXISTS {tableName} ({columnsDefinition});";
|
||||
|
||||
using (var cmd = new SQLiteCommand(createTableQuery, db))
|
||||
{
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
// 向已存在的表中添加新列
|
||||
// 参数: tableName - 表名
|
||||
// 参数: columnName - 要添加的列名
|
||||
// 参数: columnType - 列的数据类型
|
||||
// 例如: AddColumn("Users", "Email", "TEXT");
|
||||
public void AddColumn(string tableName, string columnName, string columnType)
|
||||
{
|
||||
// 检查表是否存在
|
||||
if (!TableExists(tableName))
|
||||
{
|
||||
throw new ArgumentException($"表 '{tableName}' 不存在");
|
||||
}
|
||||
|
||||
// 检查列是否已存在
|
||||
if (ColumnExists(tableName, columnName))
|
||||
{
|
||||
Console.WriteLine($"列 '{columnName}' 在表 '{tableName}' 中已存在");
|
||||
return;
|
||||
}
|
||||
|
||||
// 构建添加列的SQL语句
|
||||
string addColumnQuery = $"ALTER TABLE {tableName} ADD COLUMN {columnName} {columnType};";
|
||||
|
||||
using (var cmd = new SQLiteCommand(addColumnQuery, db))
|
||||
{
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
Console.WriteLine($"已向表 '{tableName}' 添加列 '{columnName}'");
|
||||
}
|
||||
|
||||
// 检查表是否存在
|
||||
private bool TableExists(string tableName)
|
||||
{
|
||||
string query = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=@tableName;";
|
||||
|
||||
using (var cmd = new SQLiteCommand(query, db))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@tableName", tableName);
|
||||
var result = cmd.ExecuteScalar();
|
||||
return Convert.ToInt32(result) > 0;
|
||||
}
|
||||
}
|
||||
|
||||
// 检查列是否已存在
|
||||
private bool ColumnExists(string tableName, string columnName)
|
||||
{
|
||||
string query = $"PRAGMA table_info({tableName});";
|
||||
|
||||
using (var cmd = new SQLiteCommand(query, db))
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
while (reader.Read())
|
||||
{
|
||||
if (reader["name"].ToString().Equals(columnName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 批量添加多个列
|
||||
// 参数: tableName - 表名
|
||||
// 参数: columns - 字段定义字典,键为字段名,值为字段类型
|
||||
// 例如: AddColumns("Users", new Dictionary<string, string> { {"Email", "TEXT"}, {"Age", "INTEGER"} });
|
||||
public void AddColumns(string tableName, Dictionary<string, string> columns)
|
||||
{
|
||||
foreach (var column in columns)
|
||||
{
|
||||
AddColumn(tableName, column.Key, column.Value);
|
||||
}
|
||||
}
|
||||
|
||||
// 插入数据:向指定表插入一条记录
|
||||
// 参数: tableName - 表名
|
||||
// 参数: columnValues - 字段和对应值的字典
|
||||
// 例如: InsertData("Users", new Dictionary<string, object> { {"Name", "John"}, {"Age", 30} });
|
||||
public void InsertData(string tableName, Dictionary<string, object> columnValues)
|
||||
{
|
||||
// 构建列和参数的字符串
|
||||
var columns = string.Join(", ", columnValues.Keys);
|
||||
var parameters = string.Join(", ", columnValues.Keys.Select(k => "@" + k));
|
||||
|
||||
string insertQuery = $"INSERT INTO {tableName} ({columns}) VALUES ({parameters})";
|
||||
|
||||
using (var cmd = new SQLiteCommand(insertQuery, db))
|
||||
{
|
||||
foreach (var kvp in columnValues)
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@" + kvp.Key, kvp.Value);
|
||||
}
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
// 查询数据:执行任意查询语句并返回结果
|
||||
// 参数: query - SQL查询语句
|
||||
// 参数: parameters - 可选的查询参数字典
|
||||
// 例如: SelectData("SELECT * FROM Users WHERE Age > @age", new Dictionary<string, object> { {"age", 25} });
|
||||
public List<Dictionary<string, object>> SelectData(string query, Dictionary<string, object> parameters = null)
|
||||
{
|
||||
var result = new List<Dictionary<string, object>>();
|
||||
|
||||
using (var cmd = new SQLiteCommand(query, db))
|
||||
{
|
||||
// 添加查询参数(如果有的话)
|
||||
if (parameters != null)
|
||||
{
|
||||
foreach (var kvp in parameters)
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@" + kvp.Key, kvp.Value);
|
||||
}
|
||||
}
|
||||
|
||||
using (SQLiteDataReader reader = cmd.ExecuteReader())
|
||||
{
|
||||
while (reader.Read())
|
||||
{
|
||||
var row = new Dictionary<string, object>();
|
||||
for (int i = 0; i < reader.FieldCount; i++)
|
||||
{
|
||||
row[reader.GetName(i)] = reader.GetValue(i);
|
||||
}
|
||||
result.Add(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// 更新数据:根据条件更新指定表中的记录
|
||||
// 参数: tableName - 表名
|
||||
// 参数: columnValues - 需要更新的字段和对应值的字典
|
||||
// 参数: condition - 更新条件
|
||||
// 例如: UpdateData("Users", new Dictionary<string, object> { {"Age", 31} }, "Name = 'John'");
|
||||
public void UpdateData(string tableName, Dictionary<string, object> columnValues, string condition)
|
||||
{
|
||||
// 构建SET子句
|
||||
var setClause = string.Join(", ", columnValues.Keys.Select(k => $"{k} = @{k}"));
|
||||
string updateQuery = $"UPDATE {tableName} SET {setClause} WHERE {condition}";
|
||||
|
||||
using (var cmd = new SQLiteCommand(updateQuery, db))
|
||||
{
|
||||
foreach (var kvp in columnValues)
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@" + kvp.Key, kvp.Value);
|
||||
}
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
// 删除数据:根据条件删除指定表中的记录
|
||||
// 参数: tableName - 表名
|
||||
// 参数: condition - 删除条件
|
||||
// 例如: DeleteData("Users", "Age < 18");
|
||||
public void DeleteData(string tableName, string condition)
|
||||
{
|
||||
string deleteQuery = $"DELETE FROM {tableName} WHERE {condition}";
|
||||
|
||||
using (var cmd = new SQLiteCommand(deleteQuery, db))
|
||||
{
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
// 支持事务操作:允许在同一个事务中执行多个操作
|
||||
// 参数: transactionActions - 一个包含多个数据库操作的委托
|
||||
// 例如: ExecuteTransaction(() =>
|
||||
// {
|
||||
// InsertData("Users", new Dictionary<string, object> { {"Name", "Alice"}, {"Age", 28} });
|
||||
// UpdateData("Users", new Dictionary<string, object> { {"Age", 29} }, "Name = 'Bob'");
|
||||
// });
|
||||
public void ExecuteTransaction(Action transactionActions)
|
||||
{
|
||||
using (var transaction = db.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
transactionActions.Invoke(); // 执行多个操作
|
||||
transaction.Commit(); // 提交事务
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
transaction.Rollback(); // 回滚事务
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 删除所有表
|
||||
public void DropAllTables()
|
||||
{
|
||||
// 获取所有表名
|
||||
string getTablesQuery = "SELECT name FROM sqlite_master WHERE type='table';";
|
||||
var tables = SelectData(getTablesQuery);
|
||||
|
||||
foreach (var table in tables)
|
||||
{
|
||||
string tableName = table["name"].ToString();
|
||||
string dropTableQuery = $"DROP TABLE IF EXISTS {tableName};";
|
||||
|
||||
using (var cmd = new SQLiteCommand(dropTableQuery, db))
|
||||
{
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 释放资源,关闭数据库连接
|
||||
// 确保数据库连接在对象销毁时被正确关闭
|
||||
public void Dispose()
|
||||
{
|
||||
if (!disposed)
|
||||
{
|
||||
if (db != null && db.State == ConnectionState.Open)
|
||||
{
|
||||
db.Close();
|
||||
db.Dispose();
|
||||
}
|
||||
disposed = true;
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
// 析构函数,调用Dispose释放资源
|
||||
~SQLite()
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user