1

我想知道如何获得数据库中特定列的计数。我的列中的每个不同值我想将返回的列值及其计数存储在 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;
}
4

1 回答 1

2

瞄准我猜你需要另一个结果映射器,它只处理pest_namecount列。至少它会更干净。

如果您不喜欢为此创建新类,则可以创建匿名类:

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

但这是一个黑客:)

于 2013-10-24T12:17:35.130 回答