我正在尝试打电话PL/SQL
为其某些参数定义了默认值的过程。我正在这样做使用CallableStatement
in JDBC
.
该过程有大量已定义默认值的参数。我不想在 Java 代码中显式设置默认值。这样做会使维护代码变得更加困难。如果 PL/SQL 代码发生更改,则也必须在 Java 代码中进行相同的更改。
是否有可能在 JDBC 中实现这一点?例如,只需将值绑定到您感兴趣的参数并忽略其余的。
我在以下示例程序中尝试了这一点:
-- PURPOSE: Takes a parameter which has defaults set. Returns the value of the same parameter
-- Example of: FUNCTION that takes a parameter with DEFAULT values
FUNCTION handle_defaults(empId IN NUMBER DEFAULT 20 , empCity IN VARCHAR2) RETURN NUMBER IS
BEGIN
RETURN empId;
EXCEPTION
WHEN others THEN
dbms_output.put_line('Error!');
END handle_defaults;
这是代码的相关部分(NOTE:为了可读性,已经剥离了 try catch 块、清理数据库资源等)
// Create a database connection
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PWD);
// Create a query string
String queryStr = "{ ? = call HR.EMP_PKG.handle_defaults( ? , ? ) }";
// Create a Callable Statements
callStmt = conn.prepareCall(queryStr);
// Bind values to the IN parameter
callStmt.setString(3, "Mumbai");
// Register OUT parameter
callStmt.registerOutParameter(1, java.sql.Types.NUMERIC);
// Execute the Callable Statement
callStmt.execute();
// Retrieve the value of the OUT parameter
parameterValue = callStmt.getInt(1);
System.out.println("Value returned : " + parameterValue);
我收到以下错误:
Exception occured in the database
java.sql.SQLException: Missing IN or OUT parameter at index:: 2
Database error code: 17041
作为绝望的尝试,我还尝试为这些参数传递空值。仅包含以下行:
callStmt.setNull(2, java.sql.Types.NUMERIC);
我得到以下结果:
Value returned : 0
这是有道理的,因为setNull
向参数提供 SQL Null。
我在用Oracle 11g
and Oracle 12c Jdbc Driver Version 12.1.0.2
.