Java实现批量插入、修改数据到数据库中
在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();