VastbaseG100

基于openGauss内核开发的企业级关系型数据库。

Menu

调用存储过程

调用存储过程,可以使用 prepareCall 方法,问号 (?) 是prepareCall的占位符,对于存储过程的输出,需要使用 CallableStatementregisterOutparameter 方法注册,执行存储过程使用 execute() 方法。

调用存储过程

1、调用Connection的prepareCall方法创建调用语句对象。

Connection conn = DriverManager.getConnection("url","user","password");
CallableStatement cstmt = conn.prepareCall("{? = CALL TESTPROC(?,?,?)}");

2、调用CallableStatement的setInt方法设置参数。

cstmt.setInt(2, 50); 
cstmt.setInt(1, 20);
cstmt.setInt(3, 90);

3、调用CallableStatement的registerOutParameter方法注册输出参数。

cstmt.registerOutParameter(4, Types.INTEGER);  //注册out类型的参数,类型为整型。

4、调用CallableStatement的execute执行方法调用。

cstmt.execute();

5、调用CallableStatement的getInt方法获取输出参数。

int out = cstmt.getInt(4);  //获取out参数

6、调用CallableStatement的close方法关闭调用语句。

cstmt.close();

下面的例子展示了如何调用存储过程:

java CallableStatement upperProc = conn.prepareCall(“{? = call upper( ? )}”); upperProc.registerOutParameter(1, Types.VARCHAR); upperProc.setString(2, “lowercase to uppercase”); upperProc.execute(); String upperCased = upperProc.getString(1); upperProc.close(); ```

获取结果集

函数可以通过两种方式返回结果集,根据函数被调用的方式决定结果集的返回方式。

  • 方式一:返回 SETOF 类型结果集

    Statement stmt = conn.createStatement();
    stmt.execute("CREATE OR REPLACE FUNCTION setoffunc(i int, out result_1 bigint, out result_2 bigint)\n" +
                    "returns SETOF RECORD\n" +
                    "as $$\n" +
                    "begin\n" +
                    "    result_1 = i + 1;\n" +
                    "    result_2 = i * 10;\n" +
                    "return next;\n" +
                    "end;\n" +
                    "$$language plpgsql;\n");
    ResultSet rs = stmt.executeQuery("SELECT * FROM setoffunc(1)");
    while (rs.next())
    {
        int i=1;
        Object result1 = rs.getInt(i++);
         Object result2 = rs.getInt(i);
         System.out.println("| " + result1 + " | " + result2 + " |");
    }
    rs.close();
    stmt.close();
    
  • 方式二:返回游标

    // Setup function to call.
    Statement stmt = conn.createStatement();
    stmt.execute("CREATE OR REPLACE FUNCTION refcursorfunc() RETURNS refcursor AS $$" + " DECLARE "+ " mycurs refcursor; "
                    + " BEGIN "
                    + " OPEN mycurs FOR SELECT 1 UNION SELECT 2; "
                    + " RETURN mycurs; "
                    + " END;$$ ");
    stmt.close();
    // We must be inside a transaction for cursors to work.
    conn.setAutoCommit(false);
    // Procedure call.
    CallableStatement proc = conn.prepareCall("{? = call refcursorfunc()}");
    proc.registerOutParameter(1, Types.OTHER);
    proc.execute();
    ResultSet results = (ResultSet) proc.getObject(1);
    while (results.next())
    {
        System.out.println(results);// do something with the results.
    }
    results.close();
    proc.close();