94 lines
3.5 KiB
C#
94 lines
3.5 KiB
C#
using System; // 引入System命名空间,提供基础类型
|
||
using System.Collections.Generic; // 引入集合命名空间,提供泛型集合
|
||
using System.Data; // 引入数据命名空间,提供数据访问基础接口
|
||
using System.Threading; // 引入线程命名空间,提供多线程编程支持
|
||
using MySql.Data.MySqlClient; // 引入MySQL的ADO.NET提供程序命名空间
|
||
|
||
public class BatchDatabaseExecutor
|
||
{
|
||
private List<string> _commands = new List<string>(); // 存储待执行的SQL命令列表
|
||
private Timer _timer; // 定时器,用于定期执行数据库操作
|
||
private string _connectionString; // 数据库连接字符串
|
||
|
||
public BatchDatabaseExecutor(string connectionString) // 构造函数,初始化连接字符串和定时器
|
||
{
|
||
_connectionString = connectionString; // 初始化数据库连接字符串
|
||
// 设置定时器,每1000毫秒(1秒)执行一次
|
||
_timer = new Timer(TimerCallback, null, 0, 1000);
|
||
}
|
||
|
||
public void AddCommand(string command) // 向命令列表添加SQL命令
|
||
{
|
||
lock (_commands) // 使用lock确保线程安全
|
||
{
|
||
_commands.Add(command); // 添加命令到列表
|
||
}
|
||
}
|
||
|
||
private void TimerCallback(object o) // 定时器回调方法,执行数据库操作
|
||
{
|
||
List<string> commandsToExecute;
|
||
lock (_commands) // 使用lock确保线程安全
|
||
{
|
||
if (_commands.Count == 0) // 如果没有命令需要执行,直接返回
|
||
return;
|
||
|
||
commandsToExecute = new List<string>(_commands); // 复制命令列表
|
||
_commands.Clear(); // 清空原命令列表,准备下一次收集
|
||
}
|
||
|
||
ExecuteBatch(commandsToExecute); // 执行批量命令
|
||
}
|
||
|
||
private void ExecuteBatch(List<string> commands) // 执行批量数据库命令
|
||
{
|
||
try
|
||
{
|
||
using (var connection = new MySqlConnection(_connectionString)) // 创建数据库连接
|
||
{
|
||
connection.Open(); // 打开数据库连接
|
||
|
||
using (var transaction = connection.BeginTransaction()) // 开始数据库事务
|
||
{
|
||
foreach (var commandText in commands) // 遍历命令列表
|
||
{
|
||
using (var command = new MySqlCommand(commandText, connection, transaction)) // 创建命令对象
|
||
{
|
||
command.ExecuteNonQuery(); // 执行命令
|
||
}
|
||
}
|
||
|
||
transaction.Commit(); // 提交事务
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex) // 捕获并处理异常
|
||
{
|
||
Console.WriteLine("An error occurred: " + ex.Message); // 打印异常信息
|
||
// 在这里可以添加错误处理逻辑,比如重试或记录日志
|
||
}
|
||
}
|
||
|
||
public void Dispose() // 释放资源
|
||
{
|
||
_timer?.Change(Timeout.Infinite, Timeout.Infinite); // 停止定时器
|
||
_timer?.Dispose(); // 释放定时器资源
|
||
}
|
||
}
|
||
|
||
// 使用实例
|
||
/*class Program
|
||
{
|
||
static void Main(string[] args)
|
||
{
|
||
var executor = new BatchDatabaseExecutor("your_connection_string_here"); // 实例化数据库执行器
|
||
|
||
// 不同方法调用
|
||
*//* executor.AddCommand("INSERT INTO table_name (column1) VALUES ('value1');");
|
||
executor.AddCommand("UPDATE table_name SET column1='value2' WHERE id=1;");
|
||
executor.AddCommand("DELETE FROM table_name WHERE id=2;");*//*
|
||
|
||
executor.Dispose(); // 调用Dispose方法释放资源
|
||
}
|
||
}
|
||
*/ |