美文网首页
2022-04-05_JdbcTemplate

2022-04-05_JdbcTemplate

作者: 微笑碧落 | 来源:发表于2022-04-08 09:30 被阅读0次

    前言

    • 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;
        }
    });
    

    相关文章

      网友评论

          本文标题:2022-04-05_JdbcTemplate

          本文链接:https://www.haomeiwen.com/subject/cflksrtx.html