Java / SQL Login and Password Validation Problem

1

I have a validation problem with Login and Password, the code is only taken from the values of the first row of the database, but when I try to put the values of the other lines it gives error, thank you if anyone can help me. Follow the code below.

try{
    Connection con = BancoSQL.getConexao();
    String sql = "select Login, Senha from cadfuncionario";
    PreparedStatement ps = con.prepareStatement(sql);
    ResultSet rs = ps.executeQuery(sql);

    String login = jUsuario.getText();
    String senha = jSenha.getText();

    while(rs.next()){

        if(rs.getString("Login").equalsIgnoreCase(login) 
        && rs.getString("Senha").equalsIgnoreCase(senha)){

            this.dispose();
            MenuP m = new MenuP();
            m.setVisible(true);
            JOptionPane.showMessageDialog(null,"Bem vindo");
            break;

        }else{

            JOptionPane.showMessageDialog(null,"Usuario ou Senha Incorretos!");
            jUsuario.setText("");
            jSenha.setText("");
        }

    }
    }catch(Exception e){ e.printStackTrace(); }
    
asked by anonymous 17.10.2017 / 03:16

2 answers

1

I suggest you take advantage of PreparedStatement and do the following:

PreparedStatement p = con.prepareStatement("select idusuario from usuario where login = ? and senha = ?");
p.setString(1, login);
p.setString(2, senha);
ResultSet r = p.executeQuery();

if(r.next()){
    // Se r.next() for verdade existe uma combinação login/senha               
}

// Nunca esqueça de fechar os fluxos, eles podem acumular.
r.close();
p.close();
con.close();

So the database will return only one line, it would not have to go through all the rows of your registration table (It does not make much sense since there should not be 2 equal login / password combinations). In addition, these "?" of the prepared protect against SQL injection.

Note: Avoid saving plaintext passwords to the bank, save only encrypted passwords.

    
17.10.2017 / 22:20
0

Hello, it seems:

if(rs.getString("Login").equalsIgnoreCase(login) 
 && rs.getString("Senha").equalsIgnoreCase(senha)){

When entering this code block the first time, you call the

 break;

Make the code exit while(rs.next()) and finish executing your application. That is, even if it has more than one result, it will always end up in the first row.

    
17.10.2017 / 21:34