基于其他表自动增量的java数据库外键填充
我有两张桌子。第一个表有一个自动递增id。 一个“patienten”有多个“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)
# 1 楼答案
您将一个}{}来断开,然后尝试将一个记录插入到
foreign key
作为gebit.idPatient
{gebit
中,其中一个idPatient
没有匹配的patienten.idPatient
你需要检查你想要的
idPatient
,看看这是否是错误的;如果是这样,请修复错误idPatient
导致的错误