I am using HSQLDB in my program. I want to check if my Result Set is empty or not.
//check if empty first
if(results.next() == false){
System.out.println("empty");
}
//display results
while (results.next()) {
String data = results.getString("first_name");
//name.setText(data);
System.out.println(data);
}
The above method is not working properly. According to this post I have to call .first()
or .beforeFirst()
to rest the cursor to the first row, but .first()
and .beforFirst()
are not supported in HSQL. I also tried to add connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
but I still get the same outcome (I get the message empty and the data from the DB!!!)
What am I doing wrong here?
Hence, when a Java programmer needs to determine if ResultSet is empty or not, it just calls the next() method and if next() returns false it means ResultSet is empty.
getString(String columnLabel) Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. Time. getTime(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a java.
No matter how many rows are returned(starting from 0), the resultSet will never be null. The only case in which a resultset will remain null is when an exception is thrown... but the program flow will jump to the Exception handling block anyways.
The isAfterLast() method of the ResultSet interface is used to determine whether the cursor is on the last row of the ResultSet. rs. isLast(); This method returns an boolean this value is true, if the cursor is on the last row of the ResultSet else, it returns false.
If I understand your objective, you could use do while
loop
if (!results.next()) {
System.out.println("empty");
} else {
//display results
do {
String data = results.getString("first_name");
//name.setText(data);
System.out.println(data);
} while (results.next());
}
Or, you could just keep a count
like so,
int count = 0;
//display results
while (results.next()) {
String data = results.getString("first_name");
//name.setText(data);
System.out.println(data);
count++;
}
if (count < 1) {
// Didn't even read one row
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With