我想利用 SQL Server 通知在 Windows 服务中的数据库中捕获插入/更新事件。我正在尝试使用 SQLDependency 对象。MSDN 文章使这看起来非常简单。所以我创建了一个小示例应用程序来尝试一下。当对表中的数据进行更改时,它不会引发看起来的 OnChange 事件。有人可以告诉我我错过了什么吗?谢谢!我的代码示例如下。
private bool CanRequestNotifications()
{
SqlClientPermission permit = new
SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
try
{
permit.Demand();
return true;
}
catch (System.Exception exc)
{
return false;
}
}
private void NotificationListener()
{
string mailSQL;
SqlConnection sqlConn;
try
{
string connString = "Data Source=xyz;Initial Catalog=abc;User ID=sa;Password=******";
mailSQL = "SELECT * FROM [tbl_test]";
SqlDependency.Stop(connString);
SqlDependency.Start(connString);
sqlConn = new SqlConnection(connString);
SqlCommand sqlCmd = new SqlCommand(mailSQL, sqlConn);
this.GetNotificationData();
evtLog.WriteEntry("Error Stage: NotificationListener" + "Error desc:" + "Message", EventLogEntryType.Error);
}
catch (Exception e)
{
// handle exception
}
}
private void GetNotificationData()
{
DataSet myDataSet = new DataSet();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Notification = null;
SqlDependency dependency = new SqlDependency(sqlCmd);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
evtLog.WriteEntry("Error Stage: GetNotificationData" + "Error desc:" + "Message", EventLogEntryType.Error);
}
private void dependency_OnChange(object sender,SqlNotificationEventArgs e)
{
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= dependency_OnChange;
this.GetNotificationData();
evtLog.WriteEntry("Error Stage: dependency_OnChange" + "Error desc:" + "Message", EventLogEntryType.Error);
}
protected override void OnStart(string[] args)
{
CanRequestNotifications();
NotificationListener();
}
protected override void OnStop()
{
SqlDependency dependency = new SqlDependency();
dependency.OnChange -= dependency_OnChange;
SqlDependency.Stop(connString);
}