【问题标题】:JDBC: How to retrieve the result of SQL COUNT function from the result set?JDBC:如何从结果集中检索 SQL COUNT 函数的结果?
【发布时间】:2014-06-15 17:17:27
【问题描述】:

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

【问题讨论】:

  • @gubble 在这种情况下,在该答案中应用结果将给出 1,而 OP 需要在数据库上执行 COUNT 函数。
  • 我的问题与那个问题不同。他们想要获得结果集的大小。我直接想执行查询来获取行数! @gubble
  • @a_horse_with_no_name 对!匆忙输入的示例,我将更正它。

标签: java mysql sql jdbc


【解决方案1】:

给列命名:

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

【讨论】:

  • 非常感谢您的详尽回答。我很快就会了解准备好的语句。
  • @Zarah 不客气。我强烈建议您在使用普通 JDBC 时使用 PreparedStatements 而不是使用 Statement 接口。
  • 显示的代码不正确,它缺少对rs.next()的调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 2021-11-21
  • 1970-01-01
  • 2015-05-22
  • 2013-01-05
  • 1970-01-01
  • 2018-12-20
相关资源
最近更新 更多