jdbc的批量操作使用和注意事项

//一个批量更新方法
private void doUpdateSeqence4Batch(List updates) {
if(null == updates || updates.isEmpty())return ;
String sql = "update sys_sequence set seqenceCode =?,directionCode = ? where positionCode = ?";
Connection conn = null ;
PreparedStatement pstm = null ;
try {
conn = this.getConnection();
conn.setAutoCommit(false) ; //设置自动提交为false
pstm = conn.prepareStatement(sql) ;
int i = 0 ;
for(Seqence seqence : updates){ 
i++;
pstm.setString(1, seqence.getSeqenceCode()) ;
pstm.setString(2, seqence.getDirectionCode()) ;
pstm.setString(3, seqence.getPositionCode()) ;
pstm.addBatch() ;
//当更新信息全部处理完毕后或数量为200时才执行批量操作语句,并对该批量操作提交事务。
if(i%200 == 0 || i == (updates.size())) {
pstm.executeBatch() ;
conn.commit() ;
pstm.clearBatch();
}
}
} catch (SQLException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally{
JdbcUtil.close(null, pstm, conn) ;
}
}

以上代码的知识点:
1:批量操作的写法。
2:重点是事务的设置,若不进行设置 conn.setAutoCommit(false) ; 默认即为自动提交事务,但是不是给批量操作添加事务,即当一条更新操作发生异常时,只回滚该条更新操作的数据,所以批量操作时先关闭自动提交,在批量操作执行时提交,即保证整个操作中若有更新异常则回滚至批量操作前的状态,又减少了创建的事务条数,进而提高效率。

你可能感兴趣的:(经验总结)