簡體   English   中英

Java使用外鍵將數據插入數據庫

[英]Java insert data into database with Foreign Key

因此,我正在為足球組織創建一個小型應用程序,該應用程序需要能夠將球隊添加到數據庫中。

我的數據庫具有以下ERD:

數據庫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是一個整數,因為我尚未定義trainer_id。 trainer_id成為int的默認值0。

但是隨后我得到了一個外鍵異常,因為數據庫正在查找ID為0的培訓師。

我該如何克服?

如何將我的int初始化為“ null”?

使用statement.setNull(3, java.sql.Types.INTEGER); 或將語句構造為insert into ploeg (naam, niveau) values(?,?)的語句,因此trainer_id將默認為NULL

在POJO方面,培訓師ID應該是java.lang.Integer ,而不是原始int ,以允許使用null 在JDBC方面,可以使用setObject代替setInt ,后者不接受null

// getTrainerID() returns either an Integer instance or null
statement.setObject(3, ploeg.getTrainerID()); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM