java mysql jdbcTemplate 使用

1.查询数量、ID int类型数据

String sql = "select count(id) from ddd "
int total= jdbcTemplate.queryForObject(sql,new Object[]{},Integer.class);

2.查询单条数据单个字段信息

String sql = "select name from ly_store_user where id=?";
try {
    String userInfo = jdbcTemplate.queryForObject(sql,new Object[]{user_id},String.class);
    System.out.println(userInfo);
    return userInfo;
} catch (Exception e) {
    e.printStackTrace();
    return null;
}

3.查询单条数据

String sql = "select * from ly_store_user where username=?";
try {
    StoreUser userInfo = jdbcTemplate.queryForObject(sql,new Object[]{username},new BeanPropertyRowMapper(StoreUser.class));
    return userInfo;
} catch (Exception e) {
  e.printStackTrace();
  return null;
}

4.多条数据查询

String sql = "select * from ly_store_user where id>10";

// 有实体类
List list = jdbcTemplate.query(sql.toString(),new Object[]{},new BeanPropertyRowMapper<>(StoreRecharge.class));
List> listData = new ArrayList>();
for (StoreRecharge info : list) {
    HashMap map = new HashMap();
    String newTime = DateUtil.timeStamp2Date(info.getCreated_at(), "yyyy-MM-dd");
    map.put("money",info.getMoney());
    map.put("money_give",info.getMoney_give());
    map.put("status",info.getStatus());
    map.put("created_at",newTime);
    listData.add(map);
}

// 无实体类
List> list = jdbcTemplate.queryForList(sql);//查询结果为储存map元素的集合
for (Map info : list) {
    String newTime = DateUtil.timeStamp2Date(info.get("created_at").toString(), "yyyy-MM-dd");
    info.put("created_at",newTime);
}

你可能感兴趣的:(java mysql jdbcTemplate 使用)