繁体   English   中英

在 Java 中使用 PostgreSQL NOTIFY 时如何发送/接收参数

[英]How to send/receive parameters when using PostgreSQL NOTIFY with Java

我正在使用 J2EE,我的代码如下

public class Notifier {

    private Connection conn;

    public void notifyThread() throws SQLException {
      conn  =   ConnectionManager.getConnection();
      Statement stmt = conn.createStatement();
      stmt.execute("NOTIFY notificationRecived");
      stmt.close();
    }
}

在听众的最后我使用:

org.postgresql.PGNotification notifications[] = pgconn.getNotifications();

提取通知的详细信息。 在这里我注意到

notifications[i].getParameter();

是一种提取与NOTIFY语句一起发送的数据的方法。 我看到很少有线程表明我们可以将数据与NOTIFY语句一起传递,例如NOTIFY notificationRecived, "xyz"但这一个会在,xyz处引发错误。

是否还有其他语法可以与NOTIFY一起传递参数?

这是更新的代码

public void notifyThread() throws SQLException {
  conn    =   ConnectionManager.getConnection();
  Statement stmt = conn.createStatement();
  stmt.execute("SELECT pg_notify('notificationRecived', 'xyz');");
  stmt.close();    
}    

要发送通知,您还可以使用函数pg_notify(text, text) 该函数将通道名称作为第一个参数,将有效负载作为第二个参数。 如果您需要使用非常量的通道名称和有效负载,该函数比NOTIFY命令更易于使用。

public void notifyThread() throws SQLException {
  conn  =   ConnectionManager.getConnection();
  Statement stmt = conn.createStatement();

  stmt.execute("NOTIFY notificationRecived, 'xyz'");

  stmt.close();
}

根据文档: https : //www.postgresql.org/docs/current/sql-notify.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM