检查空结果集

时间:2012-02-20 08:23:51

标签: java jsp

我正在建立一个检查空结果集的解决方案......这里是代码

     temp = rs1;
     boolean hasRows = temp.next();


     if (hasRows) {  
        while (rs1.next()) {
            String pid = rs1.getString("pid");
            System.out.println(pid);
            String pd = rs1.getString("description");
            double price = rs1.getDouble("price");%>
                    <br>
                    Product id : <%=pid %><br>
                    Description : <%=pd %><br>
                    Price : <%=price %>
      <%
                }
          }

似乎temp.next()会影响rs.next(),结果最终无法打印出来。为什么呢?

2 个答案:

答案 0 :(得分:1)

next()方法已经检查了您尝试的控件。如果结果集rs1包含元素,则将输入循环。 您似乎无法在任何地方使用temp。为什么?放弃它并完成工作,试试这个:

      boolean loopEntered = false;
      while (rs1.next())
      {
                loopEntered = true;
                String pid = rs1.getString("pid");
                System.out.println(pid);
                String pd = rs1.getString("description");
                double price = rs1.getDouble("price");

              %>
                 <br>
                 Product id : <%=pid %><br>
                 Description : <%=pd %><br>
                 Price : <%=price %>
              <%
      }

      if(!loopEntered)
      // print your error messages.

答案 1 :(得分:1)

我通常喜欢这个

if(rs.next()){
    do {                
        //print product details
    } while (rs.next());
}else{
    //print product not found
}