我想知道如何获得数据库中特定列的计数。我的列中的每个不同值我想将返回的列值及其计数存储在 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 并返回图表的计数值。如果有帮助,这是我的SightingRowMapper:
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;
}