简体   繁体   English

外键未获取主键Id的值将显示NULL

[英]Foreign Key not getting the value of Id of Primary Key prints NULL

I'm working with my project just for a academic purposes where I encounter a SQL problem. 我正在为我遇到SQL问题的学术目的而工作。 Where the Foreign Key its not getting the value of inserted ID. 凡外键未获取插入ID的值。 For me to achieve 2nd Normal Form. 对我来说,要达到第二范式。 I split out in an independent tables. 我分成一个独立的表。 And match them up using the SECTION_ID as foreign keys. 并使用SECTION_ID作为外键进行匹配。 Here where I create a two tables. 在这里我创建了两个表。

1st Table 第一桌

ALLSECTIONS_LIST

2nd Table 第二表

在此处输入图片说明

SOURCE CODE: 源代码:

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

When I run my query for the 1st Table it gives me output like this. 当我运行第一张表的查询时,它会给我这样的输出。 在此处输入图片说明

But when I run my query for the 2nd Table the SECTION_ID column gives a me null value. 但是,当我对第二张表运行查询时, SECTION_ID列为我提供了空值。 在此处输入图片说明

Feel free to comment. 随时发表评论。 If I miss something guide me where I go wrong. 如果我错过了什么,请指导我哪里出错了。 Thanks. 谢谢。

It looks like you're assuming the SECTION_ID column in your ALLSECTIONS_SETTINGS table will be automatically populated with the last primary-key value that was inserted into the ALLSECTIONS_LIST table. 似乎您假设ALLSECTIONS_SETTINGS表中的SECTION_ID列将自动填充有插入ALLSECTIONS_LIST表中的最后一个主键值。 This doesn't happen. 这不会发生。

What you need to do instead is to get the value that was automatically generated for the SECTION_ID column in the first PreparedStatement and set it in the second PreparedStatement . 您需要做的是获取第一个PreparedStatementSECTION_ID列自动生成的值,并在第二个PreparedStatement

Here's how to modify your first PreparedStatement to obtain the generated SECTION_ID : 这是修改第一个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");
            }
        }

The changes are: 更改为:

  • add a new variable sectionId to hold the generated section ID, 添加一个新的变量sectionId来保存生成的部分ID,
  • add Statement.RETURN_GENERATED_KEYS to the call to prepareStatement on the first line. Statement.RETURN_GENERATED_KEYS添加到第一行的prepareStatement调用中。 This tells your database to return the generated value for SECTION_ID . 这告诉您的数据库返回SECTION_ID的生成值。
  • fetch the generated-keys result-set from the statement and read the section ID out of it.. 从语句中获取生成关键字结果集,并从中读取节ID。

I'll leave it up to you to modify your second PreparedStatement to set the value for the SECTION_ID column when you insert into ALLSECTIONS_SETTINGS . 当您插入ALLSECTIONS_SETTINGS时,由您自己修改第二个PreparedStatement来设置SECTION_ID列的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM