简体   繁体   English

如果在数据库中找不到用户数据,如何中断while循环

[英]how to break the while loop if the user data is not found in the database

I'm trying to make a application in which put some data in database and from the html page i want to search the data in database.我正在尝试制作一个应用程序,其中将一些数据放入数据库中,并从 html 页面中搜索数据库中的数据。 I'm using the servlet api, i successfully retrieve the data from the database, but for the data which is not present in the database i required to get the "data not found" message on the same html page.我正在使用 servlet api,我成功地从数据库中检索了数据,但是对于数据库中不存在的数据,我需要在同一 html 页面上获取“未找到数据”消息。 I write the condition for checking the data for database, but for the data not present in the database i get the error message of "null pointer exception" and the while loop doesn't break by itself after checking whole data in database.我写了检查数据库数据的条件,但是对于数据库中不存在的数据,我收到“空指针异常”的错误消息,并且在检查数据库中的整个数据后,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);        
}
}

You should assign the value to a variable then check if is not null first:您应该将值分配给一个变量,然后首先检查是否不为空:

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

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

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