首页 > 代码库 > c# 实时监控数据库 SqlDependency

c# 实时监控数据库 SqlDependency

http://blog.csdn.net/idays021/article/details/49661855

class Program
{
private static string _connStr;

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

Console.Read();
}

private static void UpdateGrid()
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
//依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[],如果where条件存在datetime类型,就会导致一直触发onChange事件
using (SqlCommand command = new SqlCommand("select id,machine,jobNo From [dbo].[plm_Issue]", connection))
{
command.CommandType = CommandType.Text;
connection.Open();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

SqlDataReader sdr = command.ExecuteReader();
Console.WriteLine();
while (sdr.Read())
{
Console.WriteLine("id:{0}\t machine:{1}\t jobNo:{2}", sdr["id"].ToString(), sdr["machine"].ToString(),

sdr["jobNo"].ToString());
}
sdr.Close();
}
}
}


private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= dependency_OnChange;
if (e.Info != SqlNotificationInfo.Invalid)
{
UpdateGrid();//此处需重复注册<span style="font-family: Arial, Helvetica, sans-serif;">SqlDependency,每次注册只执行一次,SqlDependency.id可用用于验证注册唯一 编号
}
}
}

 

在数据库执行如下sql 语句

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

 

c# 实时监控数据库 SqlDependency