下面是从 ADF guide 中总结的一段调用 PLSQL 存储过程和函数的方法,仅供参考。
1 ,调用没有参数的存储过程
可以使用 executeCommand () 函数,在 AM 的实现类中可以这样来使用:
getDBTransaction().executeCommand("begin devguidepkg.proc_with_no_args; end;");
2 ,调用只有输入参数的存储过程
可以使用 getDBTransaction 提供的 createPreparedStatement 来创建 PreparedStatement 对象,使用示例:
getDBTransaction().createPreparedStatement("begin "+stmt+";end;",0);
3 ,调用只有输入参数的存储函数
可以使用 getDBTransaction 提供的 createCallableStatement 来创建 CallableStatement 对象,使用示例:
getDBTransaction().createCallableStatement("begin ? := "+stmt+";end;",0);
4 ,其他情况
调用既有输入参数又有输出参数的存储过程或函数可以使用 CallableStatement ,使用方法和 3 相同。
5 ,调用存储过程
操作流程:
1) 创建PreparedStatement
2) 设置输入输出参数
3) 执行查询
4) 关闭语句链接
- void callStoredProcedure(String stmt, Object[] bindVars) {
- PreparedStatement st = null;
- try {
- // 1. Create a JDBC PreparedStatement for
- st = getDBTransaction().createPreparedStatement("begin "+stmt+";end;",0);
- if (bindVars != null) {
- // 2. Loop over values for the bind variables passed in, if any
- for (int z = 0; z < bindVars.length; z++) {
- // 3. Set the value of each bind variable in the statement
- st.setObject(z + 1, bindVars[z]);
- }
- }
- // 4. Execute the statement
- st.executeUpdate();
- }
- catch (SQLException e) {
- throw new JboException(e);
- }
- finally {
- if (st != null) {
- try {
- // 5. Close the statement
- st.close();
- }
- catch (SQLException e) {}
- }
- }
- }
5 ,注意点:
1) 数据库连接占用数据库资源,务必在finally 语句中关闭数据库连接。
2) 对于在执行过程中发生的错误要throw 出来,否则会增加调试时寻找异常(错误)的难度。
3) 执行查询方法execute, executeQuery, executeUpdate 的区别:
executeUpdate 用于执行带有INSERT/UPDATE/DELETE 操作的语句
executeQuery 用于执行带有查询操作的语句
execute 用于执行任意类型的SQL 语句