将sql改成jdbctemplete方式查询 List<List<String>> assetscardcodeQueryList = new ArrayList<>(); ArrayList<String> query1 = new ArrayList<>(); ArrayList<String> query2 = new ArrayList<>(); query1.add("000000009247"); query2.add("000000009247"); assetscardcodeQueryList.add(query1); assetscardcodeQueryList.add(query2); List<List<String>> assetscardcodeAndBukrsQueryList = new ArrayList<>(); ArrayList<String> query3 = new ArrayList<>(); query3.add("400000001644"); query3.add("A017"); query3.add("400000001641"); query3.add("A017"); String sql="select * from table where (cloum1,cloum2) in (( 'A017', '400000001644'), ('A017', '400000001641')) or cloum1 in ('000000009247','000000009247');"
时间: 2024-03-16 12:44:46 浏览: 91
使用JDBC从数据库中查询数据的方法
5星 · 资源好评率100%
下面是将这个SQL查询改成使用JdbcTemplate执行的代码:
```
List<List<String>> assetscardcodeQueryList = new ArrayList<>();
ArrayList<String> query1 = new ArrayList<>();
ArrayList<String> query2 = new ArrayList<>();
query1.add("000000009247");
query2.add("000000009247");
assetscardcodeQueryList.add(query1);
assetscardcodeQueryList.add(query2);
List<List<String>> assetscardcodeAndBukrsQueryList = new ArrayList<>();
ArrayList<String> query3 = new ArrayList<>();
query3.add("400000001644");
query3.add("A017");
query3.add("400000001641");
query3.add("A017");
String sql = "select * from table where (cloum1,cloum2) in " +
"(?, ?)" + ", ".repeat(assetscardcodeAndBukrsQueryList.size() - 1) + "or cloum1 in " +
"(?" + ", ?".repeat(assetscardcodeQueryList.size() - 1) + ")";
List<Object> params = new ArrayList<>();
for (List<String> cloumPair : assetscardcodeAndBukrsQueryList) {
params.addAll(cloumPair);
}
params.addAll(assetscardcodeQueryList.stream().flatMap(Collection::stream).collect(Collectors.toList()));
List<Map<String, Object>> rows = jdbcTemplate.query(sql, params.toArray(), new RowMapper<Map<String, Object>>() {
@Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
Map<String, Object> row = new HashMap<>();
for (int i = 1; i <= meta.getColumnCount(); i++) {
row.put(meta.getColumnName(i), rs.getObject(i));
}
return row;
}
});
// 处理查询结果
for (Map<String, Object> row : rows) {
// do something
}
```
这里使用了与前面相同的动态生成SQL语句和参数设置方式,只是将参数列表改成了从Java对象中获取。最终,该方法将返回一个包含查询结果的列表,每个结果都是一个Map对象,其中包含列名和对应的值。你可以根据需要处理该结果集。
阅读全文