ResultSet不为null,但给出空指针异常

时间:2014-07-15 11:17:44

标签: java jdbc

我在DB中有16到17条记录 但是,当我想要检索数据....在运行时我收到空指针异常 (抱歉英语不好)

 sql="SELECT * FROM CUSTOMER ORDER BY date DESC"; //my query
stmt=con.prepareStatement(sql);   //preparedStatement
System.out.println("2");    //checking output (where is exception)
rs=stmt.executeQuery();    //resultsetGlobal declare
System.out.println("3");    //checking outpur
i=0;    //for show record number
System.out.println(i);     //checking output
while(rs.next()){     //here i get the exception any one tell me why exception??
}

2 个答案:

答案 0 :(得分:1)

你无法在指向的地方找到NPE。 while(rs.next())当且仅当变量rs为空时,此行才会抛出NPE。 javadoc说:

  

executeQuery()返回包含数据的ResultSet对象   由给定查询产生;永远不会是

因此,在rs=stmt.executeQuery();之后,变量rs不能为空。 NPE的源可能是代码中的其他位置,但不是while循环中的条件。

答案 1 :(得分:0)

如果这是真正的代码,您必须设置' rs'要在之后,在'内'循环。

相关问题