空结果集异常
我想连接到oracle并获取一些记录。
java.sql.ResultSet r = s.executeQuery("Select * from table1");
while (r.next()==true) {
System.out.println(r.getString("column1").toString());
}
table1 包含像这样的行
- row1 movieName1
- row2 movieName2
- row3
- row4 movieName2
当我执行上述代码时,我收到“线程“main”java.lang.NullPointerException 中的异常”错误。我该如何解决它?
I want to connect to oracle and get some records.
java.sql.ResultSet r = s.executeQuery("Select * from table1");
while (r.next()==true) {
System.out.println(r.getString("column1").toString());
}
table1 include like that rows
- row1 movieName1
- row2 movieName2
- row3
- row4 movieName2
I get "Exception in thread "main" java.lang.NullPointerException" error when I execute above code. How can I fix it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
r.getString("column1") 的返回值可能为 null,因此您将在后续的
toString()
上得到NullPointerException
代码>方法调用。在使用返回值之前,您必须检查是否有 null 值。您不需要在此处调用
toString()
。getString
方法已返回一个字符串。The return value of
r.getString("column1")
might be null, so you will get aNullPointerException
on the subsequenttoString()
method call. You have to check for null values before you use the return value.You don't need to to call
toString()
here. ThegetString
method already returns a string.您没有说明异常发生在代码中的具体位置。最可能的原因是
s
为null
或r.getString("column1")
返回null
。You don't say where exactly in your code the exception occurs. The most likely causes are that
s
isnull
or thatr.getString("column1")
returnsnull
.也许你会得到空指针,因为 row3 具有空值,并且你正在尝试“toString”-it
maybe you get nullpointer because row3 has null value and you're trying to "toString"-it
如果您发布的第一行抛出错误,我的猜测是变量 s 为 null(未初始化),但由于您没有确切地告诉我们代码的哪一行抛出错误,因此很难判断。
If its the first line that you posted that throws the error my guess would be that the variable s is null (not initialized), but since you don't tell us exactly what line of your code throws the error its hard to tell.
嗯,看起来
column1
没有一行的值...因此getString()
返回一个空引用,然后您调用toString()
on - 导致异常。当您调用getString()
时,toString()
调用无论如何都是毫无意义的,因此您可以将其重写为:然后将打印
null
反而。如果您想避免这种情况,请使用:Well it looks like
column1
doesn't have a value for one row... sogetString()
is returning a null reference, which you're then callingtoString()
on - leading to the exception. As you're callinggetString()
thetoString()
call is pointless anyway, so you could rewrite it as:That will then print
null
instead. If you want to avoid that, use: