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

laik7k3q  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(165)

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

wgx48brx1#

给予列命名:

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 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");
}

相关问题