SqlDependency用法

步骤一:

sql数据库必须开启ServiceBroker服务,首先检测是否已经启用ServiceBroker,检测方法:

 Select  DATABASEpRoPERTYEX('数据库名称','IsBrokerEnabled')
--1表示已经启用0表示没有启用
 

步骤二:

如果ServiceBroker没有启用,使用下面语句启用:

 ALTER  DATABASE  <数据库名称>  SET  ENABLE_BROKER;
 

步骤三:

在实现基于服务的SQL数据缓存依赖程序中,需要显式调用SqlDependency.Start来启动接受依赖项更改通知的侦听器。

SqlDependency.Start(connectionString);//程序开始时调用一次

SqlDependency.Stop(connectionString);//程序退出是调用一次

 

步骤四:
private void buttonCache_Click(object sender, EventArgs e)
{
            ObjectCache cache = MemoryCache.Default;
            Server s = (Server)cache["OneServer"];
            if (s == null)
            {
                string sql = string.Format("select [ID],[IP],[Port],[Name] from [dbo].[Server] where [ID]={0}", int.Parse(textBoxID.Text));
                CacheItemPolicy policy = new CacheItemPolicy();
                SqlDependency.Start(conStr);
                using (SqlConnection dbc = new SqlConnection(conStr))
                {
                    using (SqlCommand cmd = new SqlCommand(sql, dbc))
                    {
                        cmd.Notification = null;
                        SqlDependency dep = new SqlDependency();
                        dep.AddCommandDependency(cmd);
                        dbc.Open();
                        SqlDataReader reader = cmd.ExecuteReader();
                        if (reader.Read())
                        {
                            s = new Server()
                            {
                                ID = Convert.ToInt32(reader["ID"]),
                                IP = (string)reader["IP"],
                                Port = Convert.ToInt32(reader["Port"]),
                                Name = (string)reader["Name"]
                            };
                            reader.Close();
                        }
                        SqlChangeMonitor monitor = new SqlChangeMonitor(dep);
                        policy.ChangeMonitors.Add(monitor);
                    }
                }
                cache.Add("OneServer", s, policy);
                s = (Server)cache["OneServer"];
            }
            s = (Server)cache["OneServer"];
        }
 

注意:

使用 SqlDependency 订阅查询通知必须向SQL Server Service Broker提供制定规则的查询语句,一般来讲,必须是简单的sql查询语句(不能用*,不能用top,不能用函数,包括聚合函数,不能用子查询,包括where后的子查询,不能用外连接,自连接,不能用临时表,不能用变量,不能用视图,不能垮库,表名之前必须加类似dbo数据库所有者这样的前缀)例如:select * from table1,select column1 from table1,select count(*) from table1 都是错误的sql查询语句,select column1 from dbo.table1 则是正确的语句。

posted @ 2017-04-25 17:11  邵学军  阅读(3754)  评论(0编辑  收藏  举报