//java调用存储过程 使用游标遍历结果集
public void getCallableStatement(){
CallableStatement cs=null;
Connection conn=this.getConnection();
//存储过程 用户名.procedure
String procedure="{call emp_pkg.pro_read(?,?)}";
try {
cs=conn.prepareCall(procedure);
cs.setInt(1, 7788);
cs.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
cs.executeUpdate();
ResultSet res=(ResultSet) cs.getObject(2);
while(res.next()){
//res.getString("name");类似jdbc
//也可以根据位置获取value res.getString(1);
System.out.println("编号:"+res.getInt(1)+" 姓名:"+res.getString(2));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
测试数据库连接
public static void main(String[] args) {
String URL = "jdbc:oracle:thin:@127.0.0.1:1521:test";
String USERNAME = "quartz16";
String PASSWORD = "quartz16";
try {
// 初始化驱动包
Class.forName("oracle.jdbc.driver.OracleDriver");
// 根据数据库连接字符,名称,密码给conn赋值
Connection connection = DriverManager.getConnection(URL, USERNAME,PASSWORD);
System.out.println("数据库连接成功" + connection);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
释放数据库资源
public static void closeCon(ResultSet rs, PreparedStatement pstmt,Connection conn) {
try {
if (rs != null) {// 如果返回的结果集对象不能为空,就关闭连接
rs.close();
}
} catch (Exception e) {
LOGGER.info(e.getMessage());
}
try {
if (pstmt != null) {
pstmt.close();// 关闭预编译对象
}
} catch (Exception e) {
LOGGER.info(e.getMessage());
}
try {
if (conn != null) {
conn.close();// 关闭结果集对象
}
} catch (Exception e) {
LOGGER.info(e.getMessage());
}
}