Java - SQL Error Updating All Users

Asked

Viewed 49 times

3

Good morning,

I’m having the following problem my updateOur SQL is updating all how I do so that it just updates the User who accessed?

public class Acessar {

public static Connection con = dao.ConectarDB.getConexao();

public static String doLogin(model.Acessar usuario) {

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

    try {

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

        // Validar Grupo
        ps = null;
        sql = null;
        rs = null;
        sql = "select * from usuario where grupo=?";

        try {
            ps = con.prepareStatement(sql); 
            ps.setString(1, "Suporte");
            rs = ps.executeQuery();
            grupo = rs;

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

        // Resultado da Autenticação
        if(autenticacao.next()) {

            // Autenticado!

            // Resultado do Grupo
            if(grupo.next()) {

            } else {
                return null;
            }

            return "lider";

        } else {
            return "erro";
        }            

    } catch (SQLException ex) {
        ex.printStackTrace();
        return "erro";
    }

}

// (Corrigir) Está atualizando todos os Usuários!
public void atualizarUsuario(model.Acessar acesso) {

    // Variáveis
    PreparedStatement ps = null;
    String sql = "update usuario set acesso=?";

    // Inserção
    try {
        ps = con.prepareStatement(sql);
        ps.setDate(1, new Date(acesso.getAcesso().getTime()));
        ps.executeUpdate();

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

}

1 answer

5


In your SQL string you need to specify which user you want to update using the clause Where for this. Also, you need to pass this user as parameter in your method upgrade.

Something like that:

public void atualizarUsuario(model.Acessar acesso, Usuario usuario) {

    // Variáveis
    PreparedStatement ps = null;
    String sql = "update usuario set acesso=? where nome=?";

    // Inserção
    try {
        ps = con.prepareStatement(sql);
        ps.setDate(1, new Date(acesso.getAcesso().getTime()));
        ps.setString(2, usuario.getNome());
        ps.executeUpdate();

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

I don’t know your model, so I’m updating the user based on the name (just like you do the login), but this obviously can imply problems, when two users have the same name.

Browser other questions tagged

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