很多人表示,自己对于java代码的调用存储过程不是很了解,那么下面就一起通过下面的文章实例来进行一下了解吧!
首先的话,我们要准备好一个oracle的JDBC jar包;
ojdbc14_11g.jar
之后找到oracle安装位置。
接着创建一个jdbc数据库连接工具类:
package com.test.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCUtils { private static String driver = "oracle.jdbc.OracleDriver"; private static String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; private static String user = "数据库连接名"; private static String password = "数据库连接密码"; //注册数据库驱动 static { try { Class.forName(driver); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } /** * 获取数据库连接 * @return */ public static Connection getConnection() { try { return DriverManager.getConnection(url, user, password); } catch (SQLException e) { e.printStackTrace(); } return null; } /** * 释放数据库连接资源 * @param conn * @param st * @param rs */ public static void release(Connection conn, Statement st, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { rs = null; } } if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } finally { st = null; } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } finally { conn = null; } } } }
调用存储过程:
package com.test.demo; import java.sql.CallableStatement; import java.sql.Connection; import org.junit.Test; import oracle.jdbc.internal.OracleTypes; import oracle.jdbc.oracore.OracleType; import com.hwb.db.JDBCUtils; /** * 调用存储过程 一个输入参数,多个 输出参数 * @author Administrator * */ public class ProcedureTest { /** * create or replace procedure selectUserById(uid in number, uName out VARCHAR2, uAge out number, uSex out char) */ @Test public void testProcedure() { String sql = "{call selectUserById(?,?,?,?)}"; Connection conn = null; CallableStatement call = null; try { //得到一个数据库连接 conn = JDBCUtils.getConnection(); //通过连接创建出statement call = conn.prepareCall(sql); //对于in参数,赋值 call.setInt(1, 2); // (第几个问号,要赋的值) //对out参数,声明 call.registerOutParameter(2, OracleTypes.VARCHAR); //(第几个问号,声明的类型) call.registerOutParameter(3, OracleTypes.NUMBER); call.registerOutParameter(4, OracleTypes.CHAR); //执行调用 call.execute(); //取出结果 String userName = call.getString(2); int userAge = call.getInt(3); String userSex = call.getString(4); System.out.println("用户姓名:" + userName + "\n\t年龄:" + userAge + "\n\t性别:" + userSex); } catch (Exception e) { e.printStackTrace(); } finally { //关闭连接,释放资源 JDBCUtils.release(conn, call, null); } } }
java代码调用存储过程就给你进行了简单的介绍了,想了解更多的java程序代码例子,可以继续通过奇Q工具网来进行了解呢。
推荐阅读: