如何在JAVA中处理来自Oracle PL/SQL函数的表格数据?

问题描述 投票:0回答:1

我习惯使用

ResultSet
中的
PreparedStatement
,例如

try (PreparedStatement ps = dbConnection.prepareStatement(sqlQueryString)) {
    try (ResultSet queryResult = ps.executeQuery()) {
        while (queryResult.next()) {
            // do something with queryResult
        }
    }
}

现在,我在 Oracle DB 中创建了一个返回数据表的 PL/SQL 函数:

create or replace FUNCTION MY_FUNCTION 
(
  IN_PARAMETERS...
)
RETURN OUT_TABLE_TYPE IS
    RESULT_ROWS OUT_TABLE_TYPE;
BEGIN
    SELECT <fields>
    BULK COLLECT INTO RESULT_ROWS
    FROM SOME_TABLE
    WHERE <some complicated filter>

    RETURN RESULT_ROWS;
END MY_FUNCTION;

我想在JAVA中调用这个函数并迭代从函数返回的数据行。这就是我的距离:

String dbCall = "{? = call MY_FUNCTION(?, ...)}

try (CallableStatement functionCall = dbConnection.prepareCall(dbCall)) {
            
    functionCall.registerOutParameter(1, Types.ARRAY, "SOME_TABLE");
    // register input parameter values:
    functionCall.setInt(2, value1);
    functionCall.set... // more input

    functionCall.executeUpdate();

    // now what??? I tried something like this:
    Array test = functionCall.getArray(1);
    while (test.getResultSet().next()) {
        // test contains data, but I don't know how to process it.
    }    
}

如何逐行迭代数据?

java oracle function plsql
1个回答
0
投票

将函数写为:

CREATE FUNCTION MY_FUNCTION 
(
  IN_PARAMETERS...
)
RETURN SYS_REFCURSOR
IS
  v_result SYS_REFCURSOR;
BEGIN
  OPEN v_result FOR
    SELECT <fields>
    FROM SOME_TABLE
    WHERE <some complicated filter>;

    RETURN v_result;
END MY_FUNCTION;

然后以与过程完全相同的方式循环遍历结果集。

© www.soinside.com 2019 - 2024. All rights reserved.