首页 > 数据库技术 > 详细

c#的SqlDependency监听器sql server

时间:2020-09-15 12:45:41      阅读:105      评论:0      收藏:0      [点我收藏+]

首先要启用Service Broker

ALTER DATABASE 数据库名称 SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE 数据库名称 SET ENABLE_BROKER;

然后sql语句必须是依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]

 static void Main(string[] args)
        {
            SqlDependency.Start(connectionString);//传入连接字符串,启动基于数据库的监听
            UpdateGrid();
            Console.Read();
            SqlDependency.Stop(connectionString);
        }

static string connectionString = "Server=ADMIN-PC;Database=newsData;User Id=sa;Password=123456";
        private static void UpdateGrid()
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("SELECT id,cemskind FROM [dbo].[op_weight_cemskind]", connection))
                {
                    command.CommandType = CommandType.Text;
                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                    using (SqlDataReader sdr = command.ExecuteReader())
                    {
                        Console.WriteLine();
                        while (sdr.Read())
                        {
                            Console.WriteLine("ID:{0}\t数据:{1}\t", sdr["id"].ToString(), sdr["cemskind"].ToString());
                        }
                        sdr.Close();
                    }
                }
            }
        }
        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据
            {
                UpdateGrid();
            }
        }

监听结果

技术分享图片

 

 

  

c#的SqlDependency监听器sql server

原文:https://www.cnblogs.com/shuaimeng/p/13672052.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!