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

Asked

Viewed 78 times

2

Good morning,

I have the following code in Java Desktop. I wanted to know how I can capture this user’s group and save it into a variable. Since when it returns the value and stores in the variable "rs" does not contain information understood for the developer. You need the name of the user group to open a jFrame according to their 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;
    }

}

}

  • This will also depend on how you store groups. It is a String field in the table usuario or in a different table?

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. Thus, you can popular this user object with all 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;
}

Browser other questions tagged

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