0

我的 Oracle 数据库中有一个函数(不是过程)。这个函数看起来像:

CREATE OR REPLACE FUNCTION GETTOTAL(v_user_id IN NUMBER)
RETURN NUMBER
AS
    v_result number := 0;
BEGIN
    SELECT SUM(DAY1+DAY2) INTO v_result FROM TABLE WHERE USER_ID = v_user_id;
RETURN v_result;
END;

现在在我的 java Netbeans 程序中,我需要该结果才能在我的程序中使用它。

我尝试了以下方法:

callStatement = con.prepareCall("SELECT GETTOTAL(1) FROM DUAL;");
callStatement.execute();
resultaat = callStatement.getDouble(1);
callStatement.close();

我也尝试过使用 CALL。但似乎没有任何效果。我也试过在网上寻找问题,但似乎只解释了程序而不是功能......所以我希望我能在这里找到一个遮阳篷。

4

3 回答 3

1

检查我的例子:

CREATE TABLE my_test_tab (
  user_id NUMBER,
  day1 NUMBER,
  day2 NUMBER
);

INSERT INTO my_test_tab VALUES (1, 5, 10);
INSERT INTO my_test_tab VALUES (1, 1, 2);

COMMIT;

CREATE OR REPLACE FUNCTION GETTOTAL(v_user_id IN NUMBER)
RETURN NUMBER
AS
    v_result number := 0;
BEGIN
    SELECT SUM(DAY1+DAY2) INTO v_result FROM my_test_tab WHERE USER_ID = v_user_id;
RETURN v_result;
END;
/

在 Java 中,您创建一个CallableStatement并且您必须registerOutParameter为函数的返回值检查代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.CallableStatement;

public class Main2 {
  public static void main(String[] args) throws Exception {
    Connection conn = getOracleConnection();
    System.out.println("Got Connection.");

    CallableStatement callStmt = null;

    try {
      callStmt = conn.prepareCall("{? = call gettotal(?)}");
      callStmt.setInt(2, 1);
      callStmt.registerOutParameter(1, java.sql.Types.NUMERIC);
      callStmt.execute();

      System.out.println(callStmt.getInt(1));
    } finally {
      callStmt.close();
      conn.close();
     }
  }

  public static Connection getOracleConnection() throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@HOST_ADDRESS:1521:orcl";
    String username = "USERNAME";
    String password = "PASSWORD";

    Class.forName(driver); // load Oracle driver

    java.util.Properties info = new java.util.Properties();  
    info.put ("user", "hr");  
    info.put ("password", "oracle");  
    Connection conn = DriverManager.getConnection(url, info);

    return conn;
  }
}
于 2013-10-28T11:04:03.643 回答
0

尝试这个:

String getDBUSERByUserIdSql = "{call GETTOTAL(?, ?)}";
callableStatement = dbConnection.prepareCall(getDBUSERByUserIdSql);
callableStatement.setInt(1, 10);
callableStatement.registerOutParameter(2, Types.INTEGER);
callableStatement.execute();

int retVal = callableStatement.getInt(2);
于 2013-10-28T11:04:02.873 回答
0

您需要使用

String getDBUSERByUserIdSql = "{call GETTOTAL(?)}";
callableStatement = dbConnection.prepareCall(getDBUSERByUserIdSql);
callableStatement.setInt(1, 10);
于 2013-10-28T10:53:44.010 回答