Improving Login Logic - JDBC - JavaWeb

0

I'm developing the login method of an application, but I've been noticing that the query I'm running to check if a user is registered to the system and if his password hits the bank's data is very slow. I'm using Select * FROM cadastrados , which ends up checking the whole database leaving the application "slow".

Can someone suggest me a query better for the login method or a better logic than the one I'm using? Below is 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;
}
    
asked by anonymous 02.12.2016 / 03:27

1 answer

1

Good afternoon!

You could use the where clause in your sql, pass the user and password, let db do the search and deliver the correct user, improving the security and readability of your code, instead of getting all the accounts and do the verification on your own system.

Good practices

It is recommended that you create a Database Connections Factory, a Data access object to manipulate the access and acquisition of information to the database, and finally one that allows you to validate whether the information is valid or not. Search for pattern of Databases and JDBC

    
02.12.2016 / 18:56