Random SQL Error

Discussion in 'Programming' started by Gerolmed, Aug 7, 2018.

  1. Im executing a Batch, but when executing with same values it sometimes works and sometimes throws the following error:
    Code (Text):
    java.sql.BatchUpdateException: Cannot add or update a child row: a
    foreign key constraint fails (`findlunch`.`restaurant`, CONSTRAINT
    `fk_restaurant_restaurant_type1` FOREIGN KEY (`restaurant_type_id`)
    REFERENCES `restaurant_type` (`id`))
        at
    org.mariadb.jdbc.MySQLStatement.executeBatch(MySQLStatement.java:1274)
        at testapp.sql.SqlDatabase.addRestaurants(SqlDatabase.java:187)
        at testapp.Main.main(Main.java:35)
    Caused by: java.sql.SQLIntegrityConstraintViolationException: Cannot add
    or update a child row: a foreign key constraint fails
    (`findlunch`.`restaurant`, CONSTRAINT `fk_restaurant_restaurant_type1`
    FOREIGN KEY (`restaurant_type_id`) REFERENCES `restaurant_type` (`id`))
        at
    org.mariadb.jdbc.internal.SQLExceptionMapper.get(SQLExceptionMapper.java:132)
        at
    org.mariadb.jdbc.internal.SQLExceptionMapper.throwException(SQLExceptionMapper.java:106)
        at
    org.mariadb.jdbc.MySQLStatement.executeQueryEpilog(MySQLStatement.java:252)
        at org.mariadb.jdbc.MySQLStatement.execute(MySQLStatement.java:278)
        at
    org.mariadb.jdbc.MySQLStatement.executeBatch(MySQLStatement.java:1258)
        ... 2 more
    Caused by: org.mariadb.jdbc.internal.common.QueryException: Cannot add
    or update a child row: a foreign key constraint fails
    (`findlunch`.`restaurant`, CONSTRAINT `fk_restaurant_restaurant_type1`
    FOREIGN KEY (`restaurant_type_id`) REFERENCES `restaurant_type` (`id`))
        at
    org.mariadb.jdbc.internal.mysql.MySQLProtocol.getResult(MySQLProtocol.java:969)
        at
    org.mariadb.jdbc.internal.mysql.MySQLProtocol.executeQuery(MySQLProtocol.java:1021)
        at
    org.mariadb.jdbc.internal.mysql.MySQLProtocol.executeQuery(MySQLProtocol.java:1003)
        at org.mariadb.jdbc.MySQLStatement.execute(MySQLStatement.java:271)
        ... 3 more
    I don't know whats wrong there and showing Code is senseless as it does work(but not always)
     
  2. As the error says, the foreign key check fails. This can probably mean one of 3 things:
    • The provided foreign key doesn't exist in the relation
    • The provided foreign key is null
    • The provided foreign key value is a duplicate
    Double check if you're not generating any duplicate ID's. Also double check if the primary key restaurant_type_id is set. Also check if you're not someone executing the queries twice (that happened to me last time, I registered an event handler twice by accident).
     
    • Agree Agree x 1