java 为什么要使用 resultset!=null 是否检查 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10513288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why to use resultset!=null does it check for null
提问by Raghavender Reddy
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?
即使 rs 为 null 它也在打印"resultset has got something"。为什么会这样,我如何检查空结果集?
回答by sebastian
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");
}
回答by Thihara
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.
作为查询结果返回的 JDBC ResultSet 对象永远不会为空,请阅读 javadoc。所以你检查的方式是错误的。您可以改用ResultSet.next()
方法。
回答by Bitmap
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
对象维护一个指向其当前数据行的游标 - 除非您的调用方法不能保证传递的结果集是通过特定查询执行语句生成的,然后使用处理空指针;
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 point检查了,直接到点去询问ResultSet是否有数据;
String name=null;
while (rs.next())
{
name =rs.getString(1);
}
and then handle values like this;
然后像这样处理值;
if(name !=null && name.length()>0)
{
..
}
回答by Ashutosh
For record sets, its always better to use ternary operators provided by Java. For eg:
对于记录集,最好使用 Java 提供的三元运算符。例如:
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.
希望这可以帮助。