@Autowired
private JdbcTemplate jdbcTemplate_mysql;
方法1:
public int[] batchUpdate(final List<Persons> list) {
String sql = "insert into persons(FirstName,LastName,age,flag) values(?,?,?,?)";
return jdbcTemplate_mysql.batchUpdate(sql,
new BatchPreparedStatementSetter() {
public int getBatchSize() {
return list.size();
}
public void setValues(PreparedStatement ps, int i)
throws SQLException {
Persons p = (Persons) list.get(i);
ps.setString(1, p.getFirstName()); // 设置参数值
ps.setString(2, p.getLastName());
ps.setString(3, p.getAge());
ps.setString(4, p.getFlag());
}
});
}
方法2:
public int[] batchUpdate2(final List<Persons> list) {
String sql = "insert into persons(FirstName,LastName,age,flag) values(";
String[] sqls = new String[list.size()];
List<String> sqlList = new ArrayList<String>();
for (Persons p : list) {
sqlList.add(sql + "'" + p.getFirstName() + "','" + p.getLastName()
+ "','" + p.getAge() + "','" + p.getFlag() + "');"); // 拼sql字符串数组
}
sqlList.toArray(sqls);
return jdbcTemplate_mysql.batchUpdate(sqls);
}
转载于:https://blog.51cto.com/fanson59/1316808