【发布时间】:2015-12-10 17:30:10
【问题描述】:
所以我正在为需要能够将球队添加到数据库的足球组织创建一个小型应用程序。
我的数据库有以下 ERD:
我有以下代码可以将团队添加到我的数据库中:
public void toevoegenPloeg(Ploeg ploeg) throws DBException, ApplicationException {
//connectie tot stand brengen
System.out.println(ploeg.getTrainerID());
try (Connection connection = ConnectionManager.getConnection();) {
//statement opstellen
try (PreparedStatement statement = connection.prepareStatement("insert into ploeg (naam, niveau, trainer_id) values(?,?,?)");) {
statement.setString(1, ploeg.getNaam());
statement.setString(2, ploeg.getNiveau());
statement.setInt(3, ploeg.getTrainerID());
statement.execute();
} catch (SQLException ex) {
throw new DBException("SQL-exception in de toevoegenPloeg-methode - statement" + ex);
}
} catch (SQLException ex) {
throw new DBException("SQL-exception in de toevoegenPloeg-methode - connectie " + ex);
}
}
必须可以在没有教练的情况下添加团队。 像这样:
PloegTrans PT = new PloegTrans();
PersoonTrans PeT = new PersoonTrans();
Ploeg ploeg1 = new Ploeg();
ploeg1.setNiveau("U9");
PT.ploegToevoegen(ploeg1);
Trainer_id 是一个 int,因为我还没有定义 trainer_id。 trainer_id 成为 int 的默认值,0。
但是我得到一个外键异常,因为数据库正在寻找一个 id 为 0 的培训师。
我该如何克服这个问题?
如何将我的 int 初始化为“null”?
【问题讨论】:
标签: java database foreign-keys