Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and mysql query check if result is empty

Tags:

java

mysql

ResultSet zoeken = stat.executeQuery("SELECT * FROM leden WHERE naam = '" + text + "'");
if (zoeken.getRow() == 0){
   System.out.println("hi");
}
while( zoeken.next() ){
   System.out.println(zoeken.getString(1) + zoeken.getString(2) + zoeken.getString(3));
}

I am using this to check if the result zoeken is empty, but it throws an exception saying its illegal to do that regardless if it works or not.

What is a better solution to check if result is empty or not

like image 585
hamchi Avatar asked Dec 09 '22 19:12

hamchi


2 Answers

// I am using this to check if the result"zoeken" is empty, but it throws an exception saying its illegal to do that. regardless if it works or not

Don't invoke ResultSet.getRow() before you invoke ResultSet.next().

From API:

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

       ResultSet zoeken = stat.executeQuery("SELECT * FROM leden WHERE naam = '" + text + "'");
       boolean val = zoeken.next(); //next() returns false if there are no-rows retrieved 
        if(val==false){
            System.out.println("zoken is empty"); //prints this message if your resultset is empty
         }
        while(val){// only runs when there are rows in the resultset
           System.out.println(zoeken.getString(1) + zoeken.getString(2) + zoeken.getString(3));
          val=zoeken.next(); //updating val again to check if there are rows in result set
        }

If your result set is empty zoeken.next() will return false in which case your while loop will not execute.

An Advice

use PreparedStatement Instead of simple Statement. simple statement would lead to SQL Injection and also would ease the pain for writing complex queries.Below is the sample code which use PreparedStatement.

String yourquery ="Select whatever From table where col1= ? and col2 =?"
PreparedStatement stmnt = Conn.preparedStatement(yourquery);
stmnt.setString(1, "val1");
stmnt.setString(2, "val2");
like image 171
PermGenError Avatar answered Dec 11 '22 08:12

PermGenError


Use next() method

boolean hasNext = zoeken.next();
like image 27
jmj Avatar answered Dec 11 '22 09:12

jmj