2015-02-11 69 views
0

我有一個SQL Server 2005數據庫,它將來自某個設備的事件註冊到一個表中。我需要在C#應用程序中捕獲這些事件。在應用程序中監聽插入數據庫表

事件可能隨時發生。我正在尋找關於如何管理數據庫偵聽/捕獲數據庫發送的數據的良好實踐。關於這些問題,有一些關於stackoverflow的話題,但是在這些情況下沒有推薦的一種方法,但只有一些方法沒有系統的建議。

所以我問一下好的做法。這些工作應該如何完成?請幫忙。

在我看來,觸發器可以將一些信息從表格發送到c#應用程序似乎是最好的解決方案,但我不知道是否可以安排觸發器來完成這些工作。

我將是任何sugestion感激)

+0

什麼樣的c#應用程序? web wpf winforms? – 2015-02-11 08:55:15

+0

桌面應用。 C#+ WPF – 2015-02-11 09:04:01

回答

0

我知道通過在SQL表的更改在C#被通知的唯一方法是通過使用SqlDependencies

實施例:

private async Task RegisterSqlDependency() 
    { 
     if (_dependency != null) 
      _dependency.OnChange -= this.OnChange; 
     String query = "select MyCol from dbo.MyTable WHERE myKey = '" + _dependecyKey + "'"; 

     using (SqlConnection connexion = new SqlConnection("ConnexionString")) 
     { 
      using (SqlCommand command = new SqlCommand(query, connexion)) 
      { 
       _dependency = new SqlDependency(command, null, 0); 
       _dependency.OnChange += this.OnChange; 
       await connexion.OpenAsync(); 
       using (SqlDataReader reader = await command.ExecuteReaderAsync()) 
       { 
        while (reader.Read()) 
        { 
         .... GetData .... 
        } 
       } 
      } 
     } 
    } 

private void OnChange(object sender, SqlNotificationEventArgs e) 
    { 
     .... Data has changed on table .... 
     call RegisterSqlDependency() again 
    } 

您必須在您的數據庫上啓用SERVICE BROKER以啓用SqlDepedency:

ALTER DATABASE MyDatabase SET ENABLE_BROKER with rollback immediate; 
+0

嗯,這不是*唯一*的方式..... – sloth 2015-02-11 08:59:51

+0

@sloth,你知道更好的方法嗎? – 2015-02-11 09:08:13

+0

@DawidJablonski另一種方式?是。更好的方法?沒有。 – sloth 2015-02-11 09:35:44

相關問題