通常,当我们想从数据库中检索表中的值时,我们调用 ResultSet 的适当方法并将我们要检索的列名传递给它。
ResultSet rs= stmt.executeQuery("select name from db.persons where school ='"+sch+"'");
int count= rs.getString("person_name");
但是当我们想要获取特定列中的行(或字段)的计数时(我们使用 SQL COUNT 函数),我们如何检索结果。我应该在以下代码中的 rs.getInt() 方法中传递什么参数?
ResultSet rs= stmt.executeQuery("select count(name) from db.persons where school ='"+sch+"'");
int count= rs.getInt( ????? );
最佳答案
为列命名:
ResultSet rs= stmt.executeQuery("select count(name) AS count_name from db.persons where school ='"+sch+"'");
if (rs.next()) {
int count= rs.getInt("count_name");
}
您还可以传递基于 1 的列索引号(以防您不想修改查询)。检查ResultSet#getInt(int columnIndex)
:
ResultSet rs= stmt.executeQuery("select count(name) from db.persons where school ='"+sch+"'");
if (rs.next()) {
int count= rs.getInt(1);
}
除此之外,如果您使用 PreparedStatement
会更好执行您的查询,它比普通的 Statement
有很多优势,如下所述:Difference between Statement and PreparedStatement .您的代码如下所示:
String sql = "select count(name) AS count_name from db.persons where school = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, sch);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
int count = rs.getInt("count_name");
}
关于java - 如何从结果集中检索 SQL COUNT 函数的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23370243/