[英]Foreign Key not getting the value of Id of Primary Key prints NULL
我正在為我遇到SQL問題的學術目的而工作。 凡外鍵未獲取插入ID的值。 對我來說,要達到第二范式。 我分成一個獨立的表。 並使用SECTION_ID作為外鍵進行匹配。 在這里我創建了兩個表。
第一桌
第二表
源代碼:
String inputSectionName = Section_SectionName_TextField.getText();
int inputStudentLimit = Section_Student_Limit_ComboBox.getSelectedIndex();
String inputRoomAssign = Section_Student_Limit_ComboBox2.getSelectedItem().toString();
String inputAdviserAssign = Section_Student_Limit_ComboBox1.getSelectedItem().toString();
String inputSession = Section_Session_Settings_ComboBox.getSelectedItem().toString();
String inputYearLevel = Section_Session_Level_ComboBox.getSelectedItem().toString();
String inputSchoolYear = Section_SchooYear_ComboBox.getSelectedItem().toString();
String insertALLSECTION_LIST = "INSERT INTO ALLSECTIONS_LIST (SECTION_NAME)"
+ "VALUES (?)";
String insertALLSECTIONS_SETTINGS = "INSERT INTO ALLSECTIONS_SETTINGS (SECTION_POPULIMIT,ROOM_ASSGN,ADVISER_ASSIGNED,SESSION_ASSIGNED,YRLEVEL_ASSGN,SCHOOL_YEAR)"
+ "VALUES(?,?,?,?,?,?)";
try (Connection myConn = DBUtil.connect())//Connection
{
myConn.setAutoCommit(false);//Turn off auto commit
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
}//end of try
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTIONS_SETTINGS))//Prepared Statement
{
myPs.setInt(1,inputStudentLimit);
myPs.setString(2, inputRoomAssign);
myPs.setString(3, inputAdviserAssign);
myPs.setString(4, inputSession);
myPs.setString(5, inputYearLevel);
myPs.setString(6, inputSchoolYear);
myPs.executeUpdate();
myConn.commit();
JOptionPane.showMessageDialog(null, "Insert Successful");
}//end of try
}//end of try
catch(SQLException e)
{
DBUtil.processException(e);
}//end of catch
但是,當我對第二張表運行查詢時, SECTION_ID列為我提供了空值。
隨時發表評論。 如果我錯過了什么,請指導我哪里出錯了。 謝謝。
似乎您假設ALLSECTIONS_SETTINGS
表中的SECTION_ID
列將自動填充有插入ALLSECTIONS_LIST
表中的最后一個主鍵值。 這不會發生。
您需要做的是獲取第一個PreparedStatement
為SECTION_ID
列自動生成的值,並在第二個PreparedStatement
。
這是修改第一個PreparedStatement
以獲得生成的SECTION_ID
:
int sectionId;
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST, Statement.RETURN_GENERATED_KEYS))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
ResultSet generatedKeys = myPs.getGeneratedKeys();
if (generatedKeys.next()) {
sectionId = generatedKeys.getInt(1);
} else {
throw new SQLException("No generated section ID returned");
}
}
更改為:
sectionId
來保存生成的部分ID, Statement.RETURN_GENERATED_KEYS
添加到第一行的prepareStatement
調用中。 這告訴您的數據庫返回SECTION_ID
的生成值。 當您插入ALLSECTIONS_SETTINGS
時,由您自己修改第二個PreparedStatement
來設置SECTION_ID
列的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.