简体   繁体   中英

why to use resultset!=null does it check for null

I have following code

if (rs != null)
{
  out.println("result set has got something");
  while (rs.next())
  { 
    //I am processing result set now
  }
}
else
{
  out.println("result set is empty");
}

Even though rs is null it is printing "resultset has got something" . Why is it happening like that and how can I check for empty result set?

You could check it with:

if(rs != null && rs.next()) {
    out.println("result set has got something");
    do {
        // do what you have to do
    } while (rs.next());
} else {
    out.println("result set is empty");
}

JDBC ResultSet objects returned as a query result are never null please read the javadoc. So the way you are checking is wrong. You can use ResultSet.next() method instead.

A ResultSet object maintains a cursor pointing to its current row of data - Unless your calling method has no guarantee the passed Resultset is generated by executing a statement via a specific query, then handling the Null Pointer using;

if(rs !=null && rs.next())
{
 ..
}

is essential -but if you're handling

ResultSet rs = stmt.executeQuery(..);

then no need performing Null point checking, just go straight to the point and ask ResultSet if it holds data;

String name=null;
while (rs.next()) 
{
 name =rs.getString(1);
}

and then handle values like this;

if(name !=null && name.length()>0)
{
 ..        
}

For record sets, its always better to use ternary operators provided by Java. For eg:

Say you want to set the name to the user object pojo.

myUser.setName(null != recordSet.getString("name") ? recordSet.getString("name") : "Guest");

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM