简体   繁体   English

为什么要使用结果集!= null是否检查null

[英]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" . 即使rs为null,它也会打印“结果集有问题” 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. 作为查询结果返回的JDBC ResultSet对象永远不会为null,请阅读javadoc。 So the way you are checking is wrong. 因此,您检查的方式是错误的。 You can use ResultSet.next() method instead. 您可以改用ResultSet.next()方法。

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; 一个ResultSet对象维护一个指向其当前数据行的游标-除非您的调用方法不能保证通过通过特定查询执行一条语句,然后使用来处理Null指针,否则将生成传递的结果集。

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; 然后无需执行Null点检查,只需直接指向该点并询问ResultSet是否包含数据;

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. 对于记录集,最好使用Java提供的三元运算符。 For eg: 例如:

Say you want to set the name to the user object pojo. 假设您要将名称设置为用户对象pojo。

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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