如何从ResultSet对象获取COUNT?

时间:2013-04-25 18:46:27

标签: java jdbc resultset

我将以下查询传递给ResultSet对象:

String query = "SELECT COUNT( DISTINCT KEY ), SOURCE FROM MY_TBL\n" +
            "GROUP BY SOURCE\n" +
            "ORDER BY SOURCE";

我希望捕获每个SOURCE获得的计数并将它们总计为总计。如何通过ResultSet捕获这些计数,因为COUNT不是ResultSet中的列名,我认为我不能通过rs.getInt("COUNT")返回它的值?

4 个答案:

答案 0 :(得分:9)

getIntoverloaded,使用索引(int)代替列名:

 rs.getInt(1); // the first column is 1

答案 1 :(得分:0)

尝试使用别名

String query = "SELECT COUNT( DISTINCT KEY ) AS COUNT, SOURCE FROM MY_TBL\n" +
        "GROUP BY SOURCE\n" +
        "ORDER BY SOURCE";

答案 2 :(得分:0)

我认为最好使用

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * from Customer");
ResultSetMetaData rsmd = rs.getMetaData();

int numCols = rsmd.getColumnCount();

答案 3 :(得分:-1)

我认为" getColumnCount" retinto表中的列数而不是行数...