4

我想利用 SQL Server 通知在 winforms 应用程序中的数据库中捕获插入事件。我正在尝试使用 SQLDependency 对象。MSDN 文章使这看起来非常简单。所以我创建了一个小示例应用程序来尝试一下。该事件似乎仅在我第一次进入我的应用程序时触发(出现消息框)。将数据插入表中不会引发看起来的 OnChange 事件。有人可以告诉我我错过了什么吗?谢谢!

 public Main()
    {
        InitializeComponent();
        var check = EnoughPermission();
        SqlDependency.Stop(constr);
        SqlDependency.Start(constr);
        if(connection == null)
        {
            connection = new SqlConnection(constr);
        }
        if(command == null)
        {
            command = new SqlCommand("Select ID, ChatMessage FROM dbo.Chat",connection);
        }
        connection.Open();
        command.Notification = null;
        SqlDependency dependency = new SqlDependency(command);
        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
        command.ExecuteReader();
    }





    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        MessageBox.Show("Change!");
    }
4

2 回答 2

11

While I was working in the implementation of query notification, I got the exact problem. I checked all configurations, code pieces, and even TCP settings, but nothing helped. Then, I figured out the following query to run on database and it solved my problem. Maybe you can try it.

ALTER AUTHORIZATION ON DATABASE::[Your DB] TO sa;
于 2011-10-13T15:51:18.880 回答
6

您的第一个通知是您将收到的唯一通知。查询通知不是对更改的订阅,一旦触发通知,它也是无效的。您应该重新提交新的通知订阅。

如果您的查询立即得到通知,则意味着您没有收到更改通知,而是收到无效查询的通知。检查您收到的 SqlNotificationEventArgs 参数的值。检查信息为插入/更新/删除,检查为数据,检查类型为更改。

查看Watcher Application示例,以更好地了解您在收到通知时应该如何重新订阅。要更好地了解查询通知的工作原理,请参阅神秘通知

于 2009-12-15T00:49:38.020 回答