Live2D 看板娘 / Demo

C# 监听数据库表的变化(SqlDependency)

    SqlDependency提供了这样一种能力:当被监测的数据库中的数据发生变化时,SqlDependency会自动触发OnChange事件来通知应用程序,从而达到让系统自动更新数据(或缓存)的目的。

  场景:当数据库中的数据发生变化时,需要更新缓存,或者需要更新与之相关的业务数据,又或者是发送邮件或者短信什么的等等情况时(我项目中是发送数据到另一个系统接口),如果数据库是SQL Server,

  可以考虑使用SqlDependency监控数据库中的某个表的数据变化,并出发相应的事件。

1、使用下面语句启用数据库的 Service Broker

ALTER DATABASE testDemo SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE
testDemo SET ENABLE_BROKER;

2、具体代码

class Program
    {
        static string connectionString = "Server=.;Database=testDemo;User Id=sa;Password=123456";
        static void Main(string[] args)
        {
            SqlDependency.Start(connectionString);//传入连接字符串,启动基于数据库的监听
            UpdateGrid();
            Console.Read();
            SqlDependency.Stop(connectionString);//传入连接字符串,启动基于数据库的监听
        }
        private static void UpdateGrid()
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                //依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
                using (SqlCommand command = new SqlCommand("SELECT name,age FROM dbo.student", connection))
                {
                    command.CommandType = CommandType.Text;
                    //connection.Open();
                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                    using (SqlDataReader sdr = command.ExecuteReader())
                    {
                        Console.WriteLine();
                        while (sdr.Read())
                        {
                            Console.WriteLine("AssyAcc:{0}\tSnum:{1}\t", sdr["name"].ToString(), sdr["age"].ToString());
                        }
                        sdr.Close();
                    }
                }
            }
        }
        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据
            {
                UpdateGrid();
            }
        }
    }

 

posted @ 2020-06-05 09:49  KysonDu  阅读(5528)  评论(2编辑  收藏  举报