Get Number of Rows returned by ResultSet in Java
Another way to differentiate between 0 rows or some rows from a ResultSet:
ResultSet res = getData();
if(!res.isBeforeFirst()){ //res.isBeforeFirst() is true if the cursor
//is before the first row. If res contains
//no rows, rs.isBeforeFirst() is false.
System.out.println("0 rows");
}
else{
while(res.next()){
// code to display the rows in the table.
}
}
If you must know the number of rows given a ResultSet, here is a method to get it:
public int getRows(ResultSet res){
int totalRows = 0;
try {
res.last();
totalRows = res.getRow();
res.beforeFirst();
}
catch(Exception ex) {
return 0;
}
return totalRows ;
}
First, you should create Statement
which can be move cursor by command:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
Then retrieve the ResultSet
as below:
ResultSet rs = stmt.executeQuery(...);
Move cursor to the latest row and get it:
if (rs.last()) {
int rows = rs.getRow();
// Move to beginning
rs.beforeFirst();
...
}
Then rows variable will contains number of rows returned by sql
You could use a do ... while
loop instead of a while
loop, so that rs.next()
is called after the loop is executed, like this:
if (!rs.next()) { //if rs.next() returns false
//then there are no rows.
System.out.println("No records found");
}
else {
do {
// Get data from the current row and use it
} while (rs.next());
}
Or count the rows yourself as you're getting them:
int count = 0;
while (rs.next()) {
++count;
// Get data from the current row and use it
}
if (count == 0) {
System.out.println("No records found");
}
A simple getRowCount
method can look like this :
private int getRowCount(ResultSet resultSet) {
if (resultSet == null) {
return 0;
}
try {
resultSet.last();
return resultSet.getRow();
} catch (SQLException exp) {
exp.printStackTrace();
} finally {
try {
resultSet.beforeFirst();
} catch (SQLException exp) {
exp.printStackTrace();
}
}
return 0;
}
Just to be aware that this method will need a scroll sensitive resultSet
, so while creating the connection you have to specify the scroll option. Default is FORWARD and using this method will throw you exception.