简体   繁体   中英

How to handle if a sql query finds nothing? Using resultset in java

I have found a few answers to this question on this site, but haven't been able to apply it correctly. I'm trying to take a user's input for user name and password and check it against a database to see if its correct. Everything works fine unless the username entered is not in the database. In that case the query doesn't find any rows. I'm doing this with derby in netbeans. So I think I'm just having trouble detecting when the query is sent with an unknown username. Any Suggestions?

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "MyServlet", urlPatterns ={"/echo"})
public class LoginAction extends HttpServlet {
private ResultSet resultSet;
private Connection con;

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
    out.println("<!DOCTYPE html>");
    out.println("<html><head>");
    out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
    String userName = request.getParameter("username");
    String password = request.getParameter("password");
    if (userName.length()>0 & password.length()>0){
        try{
            String url = "jdbc:derby:c:/users/project/.netbeans-derby/";
            String db = "loginpass";
            String driver = "org.apache.derby.jdbc.EmbeddedDriver";
            String user = "user";
            String pass = "pass";
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url+db, user, pass);
            String statement = "SELECT PASSWORD FROM LOGINPASS WHERE LOGIN = '"+userName+"'";
            PreparedStatement prepStatement = con.prepareStatement(statement);
            resultSet = prepStatement.executeQuery();

            while (resultSet.next()){
               if (resultSet.getString("password").equals(password)){
                   out.println("Login attempt successful!");
                   out.println("<br><a href='index.jsp'>Back to Login Page</a>");
               } else {
                   out.println("Password incorrect");
                   out.println("<br><a href='index.jsp'>Back to Login Page</a>");
               }
            }
            con.close();
        }catch(Exception e){
            out.println("caught...");
            e.printStackTrace();
        }
     } else {
        out.println("Login attempt failed");
        out.println("<a href='index.jsp'>Back to Login Page</a>");
     }
     } finally {
        out.close();  
     }
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}

As you expect only one row, you may write:

if (resultSet.next()) {
    if (resultSet.getString("password").equals(password)){
        out.println("Login attempt successful!");
        out.println("<br><a href='index.jsp'>Back to Login Page</a>");
    } else {
        out.println("Password incorrect");
        out.println("<br><a href='index.jsp'>Back to Login Page</a>");
    }
} else {
    out.println("User doesn't exist");
    out.println("<br><a href='index.jsp'>Back to Login Page</a>");
}

And you'd better use parameters to avoid sql injections:

String statement = "SELECT PASSWORD FROM LOGINPASS WHERE LOGIN = ?";
PreparedStatement prepStatement = con.prepareStatement(statement);
prepStatement.setString(1, userName);
resultSet = prepStatement.executeQuery();

You can check that from the ResultSet object itself . ResultSet#isBeforeFirst() :

Retrieves whether the cursor is before the first row in this ResultSet object.

Note: Support for the isBeforeFirst method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY

Returns:

true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no rows.

if (!resultSet.isBeforeFirst()) {
  out.println("no rows fetched");
  out.println("User with this password not found");
  out.println("<br><a href='index.jsp'>Back to Login Page</a>");
}

在While(resultSet.next())之前,键入if(resultSet!= null)。如果查询没有结果,则resultSet将为null。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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