【问题标题】:how to break the while loop if the user data is not found in the database如果在数据库中找不到用户数据,如何打破while循环
【发布时间】:2017-01-10 12:32:35
【问题描述】:

我正在尝试制作一个应用程序,将一些数据放入数据库中,并从 html 页面中搜索数据库中的数据。我正在使用 servlet api,我成功地从数据库中检索数据,但是对于数据库中不存在的数据,我需要在同一个 html 页面上获取“找不到数据”消息。我写了检查数据库数据的条件,但是对于数据库中不存在的数据,我收到“空指针异常”的错误消息,并且在检查数据库中的整个数据后,while循环不会自行中断。

// this while loop doesn't terminate by itself if the data is not found in the database.

int flag=0;
while(rs.next()){
    if (rs.getString(1).equals(fname)&&(rs.getString(2).equals(lname)))
    {
        String message=rs.getString(4);
        out.print("<h2 align='center'>"+message+"</h2>");
        RequestDispatcher disp = req.getRequestDispatcher("/index.html");
        disp.include(req,res);
        flag=1;
    }
}

if(flag==0)
{
    out.print("<h1>"+"data not found"+"</h1>");
    RequestDispatcher disp = req.getRequestDispatcher("/index.html");
    disp.include(req,res);
    System.out.println(flag);        
}
}

【问题讨论】:

  • 使用break 声明?
  • 如@Mena所说,在System.out.println(flag);之后添加break;
  • 你不需要打破循环;如果没有数据,那么rs.next() 永远不会是真的。如果代码中额外的} 是方法的结尾,那么您可能只想在第一个disp.include 调用之后返回,从而使标志变得多余。如果你得到一个 NPE,那么你在循环中比较的两列值之一可能实际上是空的,对于其中一行(可能有很多)? NPE 是针对哪条线路报告的? (另外 - 为什么不在查询中添加过滤器以查找指定的 fname/lname,而不是获取大量数据然后检查 Java?)
  • 同意@Alex,正确设置where子句,这样你就可以找到匹配first_name和last_name的记录,如果没有匹配的数据,则根本不会进入while循环。跨度>

标签: java html servlets jdbc oracle-sqldeveloper


【解决方案1】:

你应该先将值赋给一个变量,然后检查它是否不为空:

String tmp = rs.getString(1);
        if (tmp != null && tmp.equals(fname) && tmp.equals(lname)) {...}

【讨论】:

    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多