java外键未获取主键Id的值将打印空值
我正在处理我的项目,只是为了学术目的,在那里我遇到了SQL问题。其中外键没有得到插入ID的值。对于我来说,实现了第二个标准形式。我在一张独立的桌子上分开。并使用分区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\u ID列给出了一个空值。
请随意评论。如果我错过了什么,请指引我错在哪里。谢谢
# 1 楼答案
看起来您假设
ALLSECTIONS_SETTINGS
表中的SECTION_ID
列将自动填充插入ALLSECTIONS_LIST
表中的最后一个主键值。这不会发生相反,您需要做的是在第一个
PreparedStatement
中获取为SECTION_ID
列自动生成的值,并在第二个PreparedStatement
中设置它下面是如何修改第一个
PreparedStatement
以获得生成的SECTION_ID
:这些变化是:
sectionId
来保存生成的节IDprepareStatement
的调用中添加Statement.RETURN_GENERATED_KEYS
。这会告诉数据库返回SECTION_ID
的生成值李>我将让您自行修改第二个
PreparedStatement
,以便在插入ALLSECTIONS_SETTINGS
时设置SECTION_ID
列的值