数据库开启 Service broker

来源:互联网 发布:恒压供水plc编程 编辑:程序博客网 时间:2024/06/05 07:19


当我们需要 对数据库的连接更改通知应用程序的时候

我们就要开启数据库对我们的持续的服务 相当于socket

 那么我们先对程序进行编辑 

C# 建立控制台应用程序 

   private static string _connStr;
        static void Main(string[] args)
        {
            _connStr = "Data Source = .;Initial Catalog=HappyShop;Persist Security Info=True;User ID=sa;Password=sa";
            SqlDependency.Start(_connStr);//传入连接字符串,启动基于数据库的监听
            UpdateGrid();
            Console.Read();
        }


        private static void UpdateGrid()
        {
            
            using (SqlConnection connection = new SqlConnection(_connStr))
            {
                //依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
                using (SqlCommand command = new SqlCommand("select Name from [dbo].table1", connection))
                {
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange -= new OnChangeEventHandler(dependency_OnChange);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);


                    SqlDataReader sdr = command.ExecuteReader();
                    Console.WriteLine();
                    while (sdr.Read())
                    {
                        Console.WriteLine("Name:" + sdr["Name"].ToString());
                       // sdr["Message"].ToString();
                    }
                    sdr.Close();
                }
            }
        }
        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Info == SqlNotificationInfo.Insert ||
                   e.Info == SqlNotificationInfo.Update ||
                   e.Info == SqlNotificationInfo.Delete)
            {
                UpdateGrid();
            }
           
        }

开始之后 执行 会发现报错 发现数据库没开启服务  所以 我们打开数据库的查询分析器 为当前的数据库建立 

Service broker 


--is_broker_enabled为0未启用,为1启用

SELECT name,is_broker_enabled FROM sys.databases WHERE name = 'DBNAME'


ALTER DATABASE DbName SET NEW_BROKER WITH ROLLBACK IMMEDIATE;

ALTER DATABASE DbName SET ENABLE_BROKER;

在查询分析器里面执行这个 就可以开启数据库的自动触发反应了


这时候 你打开控制台 执行 查询到数据 当你数据库进行更改是 会发现 你的程序在变化 

原创粉丝点击