大家在平时使用Greenplum的过程中,肯定免不了存储过程的使用。今天来分享一个存储过程使用过程中的小Tips:如何打印/获取Raise Notice信息。
存储过程demo
因为主要展示如何获取调试信息,所以这里的存储过程demo比较简单,结构如下,执行过程中会返回几条调试信息和结果1。
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;
psql命令行获取Raise Notice
一般情况下我们都是在终端中通过psql命令行进行调试,这样可以输出最全的信息,如下:
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=#
JDBC获取Raise Notice
Java开发过程中,可能需要获取上面这些NOTICE调试信息,方便对存储过程执行的过程进行判断控制。这个可以通过statement的getWarnings()方法获取,如果有多条调试信息,可以循环获取。下面直接展示代码:
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);
}
}
}