Error trying to insert data into Mysql database [duplicate]

1

I'm trying to insert data from a promotion into the MySQL database via a REST Web Service in Java, but when trying to insert me returns the following error:

Grave:   ERRO ao Inserir Promocao - com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails ('mercado_db'.'promocao', CONSTRAINT 'id_produto_fk' FOREIGN KEY ('id_produto_fk') REFERENCES 'produto' ('idproduto'))

Add method

public void adiciona(Promocao promocao) {

        id_conexao = N.Conectar();

        String sql = "insert into promocao (descricao, data_inicio, data_termino, id_produto_fk) values (?,?,?,?)";

        try {

            //PreparedStatement para inserção
            stmt = id_conexao.prepareStatement(sql);

            //setar valores
            stmt.setString(1, promocao.getDescricao());
            stmt.setString(2, promocao.getData_inicio());
            stmt.setString(3, promocao.getData_termino());
            stmt.setInt(4, promocao.getIdprodutoFk());

            //executa
            stmt.execute();
            System.out.println("Promoção Salva");

        } catch (SQLException e) {
            System.err.println("ERRO ao Inserir Promocao - " + e);
        } finally {
            N.Desconectar();
        }

    }

POST method to enter via Web Service

@POST 
@Consumes(MediaType.APPLICATION_JSON)
@Path("inserirPromocao")
public void inserir(String content) {

    Gson g = new Gson();
    Promocao P = (Promocao) g.fromJson(content, Promocao.class);

    PromocaoOp promo = new PromocaoOp();
    promo.adiciona(P);
}
    
asked by anonymous 10.11.2017 / 03:36

1 answer

0

according to the same error exposed at link , the value of the promocao.id_produto_fk column that you are inserting does not exist in the produto table, there it violates the referential integrity restriction ...

That is, this promocao table depends on the produto table.

    
10.11.2017 / 04:20