[英]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.