SqlDependency提供了這樣一種能力:當被監測的數據庫中的數據發生變化時,SqlDependency會自動觸發OnChange事件來通知應用程序,從而達到讓系統自動更新數據(或緩存)的目的。
場景:當數據庫中的數據發生變化時,需要更新緩存,或者需要更新與之相關的業務數據,又或者是發送郵件或者短信什么的等等情況時(我項目中是發送數據到另一個系統接口),如果數據庫是SQL Server,
可以考慮使用SqlDependency監控數據庫中的某個表的數據變化,並出發相應的事件。
1、使用下面語句啟用數據庫的 Service Broker
ALTER DATABASE testDemo SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE testDemo SET ENABLE_BROKER;
2、具體代碼
class Program { static string connectionString = "Server=.;Database=testDemo;User Id=sa;Password=123456"; static void Main(string[] args) { SqlDependency.Start(connectionString);//傳入連接字符串,啟動基於數據庫的監聽 UpdateGrid(); Console.Read(); SqlDependency.Stop(connectionString);//傳入連接字符串,啟動基於數據庫的監聽 } private static void UpdateGrid() { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); //依賴是基於某一張表的,而且查詢語句只能是簡單查詢語句,不能帶top或*,同時必須指定所有者,即類似[dbo].[] using (SqlCommand command = new SqlCommand("SELECT name,age FROM dbo.student", 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["name"].ToString(), sdr["age"].ToString()); } sdr.Close(); } } } } private static void dependency_OnChange(object sender, SqlNotificationEventArgs e) { if (e.Type == SqlNotificationType.Change) //只有數據發生變化時,才重新獲取並數據 { UpdateGrid(); } } }
