简体   繁体   中英

Is it possible to call pl/sql function from jdbc and register the return value by name?

I am able to call pl/sql functions, using call statements with the following syntax:

String call = "{ ? = call p_some_package.some_function( ?, ?, ?, ?, ?) }";
CallableStatement cs = connection.prepareCall(call);

But then I have to pass arguments using their indexes, because I have to register the return value, which doesn't have a name:

cs.registerOutParameter(1, OracleTypes.NUMBER);
cs.setInt(2, someInteger);
...

However when calling procedures, I can provide parameter names, because there's no "nameless" out parameter, as there is with a function:

cs.setInt("param_name", param_value);

Oracle pl/sql reference states that for functions Oracle creates one additional OUT parameter which it returns. So my questions is: Is it possible to pass the name of this parameter or somehow assign a name to this parameter and use it to pass arguments to pl/sql functions from JDBC as I do for procedures?

Similar question, no answer: Java named parameter's name (for Oracle JDBC function result)

You can use anonymous block instead of "call" syntax in order to use named binding

Before use this approach, take a look at this post and make sure you do not fall in trouble inverting order of setXXX variables http://info.michael-simons.eu/2012/07/23/oracle-jbdc-callablestatements-and-named-parameters/

@Test
public void testFunctionOrdered() throws SQLException {
    String sql = "begin :quotient := TEST_QUOTIENT(DIVIDEND => :numerator, DIVISOR => :denominator); end;";

    CallableStatement cs = conn.prepareCall(sql);

    cs.registerOutParameter("quotient", Types.INTEGER);
    cs.setInt("numerator", 6);
    cs.setInt("denominator", 2);

    cs.execute();

    assertEquals(3, cs.getInt("quotient"));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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