我想知道如何获取数据库中特定列的计数。我的列中的每个不同值我想将返回的列值及其计数存储在Java列表中。这就是我到目前为止所做的:
public List<Sighting> getCountPest() {
return jdbc.query("select pest_name, count(pest_name) from sighting group by pest_name", new RowMapper<Sighting>() {
public Sighting mapRow(ResultSet rs, int rowNum) throws SQLException {
Sighting sighting = new Sighting();
sighting.setCount(rs.getInt("count")); // will not work as no column name in table
sighting.setPest_name(rs.getString("pest_name"));
return sighting;
}
});
}
基本上我想使用pest_name并返回图表的计数值。 如果有帮助的话,这就是我的瞄准流量映射器:
public Sighting mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUsername(rs.getString("username")); // setting the username if logged in
Sighting sighting = new Sighting();
sighting.setId(rs.getInt("id"));
sighting.setTotal_pests(rs.getInt("total_pests"));
sighting.setDate(rs.getString("date"));
sighting.setInformation(rs.getString("information"));
sighting.setPest_name(rs.getString("pest_name"));
sighting.setPark(rs.getString("park"));
sighting.setLocation(rs.getString("location"));
sighting.set_Username(rs.getString("username"));
sighting.setUser(user);
return sighting;
}
答案 0 :(得分:2)
瞄准我猜你需要另一个结果映射器,它只需要处理pest_name
和count
列。至少它会更干净。
如果您不喜欢为此创建新类,则可以创建匿名类:
jdbc.query(
"select pest_name, count(pest_name) from sighting group by pest_name",
new RowMapper<Sighting>() {
public Sighting mapRow(ResultSet rs, int rowNum) throws SQLException {
return sighting;
}
});
或者使用现有的,但稍微更改一下查询:
select pest_name, count(pest_name) as total_pests
但这是一个黑客:)