Error while deleting data in Mysql by Java

Asked

Viewed 201 times

2

In the database I have three tables, where one of them keeps the foreign keys. Error made: Error: com.mysql.jdbc.exceptions.jdbc4.Mysqlintegrityconstraintviolationexception: Cannot delete or update a Parent Row: a Foreign key Constraint fails (db_teste.tbl_Relacao, CONSTRAINT tbl_Relacao_ibfk_1 FOREIGN KEY (primeira_pessoa) REFERENCES pessoas (id_pessoas))

Class relatives:

public class Parentes {
private int id_parentes;
private int nivel;
private String parentesco;
//getters e setters

Personal class:

public class Pessoa {
private int id_pessoa;
private String sexo;
private String nome;
private String usuario;
private String senha;
//getters e setters

Relationship class:

public class Relacao {
private int id_relacao;
private int primeira_pessoa;
private int segunda_pessoa;
private int tipo_relacao;
private Parentes parente;
private Pessoa pessoa1;
private Pessoa pessoa2;
//getters e setters

Delete of parentsDAO:

public boolean delete(Parentes parentes){
    String sql = "DELETE FROM tbl_parentes WHERE id_parentes = ?";
    PreparedStatement stmt = null;

    try {
        stmt = con.prepareStatement(sql);
        stmt.setInt(1, parentes.getId_parentes());
        stmt.executeUpdate();

        return true;
    } catch (SQLException ex) {
        System.err.println("ERROR: "+ex);
        return false;
    }
    finally{
        ConnectionFactory.closeConnection(con, (com.mysql.jdbc.PreparedStatement) stmt);
    }
}

Delete of person:

    public boolean update(Pessoa pessoa){
    String sql = "UPDATE pessoas SET nome = ?, sexo = ? WHERE id_pessoas = ?";

    PreparedStatement stmt = null;

    try {
        stmt = (PreparedStatement) con.prepareStatement(sql);
        stmt.setString(1, pessoa.getNome());
        stmt.setString(2, pessoa.getSexo());
        stmt.setInt(3, pessoa.getId_pessoa());
        stmt.executeUpdate();

        return true;

    } catch (SQLException ex) {
        System.err.println("Erro: " + ex);
        return false;
    }finally{
        ConnectionFactory.closeConnection(con, stmt);
    }
}    

Delete from the relacDAO:

    public boolean delete(Relacao relacao){
    String sql = "DELETE FROM tbl_Relacao WHERE id_relacao = ?";
    java.sql.PreparedStatement stmt = null;

    try {
        stmt = con.prepareStatement(sql);
        stmt.setInt(1, relacao.getId_relacao());
        stmt.executeUpdate();

        return true;
    } catch (SQLException ex) {
        System.err.println("ERROR: "+ex);
        return false;
    }
    finally{
        ConnectionFactory.closeConnection(con, (com.mysql.jdbc.PreparedStatement) stmt);
    }
}

I’m using Junit to do the test, follows below the code:

   public void deleteDAO() {
    Pessoa pessoa = new Pessoa();
    PessoaDAO pessoaDAO = new PessoaDAO();

    Relacao relacionamento = new Relacao();
    RelacaoDAO relacionamentoDAO = new RelacaoDAO();

    Parentes parentes = new Parentes();
    ParentesDAO parentesDAO = new ParentesDAO();

    //pessoa.setId_pessoa(3);

    //Qualquer valor vai apresentar o mesmo erro
    pessoa.setId_pessoa(c.getId_pessoa());

    parentes.setId_parentes(c.getId_parentes());

    relacionamento.setId_relacao(c.getId_relacao());


    if(pessoaDAO.delete(pessoa) && relacionamentoDAO.delete(relacionamento) && parentesDAO.delete(parentes)){
        System.out.println("Removido com sucesso!");
    }
    else{
        fail("Erro ao deletar");
    }
}

The problem is that when I try to erase the data an error appears in the table containing the foreign keys, I would like to know what I am doing wrong.

Note: I am beginner.

  • First try to remove only the AOP person and see if the error presents, so it seems to me you are trying to remove a record that has reference in another table. As Relationship has reference of person and relatives it would be right to remove the relationship first after the person and relatives. The Relationship table cannot have orphaned records.

  • Go to phpmyadmin or another bank manager you are using, search "tbl_Relacao" and search for the Constant "tbl_Relacao_ibfk_1" and put the integrity to CASCATA, so that when a delete or update is performed the database distributes the cascade in the relationships

1 answer

1

As you’re starting out, let’s go in pieces as Jack would say...

1. Do not plural entity name:

Ex: Relatives >> Relative

2. Do not put attribute name in java with underline (_):

Ex: id_person >> idPessoa

3. Constraint error when trying to exclude

Try changing the deletion order to:

if(relacionamentoDAO.delete(relacionamento) && pessoaDAO.delete(pessoa) && parentesDAO.delete(parentes)){
    System.out.println("Removido com sucesso!");
}

Another solution would be to work with Scade in the bank.

Doubt: The Relatives table relates to which table? In your class this is not clear.

  • Thank you so much for the karanalpe tips, the relatives table is relating to the relationship table.

  • It worked to change the exclusion order?

  • It worked, but before that it was presenting the following error:com.mysql.jdbc.exceptions.jdbc4.Mysqlnontransientconnectionexception: No Operations allowed after Connection closed. for testing purposes I deleted all of the following points: Finally{ Connectionfactory.closeConnection(con, (com.mysql.jdbc.Preparedstatement) stmt); } And the code worked normally, but now my doubt is this, I’m doing right in erasing?

  • Right and wrong is relative. An easier option would be to work with Bank Database.

  • Blz Karanalpe, thanks for the tips.

Browser other questions tagged

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