当表数据发生变化时,如何在前端触发NOTIFICATION事件

时间:2013-03-18 07:24:37

标签: postgresql triggers notify listen

我正在尝试使用vb.net中Notification给出的Npgsql事件。我部分了解了这个机制,我学到的是,当特定表的数据发生变化时,它的trigger将被触发,所以在trigger内我们可以notify到关于data change的前端。

我设法在前端运行以下代码

Public Sub test()

    Dim conn = New NpgsqlConnection("Server=servername;port=portNo; _
               User Id=UID;pwd=PWD;DataBase=DB;")
    conn.Open()

    Dim command = New NpgsqlCommand("listen notifytest;", conn)
    command.ExecuteNonQuery()


    AddHandler conn.Notification, AddressOf NotificationSupportHelper

    command = New NpgsqlCommand("notify notifytest;", conn)
    command.ExecuteNonQuery()



End Sub

Private Sub NotificationSupportHelper(ByVal sender As Object, _
                                      ByVal e As NpgsqlNotificationEventArgs)

'Notified here.

End Sub

以上代码正在处理任何问题。但我想知道的是如何创建一个trigger notifiesNotification event数据更改为前端,因此前端的listen会被触发?我应该在哪里拨打listen。我是否需要为每个查询的执行调用{{1}}。任何机构都可以用一些示例代码澄清我的怀疑。?

1 个答案:

答案 0 :(得分:0)

前端:

Public Sub test()

Dim conn = New NpgsqlConnection(" Server=server; port=portno;User Id=uid; pwd=pwd; DataBase=Db; ")
conn.Open()

Dim command = New NpgsqlCommand("listen notifytest;", conn)
command.ExecuteNonQuery()

AddHandler conn.Notification, AddressOf NotificationSupportHelper


command = New NpgsqlCommand("update testtable set field='test' where id=1", conn)
Dim x As NpgsqlDataReader = command.ExecuteReader
End Sub

Private Sub NotificationSupportHelper(ByVal sender As Object, ByVal e As NpgsqlNotificationEventArgs)
    MsgBox(e.Condition)
End Sub

<强> TRIGGER:

CREATE OR REPLACE FUNCTION testingNotify()
  RETURNS trigger AS
$BODY$ 
    begin
       notify notifytest;
       return null;
    end;     
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION testingNotify() OWNER TO testserver;

如果表trigger中出现Insertdeleteupdate,则上述testtable会被解雇。所以在上面的代码中,在名为test的过程中,我编写了updating the table tabletest的查询,因此在执行查询时,NotificationSupportHelper被调用。