前言
- Spring Boot 提供了一个名为 JdbcTemplate 的轻量级数据访问工具,它是对 JDBC 的封装。Spring Boot 对 JdbcTemplate 提供了默认自动配置,我们可以直接使用 @Autowired 或构造函数将它注入到 bean 中使用。
1.创建JdbcTemplate
- 参考之前的文章,使用前需要配置数据库、配置数据源、配置jdbc驱动等
@Autowired
JdbcTemplate jdbcTemplate;
2.查询导出为简单对象
Integer i = jdbcTemplate.queryForObject("SELECT count(*) from `user`", Integer.class);
3.查询导出为自定义对象
4.查询导出为list
- 注意下面的
ResultSet
和匿名对象和List返回。
- 注意
rs.getInt("playerID"))
方法
- 本例实际返回的是
list<map>
。当然可以返回自定义对象等
- 返回
list<map>
方便传递给前端
String sql = "select playerID,sum(amount) as sumAmount from ecord group by playerID";
List lst = jdbcTemplate.query(sql, new RowMapper<Map<String,Integer>>() {
@Override
public Map<String, Integer> mapRow(ResultSet rs, int rowNum) throws SQLException {
Map<String,Integer> map = new HashMap<>();
map.put("playerID",rs.getInt("playerID"));
map.put("sumAmount",rs.getInt("sumAmount"));
return map;
}
});
网友评论