Improving Login Logic - JDBC - Javaweb

Asked

Viewed 166 times

0

I am developing the method of login of an application, but I’ve been realizing that the query I’m running to check if a user is registered in the system and if his password matches the database data is too slow. I am using the Select * FROM cadastrados, that ends up checking the entire database leaving the application "slower".

Can anyone suggest me a query better for the login method or a better logic than the one I’m using? Below, follow the code:

//Login Usuário
public static Usuario Login(String login, String senha){
    Connection conn = Banco.getConexao();
    Usuario user = new Usuario();
    Statement stmt = null;
    ResultSet rs = null;
    String sql = "Select * FROM cadastrados";

    try{
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);

        while(rs.next()){
            //Lógica do Login
            if(rs.getString(2).equals(login) && rs.getString(3).equals(senha)){
                user.setCpf(rs.getString(1));
                user.setLogin(rs.getString(2));
                user.setSenha(rs.getString(3));
                user.setNome(rs.getString(4));
                user.setSobrenome(rs.getString(5));
                user.setEndereco(rs.getString(6));
                user.setEmail(rs.getString(7));
                user.setLogado(true);
                break;
            }
        }
    }
    catch(SQLException ex){
        Logger.getLogger(UsuarioDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally{
        Banco.closeConexao(conn, rs, null, stmt);
    }
    return user;
}

1 answer

1


Good afternoon!

You could use the clause where in your sql, passing the user and password, let db do the search and deliver you the correct user, improving the security and readability of your code, rather than get all accounts and do the check on your own system.

Good practice

The recommended is that you create a Factory of connections to the bank, a Data Access Object to manipulate the access and acquisition of information to the bank and, finally, one that allows you to validate whether the information is valid or not. Search for Database Database Database and JDBC

  • Thank you very much, I did a search in the "Where" that you suggested and really got much better.

Browser other questions tagged

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