有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

基于其他表自动增量的java数据库外键填充

我有两张桌子。第一个表有一个自动递增id。 一个“patienten”有多个“gebit”。idPatient是两个表中的外键

病人十:

enter image description here

格比特:

enter image description here

现在我想填写“gebit”表,但我不断地出错

我的代码:

public void addTandenToDatabase(int fdi, String voorstelling, String toestand) {
    String insertSql = "insert into gebit(fdi, voorstelling, toestand) values (:fdiVal, :voorstellingVal, :toestandVal)";
    try (Connection con = sql2o.open()) {
        con.setRollbackOnException(false);
        con.createQuery(insertSql)
                .addParameter("fdiVal", fdi)
                .addParameter("voorstellingVal", voorstelling)
                .addParameter("toestandVal", toestand)
                .executeUpdate();
    }
}

我得到的错误是:

enter image description here

我尝试了第二种方法,在gebit中将值添加到idPatient:

public void addTandenToDatabase(int fdi, String voorstelling, String toestand) {
    String insertSql = "insert into gebit(idPatient, fdi, voorstelling, toestand) values (:idVal, :fdiVal, :voorstellingVal, :toestandVal)";
    try (Connection con = sql2o.open()) {
        con.setRollbackOnException(false);
        con.createQuery(insertSql)
                .addParameter("fdiVal", fdi)
                .addParameter("idVal", fdi)
                .addParameter("voorstellingVal", voorstelling)
                .addParameter("toestandVal", toestand)
                .executeUpdate();
    }
}

但这给了我一个错误:

Error in executeUpdate, Cannot add or update a child row: a foreign key constraint fails (`toondoesselaere`.`gebit`, CONSTRAINT `idPatient` FOREIGN KEY (`idPatient`) REFERENCES `patienten` (`idPatient`) ON DELETE NO ACTION ON UPDATE NO ACTION)

共 (1) 个答案

  1. # 1 楼答案

    您将一个foreign key作为gebit.idPatient{}{}来断开,然后尝试将一个记录插入到gebit中,其中一个idPatient没有匹配的patienten.idPatient

    你需要检查你想要的idPatient,看看这是否是错误的;如果是这样,请修复错误idPatient导致的错误