//存儲過程爲sum_sal(deptno department.deptno%type,sum in out number) CallableStatement cs =conn.prepareCall("{call sum_sal(?,?)}"); cs.setInteger(1,7879); cs.setDouble(2,0.0);//第二個傳什麼都無所謂,由於第二個參數是in out模式,是做爲輸出的 cs.registerOutParameter(2,java.sql.Types.Double,2);//最後那個參數是保留小數點2位 cs.excute();//執行會返回一個boolean結果 //得到結果,獲取第二個參數 double result = cs.getDouble(2);
//存儲過程爲list(result_set out sys_refcursor, which in number) CallableStatement cs =conn.prepareCall("{call list(?,?)}"); cs.setInteger(2,1); cs.registerOutParameter(1,racleTypes.CURSOR); cs.execute(); //得到結果集 ResultSet rs = (ResultSet)cs.getObject(1);
People表中只有兩列,id和name ,還有對應的一個實體類People
批量操做應該放到事務裏進行,由於它會存在某條語句執行失敗的狀況。java
public int[] insetBatch(List<People> list) { try (Connection connection = JdbcUtil.getConnection(); PreparedStatement ps = connection.prepareStatement("insert into PEOPLE values (?,?)"); ) { // 關閉事務自動提交,手動提交 connection.setAutoCommit(false); //從list中取出數據 for (People people : list) { ps.setInt(1, people.getId()); ps.setString(2, people.getName()); //加入到指語句組中 ps.addBatch(); } int[] recordsEffect = ps.executeBatch(); // 提交事務 connection.commit(); return recordsEffect; } catch (SQLException e) { e.printStackTrace(); } return null; }
public static void main(String[] args) { List<People> list = new ArrayList<>(); int id = 1; list.add(new People(id++, "james")); list.add(new People(id++, "andy")); list.add(new People(id++, "jack")); list.add(new People(id++, "john")); list.add(new People(id++, "scott")); list.add(new People(id++, "jassica")); list.add(new People(id++, "jerry")); list.add(new People(id++, "marry")); list.add(new People(id++, "alex")); int[] ints = new BatchTest().insetBatch(list); System.out.println(Arrays.toString(ints)); }
public int[] updateBatch(List<People> list) { try (Connection connection = JdbcUtil.getConnection(); PreparedStatement ps = connection.prepareStatement("undate people set name=? where id=?"); ) { // 關閉事務自動提交,手動提交 connection.setAutoCommit(false); //從list中取出數據 for (People people : list) { ps.setInt(1, people.getId()); ps.setString(2, people.getName()); //加入到指語句組中 ps.addBatch(); } int[] recordsEffect = ps.executeBatch(); // 提交事務 connection.commit(); return recordsEffect; } catch (SQLException e) { e.printStackTrace(); } return null; }
public int[] updateBatch(List<People> list) { try (Connection connection = JdbcUtil.getConnection(); PreparedStatement ps = connection.prepareStatement("delete people where id=?"); ) { // 關閉事務自動提交,手動提交 connection.setAutoCommit(false); //從list中取出數據 for (People people : list) { ps.setInt(1, people.getId()); //加入到指語句組中 ps.addBatch(); } int[] recordsEffect = ps.executeBatch(); // 提交事務 connection.commit(); return recordsEffect; } catch (SQLException e) { e.printStackTrace(); } return null; }