Java - How to validate user group in SQL and Save result?

2

Good morning,

I have the following code in Java Desktop. I wanted to know how I can capture that user's group and save it to a variable. Since when it returns the value and stores in the variable "rs" does not contain information understood for the developer. It needs the user's group name to open a jframe according to its group.

public class UsuarioD {

public static Boolean doLogin(model.UsuarioM usuario) {

    // Variáveis
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = "select * from usuario where nome=? and senha=?";

    try {

        // Validar
        ps = ConectarDB.getConexao().prepareStatement(sql);
        ps.setString(1, usuario.getNome());
        ps.setString(2, usuario.getSenha());
        rs = ps.executeQuery();

        // Validar
        if(rs.next()) {
            return true;
        } else {
            return false;
        }            

    } catch (SQLException ex) {
        ex.printStackTrace();
        return false;
    }

}

}

    
asked by anonymous 30.11.2015 / 16:22

1 answer

3

One of the alternatives to solve this problem is the following: instead of returning true or false, return an object of type User if login is successful. So you can populate this user object with all the necessary information.

Note that if the login does not succeed due to the user and password passed as parameter, then an exception is raised.

See below:

public static Usuario doLogin(String usuario, String senha) throws SQLException {
    // Variáveis
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = "select * from usuario where nome=? and senha=?";
    Usuario usuario = new Usuario();

    // Validar
    ps = ConectarDB.getConexao().prepareStatement(sql);
    ps.setString(1, usuario);
    ps.setString(2, senha);
    rs = ps.executeQuery();

    // Validar
    if(rs.next()) {
        usuario.setNome(rs.getString("nome"));
        usuario.setGrupo(rs.getString("grupo"));    
    } else {
        throw new RuntimeException("Usuario ou senha incorretos, favor verificar.");
    }            

    return usuario;
}
    
30.11.2015 / 16:40