javamysqljdbcphpmyadminjavadb

Cant insert into intermediate table from code but when executing from phpmyadmin in MySQL it inserts it properly


I recently needed to add an intermediate table into my database. It is all in innoDB. I use Java on the software, i've never had issues excecuting SQL commands. After inserting the table and setting it up alongside with the code i realiced i could insert data into it from java. It always gave the same error

    Cannot add or update a child row: a foreign key constraint fails 
    (`jjeventoscorev3`.`event_category_link`, CONSTRAINT 
    `event_category_link_ibfk_1` FOREIGN KEY (`event_category_id`) 
    REFERENCES `event_category` (`event_category_id`))

I checked the query:

    insert into event_category_link (event_link_id, event_id, 
    event_category_id) values (NULL,118,1)

I then tried to execute it on phpmyadmin. id did it successfully under the same query. I dont really know how to debugg it. The code is the same as ive used for other intermediate tables and its nothing out of the extraordinary.

This is the code i used on a table succesfully on java:

 try{con = (Connection) DriverManager.getConnection("jdbc:mysql://"+home.credentials[0],home.credentials[1],home.credentials[2]);
            String query3 = " insert into client_event (client_id, event_id)"
            + " values (?, ?)";/*query para insertar en la tabla intermedia*/
            PreparedStatement preparedStmt3 = con.prepareStatement(query3);
            if(existing == false){/*si existe se manda el ids[0]*/
                preparedStmt3.setInt (1, ids[0]); //cliente
            }
            else{
                preparedStmt3.setInt (1, id_existing); /*se manda el id existente*/
            }
            preparedStmt3.setInt (2, ids[1]); //evento
            preparedStmt3.execute();
            con.close();
            JOptionPane.showMessageDialog(new JFrame(), "Evento añadido");
            pnlone1.continue_doc = true; /*se cambia el valor de continue_doc en el pnlone para poder generar el archivo*/
        }
        catch (Exception e){
            System.err.println("Got an exception! in 3");
            System.err.println(e.getMessage());
            continuar = false; /*se pasa a falso para no continuar con la operación*/
            System.out.println(e.getMessage());
            JOptionPane.showMessageDialog(new JFrame(), "Error: verificar datos");
        }

This is the code i use on the table I'm getting the error:

      if(continuar == true){
        System.out.println("Iniciando tabla de eventos conectados");
        try{con = (Connection) DriverManager.getConnection("jdbc:mysql://"+home.credentials[0],home.credentials[1],home.credentials[2]);
            String query4 = " insert into event_category_link (event_link_id, event_id, event_category_id)"
            + " values (NULL,"+ids[1]+","+eventlist.get(0)+")";/*query para insertar en la tabla intermedia*/

            //INSERT INTO `event_category_link` (`event_link_id`, `event_id`, `event_category_id`) VALUES (NULL, '105', '27');
            PreparedStatement preparedStmt4 = con.prepareStatement(query4);
            System.out.println(preparedStmt4);
            preparedStmt4.execute();
            con.close();
            JOptionPane.showMessageDialog(new JFrame(), "Relacion añadida");
        }catch (Exception e){
            System.err.println("Got an exception! in 4");
            System.err.println(e.getMessage());
            JOptionPane.showMessageDialog(new JFrame(), "Error: verificar datos");
        }

Here you can see how PhpMyAdmin executes it perfectly

enter image description here I would really appreciate your help. Thanks


Solution

  • The error is telling you that the event_category_id you are trying to insert does not exist in the moment you are trying to insert it. You should take this as a fact, and check your code how that can be the case. Maybe try to run a query directly before your query4 that checks if the value "eventlist.get(0)" is actually in the table. Then go backwards and check where that value comes from.

    There are several reasons why you may be able to execute it later in phpmyadmin (and they should not delude you from the fact that the value is really missing, but may help narrow down where to look):