1 回答
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);
}
}
}
添加回答
举报