`

数据库的批处理

 
阅读更多
 
对数据库进行操作时,要操作多条时,用批处理效率更高。
基本实现语句:pstm.addBatch();(//这一句多次执行
pstm,executeBatch();//最后执行一次

/*        基本步骤,要点
*1,首先把Auto commit设置为false,不让它自动提交 
*2,进行手动提交(commit) 
*3,提交完成后回复现场将Auto commit,还原为true, 
*4,当异常发生执行catch中SQLException时,记得要rollback(回滚); 
* */
public void addItem2(int orderId,List<OrderItem> items){
Connection con=null;
try {
con=DataBase.getCon();
String sql="INSERT INTO orderitem(Order_id,Good_id,num,xj) VALUES(?,?,?,?)";
PreparedStatement pstm=con.prepareStatement(sql);
con.setAutoCommit(false);
for(OrderItem orderItem:items){
pstm.setInt(1, orderId);
pstm.setInt(2, orderItem.getGood().getId());
pstm.setInt(3, orderItem.getNum());
pstm.setDouble(4,orderItem.getXj());
pstm.addBatch();
}
pstm.executeBatch();
//手动提交
con.commit();
//提交完成后回复现场将Auto commit,还原为true
con.setAutoCommit(true);

} catch (Exception e) {
e.printStackTrace();
try{
if(!con.isClosed()){
//rollback: 若出现异常,对数据库中所有已完成的操作全部撤销,则回滚到事务开始状态
con.rollback();
con.setAutoCommit(true);
}
}catch(Exception ee){
ee.printStackTrace();
}
}finally{
DataBase.close(con);
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics