1 回答

TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
由于外鍵company_id
不能是null
,公司必須存在于數(shù)據(jù)庫中,并且在插入用戶之前必須知道它的 id。
更新
要插入新用戶,您需要:
用戶名
電子郵件地址
公司名稱
我們首先需要搜索company_id
給定的公司名稱。如果在數(shù)據(jù)庫中找不到該公司,則會(huì)插入一個(gè)新公司。
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);
}
}
}
添加回答
舉報(bào)