JDBC:如何从结果集中检索SQL COUNT函数的结果?

时间:2014-04-29 16:28:03

标签: java mysql sql jdbc

通常,当我们想要从表中存在的数据库中检索一个值时,我们调用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( ????? );

1 个答案:

答案 0 :(得分:8)

为列命名:

ResultSet rs= stmt.executeQuery("select count(name) AS count_name from db.persons where school ='"+sch+"'");
int count= rs.getInt("count_name");

您还可以传递列的索引编号(如果您不想修改查询),该编号基于1。检查ResultSet#getInt(int columnIndex)

ResultSet rs= stmt.executeQuery("select count(name) from db.persons where school ='"+sch+"'");
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();
int count = rs.getInt("count_name");