JDBC 批量处理
public void insertBatch(final List<Customer> customers){ String sql = "INSERT INTO CUSTOMER (CUST_ID, NAME, AGE) VALUES (?, ?, ?)"; getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { Customer customer = customers.get(i); ps.setLong(1, customer.getCustId()); ps.setString(2, customer.getName()); ps.setInt(3, customer.getAge() ); } @Override public int getBatchSize() { return customers.size(); } }); }
注意:url jdbc:mysql://localhost:3306/yiibaijava 注意驱动url 的编写
实例
List<Object[]> batchargs = new ArrayList<>();
String sql = "INSERT INTO tableName (commodityId, commodityName, commodityURL, commodityPrice, commodityPromo, commodityCommentCount, cityCode, shopType, shopTrade, status, shopId, shopName, updateTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; Object[] das = {commodityId, commodityName, commodityURL, commodityPrice, commodityPromo, commodityCommentCount, cityCode, shopType, shopTrade, status, shopId, shopName, updateTime}; batchargs.add(das); if (batchargs.size() % 1000 == 0) { jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { for (int j = 0; j < 13; j++) { ps.setString(j + 1, batchargs.get(i)[j] == null ? "" : batchargs.get(i)[j].toString()); } } @Override public int getBatchSize() { return batchargs.size(); } }); batchargs.clear(); LOG.info("#######################-入库 :" + totalCount + "-#########################"); }