PreparedStatement定义要在for外面,定义具有占位符的statement,for中只负责设参数值。
示例代码:
public int insertTCollectionBatched(List<TCollection> list) {
Connection conn = ConnectionPool.getConnection();
PreparedStatement stat = null;
ResultSet rs = null;
String sql = "INSERT INTO table" +
+ " (ParentID, ScanTime, ExtParam1, ExtParam2)" +
" VALUES (?,?,?,?)";
try {
conn.setAutoCommit(false);
stat = conn.prepareStatement(sql);
int[] counts = {};
for(TCollection collection:list){
setPropertyValue(collection, stat);
stat.addBatch();
}
counts = stat.executeBatch();
conn.commit();
return counts.length;
}catch(Exception e){
LogUtil.error(e);
}finally{
ConnectionPool.attemptClose(rs, stat, conn);
}
return 0 ;
}
SQL占位参数设值代码:
private void setPropertyValue(TCollection collection, PreparedStatement stat)
throws SQLException {
//根据属性值是否传入,设置SQL INT类型参数,未传递的设置默认值,避免SQL异常
if(collection.getParentId()!=null){
stat.setInt(1, collection.getParentId());
}else{
stat.setInt(1, 0);
}
if(collection.getScanTime()!=null){
stat.setString(2, collection.getScanTime());
}else{
stat.setString(2, DateTimeUtil.nowAsString());
}
//必须非空
stat.setString(3, collection.getParam1());
stat.setString(4, collection.getParam2());
}
jdbc批量插入,数据只有一条