C# sqlserver监听数据表变化

 


C# 监听数据库表的变化(SqlDependency)
1
class Program 2 { 3 static string connectionString = "Server=.;Database=testDemo;User Id=sa;Password=123456"; 4 static void Main(string[] args) 5 { 6 SqlDependency.Start(connectionString);//传入连接字符串,启动基于数据库的监听 7 UpdateGrid(); 8 Console.Read(); 9 SqlDependency.Stop(connectionString);//传入连接字符串,启动基于数据库的监听 10 } 11 private static void UpdateGrid() 12 { 13 using (SqlConnection connection = new SqlConnection(connectionString)) 14 { 15 connection.Open(); 16 //依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[] 17 using (SqlCommand command = new SqlCommand("SELECT name,age FROM dbo.student", connection)) 18 { 19 command.CommandType = CommandType.Text; 20 //connection.Open(); 21 SqlDependency dependency = new SqlDependency(command); 22 dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); 23 using (SqlDataReader sdr = command.ExecuteReader()) 24 { 25 Console.WriteLine(); 26 while (sdr.Read()) 27 { 28 Console.WriteLine("AssyAcc:{0} Snum:{1} ", sdr["name"].ToString(), sdr["age"].ToString()); 29 } 30 sdr.Close(); 31 } 32 } 33 } 34 } 35 private static void dependency_OnChange(object sender, SqlNotificationEventArgs e) 36 { 37 if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据 38 { 39 UpdateGrid(); 40 } 41 } 42 }

 开启数据库Service Broker

ALTER DATABASE testDemo SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE testDemo SET ENABLE_BROKER;

转自:https://www.cnblogs.com/duhaoran/p/13047959.html
原文地址:https://www.cnblogs.com/yeyuqian/p/13490674.html