简体   繁体   English

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

[英]ResultSet is not null but giving a null pointer exception

i have 16 to 17 record in DB BUT when i want to retrive data.... on the run time i received null pointer exceptiion (sorry for bad english) 当我想检索数据时,我在DB BUT中有16至17条记录...。在运行时,我收到了空指针exceptiion(对不起,英语不好)

 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??
}

You cannot get NPE where you are pointing. 您不能将NPE指向您指向的位置。 while(rs.next()) this line will throw NPE if and only if the variable rs is null. while(rs.next())当且仅当变量rs为null时,此行才会抛出NPE。 And the javadoc says: Javadoc说:

executeQuery() returns a ResultSet object that contains the data produced by the given query; executeQuery()返回一个ResultSet对象,该对象包含给定查询产生的数据; never null` 永不为零

Hence, after rs=stmt.executeQuery(); 因此,在rs=stmt.executeQuery(); the variable rs cannot be null. 变量rs不能为null。 The source of the NPE could be somewhere else in the code but not the condition in while loop. NPE的源可能在代码中的其他位置,但不在while循环中。

如果这是真实的代码,则必须稍后在“ while”循环内将“ rs”设置为null。

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

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