我可以获得有关使用外键插入两个表的帮助吗? 我已经有了这个,当我点击“第一次”它可以工作,但当我尝试第二次或第一次后,外键不会改变,它保持不变。
我的数据库表:
passenger (name, p_id) // p_id is auto-increment
luggage (lug_id, brand, type, p_id)
到目前为止,这是我的代码:
private void InsertLuggageInfo() {
conn = jdbcDBconnection.ConnectDB();
String query_luggage, query_passenger;
query_passenger = "INSERT INTO passenger (name) VALUES (?)";
stmt1 = conn.prepareStatement(query_passenger);
stmt1.setString(1, txtFirstname.getText());
stmt1.execute();
stmt1.close();
} catch (SQLException ex) {
System.err.println(ex);
}
try {
String p_id = null;
String p_id_query = "SELECT p_id FROM passenger WHERE name = '" + txtFirstname.getText() + "'";
stmt2 = conn.prepareStatement(p_id_query);
rs2 = stmt2.executeQuery();
if (rs2.next()) {
p_id = rs2.getString("p_id");
}
query_luggage = "INSERT INTO luggage (lug_id, brand, type, p_id) VALUES (?,?,?,?)";
stmt3 = conn.prepareStatement(query_luggage);
stmt2.setString(1, txtLugNr.getText());
stmt2.setString(2, txtbrand.getText());
stmt2.setString(3, txtType.getText());
stmt2.setString(4, p_id);
stmt2.execute();
stmt2.close();
}catch (SQLException ex) {
System.err.println(ex);
}
答案 0 :(得分:0)
首先,您应该更改获取生成ID的方式。有很多约翰史密斯,它可以给你带来问题。
您可以使用stmt1.getGeneratedKeys()
,如下所示:
int affectedRows = stmt1.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Insert Passenger error: no rows were affected.");
}
try (ResultSet generatedKeys = stmt1.getGeneratedKeys()) {
if (generatedKeys.next()) {
user.setId(generatedKeys.getLong(1));
}
else {
throw new SQLException("Insert Passenger error: no ID obtained.");
}
}
这将保证您获得新插入的数据ID(您的乘客FK)。
第二:您的stmt3
是 INSERT行李。但是您正在设置值并再次执行stmt2
。