Error trying to insert data into Mysql database

Asked

Viewed 114 times

1

I’m trying to input a promotion into the database Mysql through a Web Service REST 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`))

Method add

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();
        }

    }

Method POST to insert 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);
}

1 answer

0

Browser other questions tagged

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