java - 根据其他表的自动增量填充数据库中的外键

标签 java mysql jdbc sql2o

我有两张 table 。第一个表 Patienten 有一个自动增量 id。 一个“病人”有多个“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)

最佳答案

您破坏了外键,如gebit.idPatient references patenten.idPatient并且您尝试插入将一条记录写入到 gebit 中,其中 idPatient 没有匹配的 patenten.idPatient

您需要检查要插入idPatient,看看是否不正确;如果是这样,请修复导致错误的 idPatient 的错误。

关于java - 根据其他表的自动增量填充数据库中的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37467737/

相关文章:

php - 如何将数字格式化为只有两位小数?

java - 数据未保存在 ArrayList 中

mysql - 我如何使用 logstash 从 MySQL 动态更新我的数据(不重复)?

java - 如何在 PreparedStatement 上设置查询超时?

java - 了解 Java 中的 ThreadGroup 有用吗?

mysql - 您是否应该将多个简单查询合并为一个?

php - 如何使用 PDO 将 html 输入数组插入到 mysql 中

java - Spring Form 中的类级别验证

java - Mockito 将Mocks注入(inject)静态对象

java - Java 中的语义查询