从查询中存储计数值

时间:2013-10-24 13:31:29

标签: java mysql sql spring jdbc

如何将返回的计数值存储到变量中,然后我可以用它设置属性?到目前为止,这是我的方法:

public List<Sighting> total() {

     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(????); // I need to pass a variable to setCount()
                sighting.setPest_name(rs.getString("pest_name"));
                return sighting;
            }      
       });
}

查询中的计数值..

3 个答案:

答案 0 :(得分:3)

您可以指定计数的名称,例如

return jdbc.query("select pest_name, count(pest_name) as pest_count 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("pest_count"));
                sighting.setPest_name(rs.getString("pest_name"));
                return sighting;
            }      
       });

...或者只按列号获取:

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(2));
                sighting.setPest_name(rs.getString("pest_name"));
                return sighting;
            }      
       });

您可能需要使用getLong代替getInt

答案 1 :(得分:2)

尝试:

Select pest_name, count(pest_name)  as totalCount

并在结果集中尝试使用

long count = rs.getLong("totalCount")

答案 2 :(得分:0)

命名您的点数。变化

"select pest_name, count(pest_name) from sighting group by pest_name"

"select pest_name, count(pest_name) as pest_count from sighting group by pest_name"