【Greenplum Tips】JDBC 如何获取存储过程 Raise Notice 信息

大家在平时使用 Greenplum 的过程中,肯定免不了存储过程的使用。今天来分享一个存储过程使用过程中的小Tips:

如何打印/获取 Raise Notice 信息。

存储过程 demo

因为主要展示如何获取调试信息,所以这里的存储过程 demo 比较简单,结构如下,执行过程中会返回几条调试信息和结果1。

<code>create or replace function test_proc()
returns text
as
$$

BEGIN

raise notice 'This is a JDBC raise notice test case!';
raise notice 'Raise notice 1';
raise notice 'Raise notice 2';
raise notice 'Raise notice 3';
raise notice 'Raise notice 4';

return '1';
END;

$$ language plpgsql;/<code>

psql 命令行获取 Raise Notice

一般情况下我们都是在终端中通过 psql 命令行进行调试,这样可以输出最全的信息,如下:

<code>postgres=# select test_proc();
NOTICE: This is a JDBC raise notice test case!
NOTICE: Raise notice 1
NOTICE: Raise notice 2
NOTICE: Raise notice 3
NOTICE: Raise notice 4
test_proc
-----------
1
(1 row)

postgres=#/<code>

JDBC 获取 Raise Notice

Java 开发过程中,可能需要获取上面这些 NOTICE 调试信息,方便对存储过程执行的过程进行判断控制。这个可以通过 statement 的 getWarnings() 方法获取,如果有多条调试信息,可以循环获取。下面直接展示代码:

<code>import java.sql.*;

public class PostgreSQLJDBC {
public static void main(String args[]) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("com.pivotal.jdbc.GreenplumDriver");
c = DriverManager.getConnection("jdbc:pivotal:greenplum://10.211.55.6:5432;;DatabaseName=postgres", "gpadmin1", "");
c.setAutoCommit(false);
System.out.println("Opened database successfully");

stmt = c.createStatement();

//打印结果及打印存储过程告警信息
ResultSet rs = stmt.executeQuery("select test_proc();");
while (rs.next()) {
System.out.println(rs.getString(1));
}
SQLWarning warn = stmt.getWarnings();
if(warn != null)
{
for (Throwable e : warn)
{
System.out.println(e.getMessage());
}
}

stmt.close();
c.commit();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
}/<code>


阿福:

社区活跃志愿者,山东辉鸿泛在电子科技技术总监。丰富的数据库开发运维经验。主导并完成了多个基于 Greenplum 数据平台的落地。