Java/SQL Login and Password Validation Issue

Asked

Viewed 698 times

1

I have a problem in the validation of Login and Password, the code is only taken the values of the first line of the database, but when I try to put the values of the other lines it gives error, I appreciate if someone 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(); }

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, you would not need to go through all the rows of your registration table (It doesn’t make much sense since there shouldn’t be 2 identical login/password combinations). Also, these "?" of Prepared protect against SQL Injection.

Note: Avoid storing passwords in Plain text in the bank, only save encrypted passwords.

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 command

 break;

causing the code to exit the while(rs.next()) and ending the execution of your application. IE, even if you have more than one result will always end in the first line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.