亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Spring中編寫一個查詢,將記錄插入到Mysql數據庫的2個表中

如何在Spring中編寫一個查詢,將記錄插入到Mysql數據庫的2個表中

DIEA 2023-11-10 16:54:58
我想編寫一個查詢將數據插入兩個表中。我將數據插入到兩個表中,稱為User和company。 User有外鍵company _id。表結構如下用戶表int user_id;(AI)int 公司_id;(外鍵)字符串用戶名;字符串 user_email;公司表int company_id;(AI)字符串公司名稱;-void insert(String user){    String query="insert into user(user_name,user_email,company_id,company_name) values    (variable,variable, variable, variable)";    //code to map using put method}我收到錯誤company_id cannot be null.
查看完整描述

1 回答

?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

由于外鍵company_id不能是null,公司必須存在于數據庫中,并且在插入用戶之前必須知道它的 id。

更新

要插入新用戶,您需要:

  • 用戶名

  • 電子郵件地址

  • 公司名稱

我們首先需要搜索company_id給定的公司名稱。如果在數據庫中找不到該公司,則會插入一個新公司。

public void insertUser(String userName, String userEmail, String companyName)

        throws SQLException {

    int companyId = getOrInsertCompany(companyName);

    try (PreparedStatement stmt = cnt.prepareStatement(

            "insert into User(company_id,user_name,user_email)"

            + " values(?,?,?)")) {

        stmt.setInt(1, companyId);

        stmt.setString(1, userName);

        stmt.setString(1, userEmail);

        stmt.executeUpdate();

    }

}


private int getOrInsertCompany(String companyName) throws SQLException {

    try (PreparedStatement stmt = cnt.prepareStatement(

            "select company_id from Company where company_name=?")) {

        stmt.setString(1, companyName);

        try (ResultSet rs = stmt.executeQuery()) {

            if (rs.next()) {

                return rs.getInt(1);

            }

        }

    }

    // the company was not found; insert it

    try (PreparedStatement stmt = cnt.prepareStatement(

            "insert into Company(company_name) values(?)")) {

        stmt.setString(1, companyName);

        stmt.execute();

        try (ResultSet rs = stmt.getGeneratedKeys()) {

            if (!rs.next()) {

                throw new SQLException(

                        "Could not get generated keys");

            }

            return rs.getInt(1);

        }

    }

}



查看完整回答
反對 回復 2023-11-10
  • 1 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號