简体   繁体   中英

Mysql Cannot add or update a child row: a foreign key constraint fails

Mysql tables mysqltables

This is my query to insert data to the database.

public void voegSpelerToe(Speler speler, String spelNaam)
{

    PreparedStatement invoerSpeler;
    Speler huidigeSpeler = null;
    try
    {

        Connection connection = PersistentieController.getInstance().getConnection();

        invoerSpeler = connection.prepareStatement("INSERT INTO Speler " + "(naam, kleur, sector, aantalZilverstukken, Spel_naam) " + "VALUES ( ?, ?,?, ?, ?)");


        invoerSpeler.setString(1, speler.getNaam());
        invoerSpeler.setString(2, speler.getKleur());
       invoerSpeler.setInt(3, speler.getSector().getCode());
        invoerSpeler.setInt(4,speler.getKrediet());
        invoerSpeler.setString(5, spelNaam);




        invoerSpeler.executeUpdate();


    } catch (SQLException sqlException)
    {
        sqlException.printStackTrace();
    } finally
    {
      //  PersistentieController.getInstance().closeConnection();
    }


}

Everything has a value so I don't have nullexeptions.

But when I want to save the data I get this error:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`projecteng62`.`speler`, CONSTRAINT `fk_Speler_Spel1` FOREIGN KEY (`Spel_naam`) REFERENCES `spel` (`naam`) ON DELETE CASCADE ON UPDATE CASCADE)

How can I insert data in the foreign key. First It save data to the table Spel and then i need to save data in the table speler but I get a problem wit the foreign Key.

Like table spel:

  1. naam: Game12
  2. aantalTeSPelenRondes: 2

table Speler:

  1. naam : player1
  2. kleur : green
  3. sector : 2
  4. aantalZilverStukken : 10

  5. Spel_Naam: game12 Spel_naam must be the same as naam in table Spel

It is telling you that it is expecting the contents of Spel_Naam to exist in some row in spels naam attribute, but it does not exist.

To fully figure out the issue I would also need to see where you are inserting into spel.

But in the example input you provided

naam: Game12

Spel_Naam: game12

there is an issue because one is capitalized and the other is not. If this is actually how the data is set up, then that is likely your problem. But it seems you have the right idea, you need to insert into naam first, then into Spel_Naam.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM