需求:获取A库表字段与数据,插入到b库表中;
难点:无法确定插入字段数量及插入的字段类型。
//注入jdbctemplate
@resource
jdbctemplate jdbctemplate;
1.获取A库表字段数量:
Statement statement = jdbcTemplate.getDataSource().getConnection().createStatement();
//查A库表
ResultSet rs = statement.executeQuery(sql);
List<String> columns = new ArrayList<>();
ResultSetMetaData meta = rs.getMetaData();
int cnt = meta.getColumnCount();
for (int i = 0; i < cnt; i++) {
columns.add(meta.getColumnTypeName(i+1));
}
2.根据获取表字段数量,拼接values 后面的问号
String valParams = cols.stream().map(x -> "?").collect(Collectors.joining(",", "(", ")"));
// 拼接插入字段名,tableColumns字段名称,
String collect1 = tableColumns.stream().collect(Collectors.joining(",", "(", ")"));
String insertSql = "insert into " + table +" "+ collect1 + "values " + valParams;
3.实现批量操作
// dataList 需要插入的的数据
List<String> finalRawList = dataList;
jdbcTemplate.batchUpdate(insertSql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
//第几批,批量插入
int temp = i * cols.size();
//一批插入多少个字段,遍历其类型,根据下标插入对应类型的值
for (int j = 0; j < cols.size(); j++) {
int index = j + 1;
int param = j+temp;
String columnTypeName = cols.get(j);
// 区分字段类型 设值
if (columnTypeName.contains("INT")) {
preparedStatement.setInt(index, Integer.parseInt(finalRawList.get(param)));
}
else if (columnTypeName.contains("DATE")){
preparedStatement.setDate(index, DateUtil.parse(finalRawList.get(param),"yyyy-MM-dd HH:mm:ss","yyyy/MM/dd HH:mm:ss").toSqlDate());
}
else if (columnTypeName.contains("VARCHAR")){
preparedStatement.setString(index, finalRawList.get(param));
}
else if (columnTypeName.contains("TIME")){
preparedStatement.setTimestamp(index, DateUtil.parse(finalRawList.get(param)).toTimestamp());
}
}
}
@Override
public int getBatchSize() {
//遍历上边方法次数
return finalRawList.size() / cols.size();
}
});
缺点:需自己定义涵盖的类型,进行判断插入值。
1357

被折叠的 条评论
为什么被折叠?



