简体   繁体   中英

How to get the Primary Key value after Select using Stored Procedure?

How can I get the value of the existing Primary Key ID in my data? I tried to select a data but it's not getting the value in my current table. When I try search a existing record. It prints to the textfields. Also when I search a non existing record it still prints to the textfields. Did I missed something?

Non Existing Record

在此处输入图片说明

TABLE

CREATE TABLE allsections_list
(
 SECTION_ID INT PRIMARY KEY AUTO_INCREMENT,
 SECTION_NAME INT VARCHAR(50)
)

STORED PROCEDURE

CREATE PROCEDURE getSECTION_NAME (IN SECTION_NAME VARCHAR(50))
SELECT SECTION_NAME FROM allsections_list

DATA

在此处输入图片说明

CODE

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String searchSection = Section_SearchSection_Textfield.getText();
    String searchSection_Name = Section_SectionName_TextField.getText();
    int sectionId = 0;
    if (searchSection.isEmpty())
    {
        JOptionPane.showMessageDialog(null, "Please fill up this fields");
    }
    else 
        try (Connection myConn = DBUtil.connect())
        {   
            try (CallableStatement myFirstCs = myConn.prepareCall("{call getSECTION_NAME(?)}"))
            {
                myFirstCs.setString(1, searchSection);//Get value of Section_SearchSection_Textfield

                myFirstCs.executeQuery();

            try (ResultSet myRs = myFirstCs.executeQuery())
            {
                int resultsCounter = 0;
                while (myRs.next())
                {
                    String getSection_Name = myRs.getString(1);
                    sectionID = myRs.getInt("SECTION_ID");

                    Section_SectionName_TextField.setText(getSection_Name);//Set the value of text
                    Section_SectionName_TextField.setEnabled(true);//Set to enable

                    System.out.print(sectionID);
                    resultsCounter++;

                }//end of while
                }//end of resultset
            }//end of callablestatement
        }//end of connection
        catch (SQLException e) 
        {
            DBUtil.processException(e);
        }  
}

Any help or tips will appreciate! Thanks!

You only have an IN parameter in your procedure definition. You might use an OUT parameter, set it in the procedure and SELECT it after execution to get the result, like here: mysql manual

in the first example.

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