【问题标题】:foreign key always stays null外键始终为空
【发布时间】:2016-05-27 08:38:15
【问题描述】:

我需要一些帮助才能在我的两个表之间建立连接

这些是“idPatient 是外键”的表

我这样填表“tanden”

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

一切都很好地添加了,但 idPatient 保持为空

【问题讨论】:

  • idPatient 不包含在您的 INSERT 查询的值中。你没有指定它。您是否希望以某种方式自动检索它?
  • 是的,但是我如何指定它
  • 您至少需要插入一个病人。然后,知道它的 id,将其用作 tanden 中 idPatient 列的值。

标签: java mysql jdbc sql2o


【解决方案1】:

如果你想为它设置值,你应该在你的insert 中包含idPatient。 '外键'并不意味着它会自动设置值。

【讨论】:

  • 如果我尝试在外键中插入一些东西,我会得到:线程“AWT-EventQueue-0”org.sql2o.Sql2oException 中的异常:executeUpdate 中的错误,无法添加或更新子行:外键约束失败(toondoesselaere.tanden, CONSTRAINT id FOREIGN KEY (id) REFERENCES patienten (idPatient) ON DELETE NO ACTION ON UPDATE NO ACTION)
【解决方案2】:

您必须从 Patienten 表中取出 idPatient 列值插入到 tanden 表中。

【讨论】:

    【解决方案3】:

    你在 tanden 表中的 id 列应该设置为主键和自动增量,你必须在你的插入中设置 idPatient

    insert into tanden(idPatient, fdi, voorstelling, toestand) values(:idVal,:fdiVal, :voorstellingVal, :toestandVal)";
    

    (你在子表中设置的idPatient已经必须存在于父表中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2019-07-06
      • 2018-12-27
      • 2021-02-24
      • 1970-01-01
      相关资源
      最近更新 更多