Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if ResultSet is empty in Java [duplicate]

Tags:

java

jdbc

hsqldb

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?

like image 222
Max Pain Avatar asked Jun 25 '14 00:06

Max Pain


People also ask

How do you check if a ResultSet is empty?

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.

What is ResultSet getString ()?

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.

Can a ResultSet be null?

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.

How can you tell if a record is last ResultSet?

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.


1 Answers

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
}
like image 137
Elliott Frisch Avatar answered Oct 03 '22 11:10

Elliott Frisch