在Java中使用JDBC實現批處理的對象一般是使用PrepareStatement對象。
如何使用:
Class.forName("Oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:demo" , "scott" , "tiger");
PreparedStatement ps = conn.prepareStatement("insert into dept2 values(? , ? , ?)");
for(Dept dept-> depts){
ps.setInt(1, dept.Id);
ps.setString(2, dept.Name);
ps.setString(3, dept.Description);
ps.addBatch();
}
ps.executeBatch();
ps.close();
conn.close();
同樣在批量更新時,也是使用這個PrepareStatement對象來處理的。
Class.forName("Oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:demo" , "scott" , "tiger");
PreparedStatement ps = conn.prepareStatement("update dept2 set name=? , description=? where id=?)");
for(Dept dept-> depts){
ps.setString(1, dept.Name);
ps.setString(2, dept.Description);
ps.setInt(3, dept.Id);
ps.addBatch();
}
ps.executeBatch();
ps.close();
conn.close();