Sqlupdate does not change data in the database

Asked

Viewed 170 times

0

Note: Several people could not solve this question and marked my question as erroneously duplicated because of an answer in a similar question but the answer does not help me at all.

I am developing software for a video rental company with Pattern MVC (Model-view-controller) design and the problem of not changing people’s attributes is occurring. When I change by clicking on my save button to save my changes displays the message "changed successfully" but does not really change!

Video person class including save and change buttons, layer view:

 public VideoPessoa() {
            initComponents();

            new Conexao();
            pessoaController = new PessoaController();
            pessoa = new Pessoa();
            this.carregarPessoas();
             this.novaPessoa();
            this.habilitarCampos();

        }

    public boolean alterarPessoa() {
            pessoa.setCodigo( Integer.parseInt(this.txtCodigo.getText()));
            pessoa.setNome(this.txtNome.getText());
            pessoa.setEndereco(this.txtEndereco.getText());
            pessoa.setBairro(this.txtBairro.getText());
            pessoa.setCPF(this.txtCPF.getText());
            pessoa.setSexo(this.txtSexo.getText());
            pessoa.setUf(this.txtUF.getText());
            pessoa.setCelular(this.txtCelular.getText());
            pessoa.setTelefone(this.txtTelefone.getText());
            pessoa.setCidade(this.txtCidade.getText());

            if (pessoaController.alterar(pessoa)) {

                JOptionPane.showMessageDialog(this, "Registro alterado com sucesso!");
                 this.desabilitarCampos();
                this.carregarPessoas();
            } else {

                JOptionPane.showMessageDialog(this, "Erro ao alterar os dados!", "ERRO", JOptionPane.ERROR_MESSAGE);

            }

            return true;

        }

private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:

      if (!alterarPessoa){
              salvarPessoa();
          } else {
              alterarPessoa();
          }

    }                                         

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
       habilitarCampos();
     recuperarPessoas();
     alterarPessoa = true;

    }                     

Personal Classcontroller:

public class PessoaController {

    private final PessoaDAO pessoaDAO;

    public PessoaController() {
        pessoaDAO = new PessoaDAO();

    }

 public boolean alterar( Pessoa pessoa ) {
        boolean retorno;

        retorno = pessoaDAO.alterar(pessoa);

        System.out.println("Pessoa: "+pessoa); 

        return retorno;
    }

Personal class, including the method of changing people:

public class PessoaDAO {

    private Connection con;

    private final String SQLSELECT = " SELECT  codigo, nome, endereco, bairro, sexo, telefone, celular, CPF,  uf, cidade FROM PESSOA";

    private final String SQLUPDATE = " UPDATE pessoa"
            + " SET nome = ?, "
            + " endereco = ?, "
            + " bairro   = ?, "
            + " sexo     = ?, "
            + " telefone = ?, "
            + " celular  = ?, "
            + " CPF      = ?, "
            + " uf       =?, "
            + " cidade   =? "
            + " WHERE codigo = ?";

    private PreparedStatement sqlSelect, sqlUpdate;

    public PessoaDAO() {

        con = Conexao.getConnection();
        try {
            sqlSelect = con.prepareStatement(SQLSELECT);
            sqlUpdate = con.prepareStatement(SQLUPDATE);
        } catch (SQLException ex) {
            Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public Pessoa getPessoaPeloCodigo(int codigo) {

        Pessoa pessoa = null;
 try (
            PreparedStatement ps = con.prepareStatement(SQLPESSOAPELOCODIGO)
        ) {
            ps.setInt(1, codigo);
            try (ResultSet rs = ps.executeQuery()) {
                if (!rs.next()) return null; // Não encontrou.
                // Instancia a nova pessoa.
                //Instancia o novo filme
                pessoa = new Pessoa();

                //Seta as informações no filme
                pessoa.setCodigo(rs.getInt("codigo"));
                pessoa.setNome(rs.getString("nome"));
                pessoa.setEndereco(rs.getString("endereco"));
                pessoa.setBairro(rs.getString("bairro"));
                pessoa.setSexo(rs.getString("sexo"));
                pessoa.setTelefone(rs.getString("telefone"));
                pessoa.setCelular(rs.getString("celular"));
                pessoa.setCPF(rs.getString("CPF"));

                pessoa.setUf(rs.getString("uf"));
                pessoa.setCidade(rs.getString("cidade"));

            }
        } catch (SQLException ex) {
            Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return pessoa;
    }

public boolean alterar(Pessoa pessoa) {
        boolean retorno = false;
        try {
            sqlUpdate.setInt(1, pessoa.getCodigo());
            sqlUpdate.setString(2,pessoa.getNome());
            sqlUpdate.setString(3, pessoa.getEndereco());
            sqlUpdate.setString(4, pessoa.getBairro());
            sqlUpdate.setString(5, pessoa.getSexo());
            sqlUpdate.setString(6, pessoa.getTelefone());
            sqlUpdate.setString(7, pessoa.getCelular());
            sqlUpdate.setString(8, pessoa.getCPF());
            sqlUpdate.setString(9, pessoa.getUf());
            sqlUpdate.setString(10, pessoa.getCidade());


            sqlUpdate.executeUpdate();

            retorno = true;

        } catch (SQLException ex) {
            Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return retorno;
    }
  • 5

    Did you check the autocommit of the seat if it is activated? , Related: Prepared statement does not work or how to enable in Workbench

  • @rray checked yes and is activated! These two links did not solve my question.

  • @rray I checked and was on yes and these two links of yours did not solve my problem!

  • In your change, change sqlUpdate.executeUpdate(); for : sqlUpdate.executeUpdate(SQLUPDATE);

  • Was a mistake : com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, endereco = ?, bairro = ?, sexo = ?, telefone = ?, celular = ?, C' at line 1

  • I’m trying to find the line but I can’t find any mistakes

  • Gives a sysout in SQLUPDATE and put the return here

  • sysout before the sqlupadte= PessoaPessoa{nome=ee, endereco=eee, bairro=eee, sexo=, telefone=4444, celular=44, CPF=6666, codigo=44, cidade=eee, uf=jj, pessoa=null

  • after the sysout: Pessoa: Pessoa{nome=ee, endereco=eee, bairro=eee, sexo=, telefone=4444, celular=44, CPF=6666, codigo=44, cidade=eee, uf=jj, pessoa=null}

Show 4 more comments

1 answer

0

It seems that the parameters passed are not in the right order to perform the update, see:

UPDATE pessoa SET
    nome = ?,    <--- 1
    endereco = ?,<--- 2
    bairro   = ?,<--- 3
    sexo     = ?,<--- 4
    telefone = ?,<--- 5
    celular  = ?,<--- 6
    CPF      = ?,<--- 7
    uf       = ?,<--- 8
    cidade   = ? <--- 9
WHERE codigo = ? <--- 10

Look at the Binds now, the codigo should be number 10 and not number 1, because the first question refers to the field nome

sqlUpdate.setInt(1, pessoa.getCodigo());
sqlUpdate.setString(2,pessoa.getNome());
sqlUpdate.setString(3, pessoa.getEndereco());
sqlUpdate.setString(4, pessoa.getBairro());
sqlUpdate.setString(5, pessoa.getSexo());
sqlUpdate.setString(6, pessoa.getTelefone());
sqlUpdate.setString(7, pessoa.getCelular());
sqlUpdate.setString(8, pessoa.getCPF());
sqlUpdate.setString(9, pessoa.getUf());
sqlUpdate.setString(10, pessoa.getCidade());

The final code should look like this:

sqlUpdate.setString(1,pessoa.getNome());
sqlUpdate.setString(2, pessoa.getEndereco());
sqlUpdate.setString(3, pessoa.getBairro());
sqlUpdate.setString(4, pessoa.getSexo());
sqlUpdate.setString(5, pessoa.getTelefone());
sqlUpdate.setString(6, pessoa.getCelular());
sqlUpdate.setString(7, pessoa.getCPF());
sqlUpdate.setString(8, pessoa.getUf());
sqlUpdate.setString(9, pessoa.getCidade());
sqlUpdate.setInt(10, pessoa.getCodigo());
int linhasAfetadas = sqlUpdate.executeUpdate(SQLUPDATE);

if(linhasAfetadas > 0){
   return true;
}else{
   return false;
} 
  • I did as you said and it didn’t work!

  • @Igorcontini, did you change all the clues? which error appeared?

  • The Internet dropped here. I put the final code and the sqlUpdate.executeUpdate(SQLUPDATE); was underlined with red line indicating error and displaying the message: unreachable statement!

  • @Igorcontini, see now, anything remove the if-lse to test.

  • I changed all indexes to 1 until 10 and the code got the index 10. Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, endereco = ?, bairro = ?, sexo = ?, telefone = ?, celular = ?, C' at line 1

  • removed the if and the Else and gave that same: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, endereco = ?, bairro = ?, sexo = ?, telefone = ?, celular = ?, C' at line

  • @Igorcontini has some stranger in ? of the name ... nome = ?, this is the part with problem ...

  • Even worse.. had already noticed this and now I launched a new question!

Show 3 more comments

Browser other questions tagged

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