我有以下sql查询,并希望在spring:{/ p>中使用JdbcTemplate
String sql = "SELECT name, age FROM EMPLOYEE WHERE age >= ?";
List<Employee> employees = jdbcTemplate.query(sql, 18, new EmployeeRowMapper());
public class EmployeeRowMapper implements RowMapper<Employee> {
@Override
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee employee = new Employee();
employee.setName(rs.getString("name"));
employee.setAge(rs.getString("age"));
return employee;
}
}
问题:如果我在任何常见的sql工具中执行sql,我只关心输出的内容怎么办?输出将是:
name;age
john;18
doh;22
...
我知道我的sql,我知道我要回到2列,第一列是名字,第二列是年龄。那么对我来说,通过明确使用列名来提取数据是不必要的,例如rs.getString("age")
?
如何使用JdbcTemplate
将结果作为csv列表输出,而不必将其映射到对象?
答案 0 :(得分:1)
String sql = "SELECT name || ';' || age FROM EMPLOYEE WHERE age >= ?";
List<String> employees = jdbcTemplate.queryForList(sql, String.class, 18);
答案 1 :(得分:0)
final StringBuiler sb = new StringBuilder();
ResultSetExtractor rse = new ResultSetExtractor() {
@Override
public String extractData(ResultSet rs) throws SQLException, DataAccessException {
while (rs.next()) {
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
sb.append(rs.getObject(i));
}
sb.append("\n");
}
return sb.toString();
}
};
jdbcTemplate.query(sql, 18, rse);