2013-10-24 79 views
0

如何將返回的計數值存儲到變量中,然後我可以使用它設置一個屬性?這是迄今爲止我的方法:從查詢中存儲計數值

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

您既可以指定一個名稱爲計數,例如

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

+0

非常感謝。兩種解決方案都經過了測試並正常工作非常感激。 – Maff

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" 
2

嘗試:

Select pest_name, count(pest_name) as totalCount 

,並在結果嘗試

long count = rs.getLong("totalCount")