我正在做一个项目,用户应该在表单中填写他想要的标准,然后根据这些标准,servlet 从数据库中返回适当的结果;我正在使用mysql服务器。我的问题是我使用的 Prepared Statement(因为用户可以使用可变数量的条件进行搜索)总是返回 null,所以我得到一个
Exception: null java.lang.NullPointerException at
Servlet_GrowerResults.doGet(Servlet_GrowerResults.java:102)
这是 GetData 类中的 fetchGrowers 方法,它将 ResultSet 返回给 Servlet_GrowerResults
private PreparedStatement stmt_growers=null;
private ResultSet rs_growers;
private final String getGrowersQuery="select * from grower where name like ? and surname like ? and area like ? and partnership like ?;";
public ResultSet fetchGrowers(String criteria_name,String criteria_surname,String criteria_area, String criteria_partnership){
try{
stmt_growers=dbcon.getConnection().prepareStatement(getGrowersQuery);
stmt_growers.setString(1, criteria_name);
stmt_growers.setString(3, criteria_surname);
stmt_growers.setString(5, criteria_area);
stmt_growers.setString(7, criteria_partnership);
rs_growers=stmt_growers.executeQuery();
return rs_growers;
}
catch(Exception e9){
errorMessage = "Error while getting all growers from database!<br>" + e9.getMessage();
return null;
}
这是初始化 ResultSet 的行。如果涵盖所有提交的标准案例,还有其他其他方法
try{
getData.getDBcon().open();
ResultSet rsAreas=getData.fetchGrowerAreas();
ResultSet rsPartnership=getData.fetchGrowerPartnership();
ResultSet rsGrowersReturned;
String sqlWildcard="%";
//Cases of criteria submited by the user,
//in order to send the apropriate parameters
//to the PreparedStatement
//1st case: searching without names criteria
if( (criteriaNames.length()>0) && (!(criteriaAreas.length()>0)) && (!(criteriaPartnerships.length()>0)) ){
rsGrowersReturned=getData.fetchGrowers(sqlWildcard,sqlWildcard,criteriaAreas,criteriaPartnerships);
}
这是异常指向的行。更具体地说,第 102 行是:while(rsGrowersReturned.next())
if((sorting.equals("περιοχή"))){
while(rsAreas.next()){
out.println("<table>");
String area=rsAreas.getString("area");
area = new String(area.getBytes("ISO-8859-1"), "ISO-8859-7");
out.println("<tr><th>"+rsAreas.getString("area")+"</th></tr>");
/*line 102*/ while(rsGrowersReturned.next()){
if(rsGrowersReturned.getString("area").equals(rsAreas.getString("area"))){
String name=rsGrowersReturned.getString("name");
name = new String(name.getBytes("ISO-8859-1"), "ISO-8859-7");
String surname=rsGrowersReturned.getString("surname");
surname = new String(surname.getBytes("ISO-8859-1"), "ISO-8859-7");
String partnership=rsGrowersReturned.getString("partnership");
partnership = new String(partnership.getBytes("ISO-8859-1"), "ISO-8859-7");
out.println("<tr><td>"+name+" "+surname+"</td>");
out.println("<td>"+partnership+"</td></tr>");
}//end of neaced if
}//end of second while
}//end of first while
out.println("</table>");
}//end of if
我可以看到确实出现了问题,因为在到达第二个之前,它会按预期打印第一个区域,然后是异常!!!
我尝试了直接对mysql服务器的sql查询,它可以工作,我只是找不到问题!每一个答案都将不胜感激,谢谢。