Java - 批量插入用法(jdbcTemplate)

来源:互联网 发布:用苹果手机拍淘宝图片 编辑:程序博客网 时间:2024/05/16 14:04

一个List类型的:

public void insertBooks(List<Book>book)
{
final List<Book>tempBook=book;
String sql="insert into book(name,pbYear)values(?,?)";
jdbcTemplate.batchUpdate(sql, newBatchPreparedStatementSetter()
{
public voidsetValues(PreparedStatement ps,int i)throws SQLException
{
Stringname=tempBook.get(i).getName();
intpbYear=tempBook.get(i).getPbYear();
ps.setString(1, name);
ps.setInt(2,pbYear);
}
public intgetBatchSize()
{
returntempBook.size();
}
});

}

两个数组类型的:

public int[] updateCompanyType(String[] unitIds, String[] unitType) {

           final List<String> list=new ArrayList<String>();
            for (int i = 0; i < unitIds.length; i++) {
                for (int j = 0; j < unitType.length; j++) {
                    list.add(unitIds[i]+","+unitType[j]);
                }
            }
        String sql="insert into map_unit_join_type (parentId,unitId,typeId,firstId,secondId,thirdId) values(?,?,?,?,?,?)";
               
        int[] counts=jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){
            public int getBatchSize() {
                return list.size();
            }
            public void setValues(PreparedStatement ps, int i)throws SQLException {
                String[] args=list.get(i).split(",");

                ps.setInt(1, Integer.parseInt(args[1]));
                ps.setInt(2, Integer.parseInt(args[0]));
                ps.setInt(3, Integer.parseInt(args[2]));
                ps.setInt(4, Integer.parseInt(args[3]));
                ps.setInt(5, Integer.parseInt(args[4]));
                ps.setInt(6, Integer.parseInt(args[5]));
            }
        });

}

0 0
原创粉丝点击