10

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?

Community
  • 1
  • 1
Max Pain
  • 1,217
  • 7
  • 19
  • 33
  • 2
    What is the problem? An observation: the `results.next()` moves the cursor to the first row when called for the first time (in the `if`). Hence, if there is data, your while loop's condition will move it to the second row when it starts effectively skipping the first row. You may use a do-while loop instead. – Islay Jun 25 '14 at 01:05
  • The question you linked to also has answer for `FORWARD_ONLY` resultsets (eg: the accepted answer). – Mark Rotteveel Jun 25 '14 at 06:19

1 Answers1

16

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
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249