我怀疑这与您使用匿名块有关。使用 IN OUT 意味着某种过程,您实际上是在传递一个值 IN 或 OUT(或两者)。这是一个使用 PL/SQL 过程的测试。
CREATE OR REPLACE PROCEDURE add_one_if_odd(x IN OUT INTEGER) IS
BEGIN
IF MOD(x,
2) > 0 THEN
x := x + 1;
END IF;
END add_one_if_odd;
/
这是要演示的 Java 程序。
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
public class InOutTest {
public static void main(String[] args)
throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:@//your.db.string", "user", "password");
CallableStatement statement = connection
.prepareCall("BEGIN add_one_if_odd(?); END;");
for (int i = 0; i < 10; i++) {
statement.registerOutParameter(1, Types.INTEGER);
statement.setInt(1, i);
statement.execute();
System.out.println(i + " " + statement.getInt(1));
}
statement.close();
connection.close();
}
}
结果如下:
0 0
1 2
2 2
3 4
4 4
5 6
6 6
7 8
8 8
9 10
更新:正如你所说,你只允许匿名块。如果您知道 IN OUT 参数的 NULL 值表示它没有被设置(如您的示例中所示),您可以使用 wasNull() 来检测和处理这种情况。
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
public class InOutTest {
public static void main(String[] args)
throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:@//your.db.string", "user", "password");
CallableStatement statement = connection.prepareCall("BEGIN\n"
+ " IF UPPER(?) = UPPER(?) THEN\n"
+ " ? := 'Test';\n" + " END IF;\n" + "END;");
String inOut = "Name";
statement.setString(1, "Test1");
statement.setString(2, "Test1");
statement.setString(3, inOut);
statement.registerOutParameter(3, Types.VARCHAR);
statement.execute();
String out = statement.getString(3);
out = statement.wasNull() ? inOut : out;
System.out.println(out);
statement.close();
connection.close();
}
}
为不匹配生成“名称”,为匹配生成“测试”。