简体   繁体   中英

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. Where the Foreign Key its not getting the value of inserted 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. 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. 在此处输入图片说明

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. 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 .

Here's how to modify your first PreparedStatement to obtain the generated 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,
  • add Statement.RETURN_GENERATED_KEYS to the call to prepareStatement on the first line. This tells your database to return the generated value for SECTION_ID .
  • fetch the generated-keys result-set from the statement and read the section ID out of it..

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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