简体   繁体   中英

Servlet login with prepared statement

I try to find out, where is Error in my Code below:

public void service(HttpServletRequest request, HttpServletResponse response){
        try{
            user1 = request.getParameter("nameLog");
            pass1 = request.getParameter("passLog");
            String userid = null;
            String passdb = null;
            String query = "select user, pass from login where `user` = ? and `pass`=?";

            PreparedStatement pst = conn.prepareStatement(query);
            ResultSet rs = pst.executeQuery();
            pst.setString(1, user1);
            pst.setString(2, pass1);

            while(rs.next()){
                userid = rs.getString("user1");
                passdb = rs.getString("pass1");

                pst.executeQuery();
            }
            if(userid.equals(user1)&& passdb.equals(pass1)){
                response.sendRedirect("/WebContent/login/Main.html");

            }


        }catch(Exception ex){
        ex.printStackTrace();
        }
    }

I try to log in to my application (db Column names are user and pass ) but i get an Error:

java.sql.SQLException: No value specified for parameter 1

in this row

ResultSet rs = pst.executeQuery();

How can I get rid of this error and log into my Page?

Thanks

Order matters! You need to pass the parameters before you call executeQuery , like so:

PreparedStatement pst = conn.prepareStatement(query);            
pst.setString(1, user1);
pst.setString(2, pass1);            
ResultSet rs = pst.executeQuery();

You are executing the query before setting the values. It should be:

PreparedStatement pst = conn.prepareStatement(query);
pst.setString(1, user1);
pst.setString(2, pass1);

ResultSet rs = pst.executeQuery();

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