儲存過程呼叫 遍歷返回結果集
阿新 • • 發佈:2019-02-18
//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()); } }