zoukankan      html  css  js  c++  java
  • 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}	Snum:{1}	", sdr["name"].ToString(), sdr["age"].ToString());
                            }
                            sdr.Close();
                        }
                    }
                }
            }
            private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
            {
                if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据
                {
                    UpdateGrid();
                }
            }
        }
  • 相关阅读:
    Educational Codeforces Round 30 B【前缀和+思维/经典原题】
    Educational Codeforces Round 30 A[水题/数组排序]
    洛谷 P2415 集合求和【数学公式/模拟】
    洛谷 P2689 东南西北【模拟/搜索】
    洛谷 P1012 拼数 [字符串]
    codeforces 869C The Intriguing Obsession【组合数学+dp+第二类斯特林公式】
    洛谷 P3927 SAC E#1
    洛谷P3929 SAC E#1
    洛谷P3926 SAC E#1
    codeforces 868B The Eternal Immortality【暴力+trick】
  • 原文地址:https://www.cnblogs.com/duhaoran/p/13047959.html
Copyright © 2011-2022 走看看