0

我想利用 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);
}
4

1 回答 1

0

似乎您SqlDependency为每个操作都使用了一个新实例 - 从长远来看,这不会起作用;你应该有一个对需要它的代码部分可访问的单个实例的引用——这可能有助于解决你的问题。

此外,我实际上看不到您正在更改任何数据,您创建了连接和命令,但没有执行。

于 2011-09-06T12:21:56.220 回答