Is it possible to know the number of records in a ResultSet? Java

0

I have a small concern about ResultSet in Java, my question is

Can we know the number of records they have at the time of completing a query?

I want to get this information to be able to perform an action with this amount of records.

So far what I have researched is that with getMetaData() I could get this number, but, until now I have only been able to extract is the number of columns that the query brings.

The other solution that I have thought is to make a query before the one that brings the data to count the number of records with COUNT() , but, I do not know before I wanted to know if this is possible.

    
asked by Salth95 15.06.2017 в 21:45
source

3 answers

2

There is not a way TO still know the total. But if you are already handling the data and you need to know the total of this, you can do something like this:

int total = 0;
while (result.next()){
   //Obtienes la data que necesitas...
   total++;
}
System.out.println("El total de registros es : "+total);

Also, what you can do is use the last() method, you can check if the item you are currently traveling is the last one then it would be like this:

try {
    boolean ultimo = result.last();
    int total = 0;
    if (ultimo) { 
        total = result.getRow();
    }
} catch (SQLException e) {
    e.printStackTrace();
}

getRow returns a data of int type and is the number of the current row, so if you had 10 results for example, you will drop the last() in the 10 and so you would know the total results.

  

int getRow () throws SQLException   Retrieve the number of the current row. The first row is number 1, the second row is 2, and so on.

    
answered by 15.06.2017 / 21:51
source
1

If what you want is to know the number of records that you obtained from your query result set you can use the following code:

int count = 0;

while (rs.next()) {
    ++count;
}

if (count != 0) {
    System.out.println("Existen " + count.toString() + " registros.");
}

I hope I have helped you, regards.

    
answered by 15.06.2017 в 21:53
1

Another way to do this would be to move the cursor to the end with last() and then get the getRow() that returns the current row number. (starts at 1)

if (rs.last()) 
   System.out.println("Cantidad de Registros : "  + rs.getRow());
else
   System.out.println("No Hay Registros ");
    
answered by 15.06.2017 в 21:56