You need to enable JavaScript to run this app. 如何让C#程序监测alerts表新增行并弹出Alert提示消息框
优惠活动
大模型
产品
解决方案
定价
更多

如何让C#程序监测alerts表新增行并弹出Alert提示消息框

实现C#监听alerts表新增行并弹出提醒的方案

以下适配最常用的SQL Server场景,如果使用其他数据库可直接看末尾的通用轮询方案:

前置数据库配置

SqlDependency依赖SQL Server的Service Broker组件实现主动通知,需要先在数据库执行以下SQL开启配置:

-- 开启Service Broker,替换为实际数据库名
ALTER DATABASE [你的数据库名] SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
-- 给数据库登录账号赋通知权限,替换为实际登录名
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO [你的登录用户名];
GRANT RECEIVE ON QueryNotificationErrorsQueue TO [你的登录用户名];

C#核心代码实现(WinForm示例)

WPF场景只需替换弹窗逻辑为对应实现即可:

using System.Data.SqlClient;
using System.Windows.Forms;

public partial class MainForm : Form
{
    // 替换为实际数据库连接字符串
    private const string ConnectionString = "Server=你的服务器地址;Database=你的数据库名;Uid=账号;Pwd=密码;";
    private SqlConnection _connection;
    private SqlCommand _command;
    private SqlDependency _dependency;

    private void MainForm_Load(object sender, EventArgs e)
    {
        // 窗体加载时启动监听
        StartAlertMonitor();
    }

    private void StartAlertMonitor()
    {
        SqlDependency.Start(ConnectionString);
        _connection = new SqlConnection(ConnectionString);
        // 注意:查询语句必须明确列名、携带schema前缀,不能用*,否则SqlDependency无法生效
        _command = new SqlCommand("SELECT id, alert_content, create_time FROM dbo.alerts ORDER BY create_time DESC", _connection);
        _dependency = new SqlDependency(_command);
        _dependency.OnChange += OnAlertTableChanged;

        _connection.Open();
        // 执行一次查询完成监听注册
        _command.ExecuteReader();
        _connection.Close();
    }

    private void OnAlertTableChanged(object sender, SqlNotificationEventArgs e)
    {
        // 仅新增行事件触发弹窗
        if (e.Type == SqlNotificationType.Change && e.Info == SqlNotificationInfo.Insert)
        {
            // 跨线程访问UI控件需要封送到UI线程
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => MessageBox.Show("Alert")));
            }
            else
            {
                MessageBox.Show("Alert");
            }
        }
        // SqlDependency单次触发后会失效,需要重新注册监听
        StartAlertMonitor();
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        // 程序退出时释放资源
        SqlDependency.Stop(ConnectionString);
        _connection?.Dispose();
        _command?.Dispose();
    }
}

其他数据库通用方案

如果使用MySQL、PostgreSQL等不支持SqlDependency的数据库,可以用轻量轮询方案实现:

  • 开一个后台定时任务,每隔1~3秒查询alerts表的最大ID/最新创建时间
  • 每次查询结果和上一次存储的最大值做对比,如果数值变大说明有新增行,直接触发弹窗
  • 该方案无需数据库特殊配置,适合数据量不大的业务场景

内容的提问来源于stack exchange,提问作者user15960482

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 06:27:00