如何在servlet中使用多个if条件的多个预处理语句?

时间:2016-10-31 14:55:43

标签: java-ee

PreparedStatement ps=Database.con.prepareStatement("select * from account where accountno='"+accno+"' and password= '" +pass+ "'");
        ResultSet rs=ps.executeQuery();
        PreparedStatement ps1=Database.con.prepareStatement("select * from apass where accountno='"+accno+"' and OTP= '" +pass+ "'");
        ResultSet rs1=ps1.executeQuery();
        PreparedStatement ps2=Database.con.prepareStatement("select * from account where accountno='"+accno+"'");
        ResultSet rs2=ps2.executeQuery();
        if(rs.next())
        {
        session.setMaxInactiveInterval(300);
        session.setAttribute("name",rs.getString("full_name"));
        session.setAttribute("mbno",rs.getString("mobileno"));
        session.setAttribute("pass",rs.getString("password"));
        session.setAttribute("accno",rs.getString("accountno"));
        response.sendRedirect("PBank.jsp");
        }
        if(rs2.next())
        {
            String pas=rs2.getString(6);
            if(pas==null)
            {
                response.sendRedirect("login.jsp?messageInactive=You have deactivated your account, kindly activate your account to login!!");
            }
        }
        if(rs1.next())
        {
           session.setAttribute("accno",rs1.getString("accountno"));
           session.setAttribute("pass",rs1.getString("OTP"));
           response.sendRedirect("reset.jsp");
        }
       if(pass.equals(passs) && accno.equals(acc))
       {
            session.setAttribute("passs",passs);
            session.setAttribute("acc",acc);
            response.sendRedirect("admin.jsp");
        }
       else
       {
           response.sendRedirect("login.jsp?message=Incorrect Account Number or Password!!!");
       }

1 个答案:

答案 0 :(得分:0)

使用如下构造:

    try (PreparedStatement ps = Database.con.prepareStatement(
                "select full_name, mobileno, password, accountno "
                + "from account where accountno=? and password=?")) {
        ps.setInt(1, accno);
        ps.setString(2, pass);
        try (ResultSet rs = ps.executeQuery()) {
            if (rs.next()) {
                session.setMaxInactiveInterval(300);
                session.setAttribute("name",rs.getString("full_name")); // Or (1)
                session.setAttribute("mbno",rs.getString("mobileno"));// Or (2)
                session.setAttribute("pass",rs.getString("password")); // pass
                session.setAttribute("accno",rs.getString("accountno")); // accno
                response.sendRedirect("PBank.jsp");
                return;
            }
        }
    }
  • PreparedStatement 占位符? 会阻止SQL injection并转义'等。你可以使用类型。
  • 尝试使用资源自动close语句和结果集,即使在异常和返回时也是如此。
  • 在SQL select *中这里没问题,但是对于列表,最好选择有限数量的列,这样会更快并且使用更少的内存。
  • 密码处理:最好不要将其存储为属性。还要搜索一下主题(SQL PASSWORD,java)。
  • 每个声明都是一个接一个,尽管我认为这些例子都是人为的。通过这种方式,它们可以在最短的时间内保持打开状态减少数据库端的句柄数。