简体   繁体   English

从Java JDBC调用oracle函数

[英]Calling oracle function from Java JDBC

We have a Oracle function we are trying to call from JDBC. 我们有一个我们试图从JDBC调用的Oracle函数。 It takes 3 inputs (String, Number and Date) and returns 1 Number: 它需要3个输入(字符串,数字和日期)并返回1个数字:

create or replace function     mww_avgcost
(in_prd_lvl_number prdmstee.prd_lvl_number%type,
in_org_lvl_number orgmstee.org_lvl_number%type,
in_sales_date     prcmstee.prc_from_date%type)
RETURN NUMBER
AS
begin   

Using Java JDBC code as follows: 使用Java JDBC代码如下:

        String call = "{ ? = call PMM.MWW_AVGCOST(?, ?, ?) }";
        CallableStatement cstmt = conn.prepareCall(call);
        cstmt.registerOutParameter(1, java.sql.Types.INTEGER);
        cstmt.setString(2, productNumber);
        cstmt.setInt(3, storeNumber);

        // convert XML input to SQL date
        java.sql.Date sqlDate = new java.sql.Date(saleDate.toGregorianCalendar().getTimeInMillis());

        cstmt.setDate(4, sqlDate);
        cstmt.execute();
        BigDecimal resultFromFunction = cstmt.getBigDecimal(1);
        log.info("resultFromFunction:" + resultFromFunction);

The result always returns 1 though and not the proper number. 结果总是返回1而不是正确的数字。 We have run it fine from SQL Developer with the same parameters and it looks fine. 我们已经从SQL Developer运行它与相同的参数,它看起来很好。 Is this is proper way to call a SQL function from JDBC? 这是从JDBC调用SQL函数的正确方法吗?

Looks like your have a type mismatch. 看起来你的类型不匹配。 You're setting the out parameter to an sql integer but then getting it as a BigDecimal. 您将out参数设置为sql整数,然后将其设置为BigDecimal。
If the sql function returns an integer then use: callableStatement.getInt(1) 如果sql函数返回一个整数,那么使用: callableStatement.getInt(1)

If the sql function returns a floating point number, then use callableStatement.registerOutParameter(1, java.sql.Types.DOUBLE) and callableStatement.getDouble(1) 如果sql函数返回浮点数,则使用callableStatement.registerOutParameter(1, java.sql.Types.DOUBLE)callableStatement.getDouble(1)

The mapping for java and oracle types can be found here: https://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html 可以在此处找到java和oracle类型的映射: https//docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html

If you really do need BigDecimal because of rounding problems or something, then your sql function should return DECIMAL or NUMERIC. 如果由于舍入问题或其他问题确实需要BigDecimal,那么你的sql函数应该返回DECIMAL或NUMERIC。 And you should set your out parameter and getBigDecimal() as you're doing now. 你应该像现在一样设置你的out参数和getBigDecimal()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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