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>(StoreUser.class));
return userInfo;
} catch (Exception e) {
e.printStackTrace();
return null;
}
4.多条数据查询
String sql = "select * from ly_store_user where id>10";
// 有实体类
List<StoreRecharge> list = jdbcTemplate.query(sql.toString(),new Object[]{},new BeanPropertyRowMapper<>(StoreRecharge.class));
List<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();
for (StoreRecharge info : list) {
HashMap<String, Object> map = new HashMap<String, Object>();
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<Map<String, Object>> list = jdbcTemplate.queryForList(sql);//查询结果为储存map元素的集合
for (Map<String, Object> info : list) {
String newTime = DateUtil.timeStamp2Date(info.get("created_at").toString(), "yyyy-MM-dd");
info.put("created_at",newTime);
}
本文地址:https://blog.csdn.net/gugu251/article/details/109001801