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

场景:当数据库中的数据发生变化时,需要更新缓存,或者需要更新与之相关的业务数据,又或者是发送邮件或者短信什么的等等情况时(我项目中是发送数据到另一个系统接口),如果数据库是SQL Server,可以考虑使用SqlDependency监控数据库中的某个表的数据变化,并出发相应的事件。

学习时建的控制台应用程序“SqlDependency_监听数据库”

函数入口Main函数中添加以下代码:


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


在Main函数的下面紧接着再写一下两个方法:


private static void UpdateGrid()
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
connection.Open();
//依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
using (SqlCommand command = new SqlCommand("SELECT [Process_Cmn_AssyAcc],[Process_Cmn_Snum] FROM [dbo].[T_DD_OP101_Final]", 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["Process_Cmn_AssyAcc"].ToString(), sdr["Process_Cmn_Snum"].ToString());
}
sdr.Close();
}
}
}
}

private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据
{
UpdateGrid();
}
}


不要忘记配置App.config连接字符串(需要添加引用System.Configuration;该程序集不是新建控制台程序时默认添加的)


<connectionStrings>
<add name="ConnectionStringMain" connectionString="Data Source=192.168.1.211;Initial Catalog=WLZhuJianMes;Persist Security Info=True;User ID=sa;Password=sa;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>


在添加完以上代码运行后会出现“未启用当前数据库的 SQL Server Service Broker,因此查询通知不受支持。如果希望使用通知,请为此数据库启用 Service Broker”:

在数据中执行以下查询:


SELECT is_broker_enabled FROM sys.databases WHERE name = 'WLZhuJianMes'


查询结果:is_broker_enabled de 结果是  0,代表数据库没有启动 Service Broker

解决办法:注:两句同时执行,单独执行显示:正在回滚不合法事务。估计回滚已完成: 100%。


use WLZhuJianMes  
go
ALTER DATABASE WLZhuJianMes SET NEW_BROKER WITH ROLLBACK IMMEDIATE;

ALTER DATABASE WLZhuJianMes SET ENABLE_BROKER;


再次查询is_broker_enabled状态,状态为1,数据库没有启动 Service Broker成功。

启动项目后的显示页面:

SqlDependency C#代码监听数据库表的变化_数据

向数据库的表中添加一条数据:insert into [WLZhuJianMes].[dbo].​T_DD_OP101​​ values(1,'342536465456');窗口就立马监测到了数据库表的变化了。

 

SqlDependency C#代码监听数据库表的变化_数据库_02