java 如何从 ResultSet 对象中获取 COUNT?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16222398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get COUNT from ResultSet object?
提问by gjw80
I am passing the following query to a ResultSet object:
我将以下查询传递给 ResultSet 对象:
String query = "SELECT COUNT( DISTINCT KEY ), SOURCE FROM MY_TBL\n" +
"GROUP BY SOURCE\n" +
"ORDER BY SOURCE";
I want to capture the counts I am getting for each SOURCE and sum them into a total. How can I capture these counts via ResultSet since COUNT isn't a column name in the ResultSet and I don't think I can return it's value via rs.getInt("COUNT")
?
我想捕获我为每个 SOURCE 获得的计数并将它们加总。我如何通过 ResultSet 捕获这些计数,因为 COUNT 不是 ResultSet 中的列名,而且我认为我无法通过 返回它的值rs.getInt("COUNT")
?
回答by piokuc
getInt
is overloaded, use index (an int
) instead of a column name:
getInt
被过载,使用索引(一个int
),而不是列名:
rs.getInt(1); // the first column is 1
回答by Vjy
Try having alias
尝试使用别名
String query = "SELECT COUNT( DISTINCT KEY ) AS COUNT, SOURCE FROM MY_TBL\n" +
"GROUP BY SOURCE\n" +
"ORDER BY SOURCE";
回答by Raj Bhatta
I Think it is better to use
我认为最好使用
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * from Customer");
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
回答by Kunal Kakkad
I think "getColumnCount" retinto number of column in a table instead of number of rows...
我认为“getColumnCount”retinto 表中的列数而不是行数......