获取 Java 结果集中的行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3052714/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:01:44  来源:igfitidea点击:

Getting the count of rows in a Java resultset

javamysqljdbc

提问by Mr Morgan

Does anyone know a better way of getting the number of rows in a Java resultset returned from a MySQL database? The resultset returned is not going to be the total number of rows read from the database so I don't think I can use SQL's COUNTaggregate function.

有谁知道获取从 MySQL 数据库返回的 Java 结果集中的行数的更好方法吗?返回的结果集不会是从数据库读取的总行数,所以我认为我不能使用 SQL 的COUNT聚合函数。

public static int getResultSetRowCount(ResultSet resultSet) {
    int size = 0;
    try {
        resultSet.last();
        size = resultSet.getRow();
        resultSet.beforeFirst();
    }
    catch(Exception ex) {
        return 0;
    }
    return size;
}

采纳答案by duffymo

A better answer is to forget about the number of rows until you've successfully loaded the ResultSet into an object or collection. You can keep the count of the number of rows with either of those options.

更好的答案是忘记行数,直到您成功将 ResultSet 加载到对象或集合中。您可以使用这些选项中的任何一个来保持行数。

It's important to close ResultSets (and all SQL resources like Connection and Statement) in the narrowest method scope possible. That means not passing ResultSet out of the persistence layer. Better to get the number of rows using a Collection size() call.

在尽可能窄的方法范围内关闭 ResultSets(以及所有 SQL 资源,如 Connection 和 Statement)非常重要。这意味着不要将 ResultSet 传递出持久层。最好使用 Collection size() 调用获取行数。

Stop thinking about databases and start thinking in terms of objects. Java's an object-oriented language.

停止考虑数据库并开始考虑对象。Java 是一种面向对象的语言。

回答by Lalith

You can execute

你可以执行

SELECT FOUND_ROWS()

immediately after executing your SELECT statement to find the row count.

在执行 SELECT 语句以查找行数后立即执行。

回答by Adeel Ansari

You can always use SELECT COUNT()with the same exact conditions, before making the actual SELECT.

您可以随时使用SELECT COUNT()带有完全相同的条件下,使实际前SELECT

回答by Andre Farina

If you are using Java 6 you can use the JDBC4ResultSet class which has the getUpdateCount method that returns the number of the lines affected by a SQL Statement even for a Select Statement.

如果您使用的是 Java 6,则可以使用 JDBC4ResultSet 类,该类具有 getUpdateCount 方法,该方法返回受 SQL 语句影响的行数,即使对于 Select 语句也是如此。

See below the example code:

请参阅下面的示例代码:

PreparedStatement ps = con.prepareStatement("select * from any_table ...");
JDBC4ResultSet rs = (JDBC4ResultSet)ps.executeQuery();
int rowNumber = rs.getUpdateCount();

I hope that this help!

我希望这有帮助!

回答by Kingsolmn

Here is my solution to this question (since I mostly want the number of records returned to build an array or something similar): Use a collection such as Vector<T>instead.

这是我对这个问题的解决方案(因为我最想要返回的记录数来构建数组或类似的东西):改用诸如Vector<T> 之类的集合。

public Vector<T> getRecords(){
   Vector<T> records = new Vector<T>();
   init_conn_and_stmt_and_rs();

   try {
      rs = stmt.executeQuery("SELECT * FROM `table` WHERE `something` = 0");
      while(rs.next()){
         // Load the Vector here.
      }
   } catch (SQLException e) {
      e.printStackTrace();
   }finally{
      close_rs_and_stmt_and_conn();
   }
   return records;
}

Clean and simple, no? Works for any size record set returned (no need to know the size before hand) and makes all the Listmethods available.

干净简单,不是吗?适用于返回的任何大小的记录集(无需事先知道大小)并使所有List方法可用。

This has served me well for a time now, but if someone sees a flaw in this, please let me know. Always want to make my practices better, ya know.

一段时间以来,这对我很有帮助,但是如果有人发现其中的缺陷,请告诉我。总是想让我的练习更好,你知道。

回答by yi2ng2

You can also use the following way to get the total records in the resultSet:

也可以通过以下方式获取resultSet中的总记录数:

statement = connect.createStatement();
resultSet = statement.executeQuery(sqlStatement);
resultSet.last();
int count = resultSet.getRow();
System.out.println(count);

countis the total returned rows for your result set. ;)

count是结果集返回的总行数。;)

回答by Karima Rafes

See below the example code with the solution of Lalith :

请参阅下面带有 Lalith 解决方案的示例代码:

public static int getResultSetRowCount(connection) {
    int size = 0; 
    statement = connection.createStatement(); 
    try {
        resultSet = statement.executeQuery("SELECT FOUND_ROWS()")
        resultSet.next()
        size = resultSet.getInt(1)
    }
    catch(Exception ex) {
        return 0;
    }
    statement.close();
    return size;
}