我有两张 table 。第一个表 Patienten 有一个自动增量 id。 一个“病人”有多个“gebit”。 idPatient 是两个表中的外键。
病人:
吉比特:
现在我想填写“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();
}
}
我得到的错误:
我尝试了第二种方法,在 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)
最佳答案
您破坏了外键
,如gebit.idPatient
references
patenten.idPatient
并且您尝试插入将一条记录写入到 gebit
中,其中 idPatient
没有匹配的 patenten.idPatient
。
您需要检查要插入
的idPatient
,看看是否不正确;如果是这样,请修复导致错误的 idPatient
的错误。
关于java - 根据其他表的自动增量填充数据库中的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37467737/