3

I'm trying to find a record. Which let me choose to find a existing record in my database using Stored Procedure. When I tried to search a existing data it doesn't give me the value that I want. When I hit the search button it's not printing the value to the textfield.

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.setInt(1, sectionID);// I set the ID for Primary Key
                myFirstCs.registerOutParameter(2, Types.VARCHAR);
                myFirstCs.setString(2, searchSection_Name);


                boolean hasresults = myFirstCs.execute();

            if (hasresults)
            {
            try (ResultSet myRs = myFirstCs.getResultSet())
            {
                int resultsCounter = 0;
                while (myRs.next())
                {
                    sectionID = myRs.getInt("SECTION_ID");
                    String sectionName = myRs.getString(2);
                    Section_SectionName_TextField.setText(sectionName);//Set the value of text
                    Section_SectionName_TextField.setEnabled(true);//Set to enable

                    resultsCounter++;

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

Stored Procedure

CREATE PROCEDURE getSECTION_NAME(IN ID INT, OUT NAME VARCHAR(50))
SELECT * FROM allsections_list WHERE SECTION_ID = ID AND SECTION_NAME = NAME

Table

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

Any help would be appreciated! Thanks!

Update! According to what I read Stored Procedure can return a result set. I want to retrieve the values of the OUT parameter.

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String searchSection = Section_SearchSection_Textfield.getText();
    String searchSection_Name = Section_SectionName_TextField.getText();

    if (searchSection.isEmpty())
    {
        JOptionPane.showMessageDialog(null, "Please fill up this fields");
    }
    else 
        try (Connection myConn = DBUtil.connect();
             CallableStatement myFirstCs = myConn.prepareCall("{call getSECTION_NAME(?,?)}"))
        {

             myFirstCs.setInt(1, sectionID);// I set the ID for Primary Key
             myFirstCs.registerOutParameter(2, Types.VARCHAR);

            boolean hasresults = myFirstCs.execute();

        if (hasresults)
        {
        try (ResultSet myRs = myFirstCs.getResultSet())
        {
            while (myRs.next())
            {
                sectionID = myRs.getInt("SECTION_ID");

                System.out.print(sectionID);
            }//end of while

        }//end of resultset
        }//end of if
                String sectionName = myFirstCs.getString(2);
                Section_SectionName_TextField.setText(sectionName);//Set the value of text
                Section_SectionName_TextField.setEnabled(true);//Set to enable
                System.out.print(sectionName);
        }//end of connection
        catch (SQLException e) 
        {
            DBUtil.processException(e);
        }

}

I removed the String sectionName = myRs.getString(2); Section_SectionName_TextField.setText(sectionName); Section_SectionName_TextField.setEnabled(true); out of the Result Set block and put it in the Callable Statement block. When I run the program. The only changes is the textfield become enabled and prints me a "null" value.

enter image description here

2nd Update! I want to returned the values of OUT parameter I should not use Result Set to retrieve it. So I used Callable Statement parameter with OUT parameter of stored procedure according to @Gord Thompson.

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

             myFirstCs.setInt(1, 2);// I set the ID for Primary Key
             myFirstCs.registerOutParameter(2, Types.VARCHAR);
             myFirstCs.execute();

             String sectionName = myFirstCs.getString(2);  // retrieve value from OUT parameter
             Section_SectionName_TextField.setText(sectionName);//Set the value of text
             Section_SectionName_TextField.setEnabled(true);//Set to enable
             System.out.println(sectionName);

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

Its still giving me a null values where I don't why I getting this value.

enter image description here

The only changes to my GUI is the textfield become enabled and it's not printing the value I want in the following textfield. :(

enter image description here

Thanks for responding. Feel free to comment.

Francisunoxx
  • 1,440
  • 3
  • 22
  • 45
  • @SashaSalauyou Hi! Please see my updated post. Thanks :) – Francisunoxx Mar 23 '16 at 18:38
  • @SashaSalauyou When I run the query and throws me a error. 'The END;' doesn't show up only the error near line 3. Thanks. – Francisunoxx Mar 23 '16 at 18:44
  • By the way, your Java code sample is definitely not complete, since it starts with an "else" without an "if". And it ends in the middle of the code. This way, it is hard to help you. Please provide at least the complete method, if not even the whole class source code. – Lars Gendner Mar 23 '16 at 19:06
  • @LarsGendner I just cut my source code. Thanks for responding. Please see my updated post. I post already the whole code. Thanks again. – Francisunoxx Mar 23 '16 at 19:12

2 Answers2

2

If you want the value that is returned via an OUT parameter of a stored procedure then you don't use a ResultSet, you use the CallableStatement parameter associated with the OUT parameter of the stored procedure. For example, for the test table

CREATE TABLE `allsections_list` (
 `SECTION_ID` int(11) NOT NULL,
 `SECTION_NAME` varchar(50) DEFAULT NULL,
 PRIMARY KEY (`SECTION_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

containing the sample data

SECTION_ID  SECTION_NAME
----------  ---------------
         1  one_section
         2  another_section

and the stored procedure

CREATE PROCEDURE `getSECTION_NAME`(IN myID INT, OUT myName VARCHAR(50))
BEGIN
   SELECT SECTION_NAME INTO myName FROM allsections_list WHERE SECTION_ID = myID;
END

then the following Java code

try (CallableStatement myFirstCs = conn.prepareCall("{call getSECTION_NAME(?,?)}")) {
    myFirstCs.setInt(1, 2);  // set IN parameter "myID" to value 2
    myFirstCs.registerOutParameter(2, Types.VARCHAR);
    myFirstCs.execute();
    String sectionName = myFirstCs.getString(2);  // get value from OUT parameter "myName"
    System.out.println(sectionName);
}

prints

another_section
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
  • Hi! Please see my updated post. I follow the codes that you posted here and still giving me a null values :( and last one why should I put 2 in my parameter? `myFirstCs.setInt(1, 2);//Why should I put 2?` Thanks for responding. – Francisunoxx Mar 25 '16 at 14:58
  • In my sample code I supplied the value `2` for the first parameter so in the stored procedure `myID` would equal `2` and the `SELECT` would look up the `SECTION_NAME` value corresponding to `SECTION_ID=2`. If you wanted your code to look up the `SECTION_NAME` value corresponding to `SECTION_ID=7` then you would use `myFirstCs.setInt(1, 7);`. – Gord Thompson Mar 25 '16 at 15:10
  • Oh! Your a life saver :)) I already get it. So the 2nd value of the parameter is the # of index of column. My last question. What if I want to find a existing record depending on what I want to search? Without calling the # of ID? Thanks again! :) – Francisunoxx Mar 25 '16 at 15:25
  • I'm not sure what you mean, but if you wanted to search by SECTION_NAME instead of by SECTION_ID then you'd need to create another stored procedure that does `SELECT ... WHERE SECTION_NAME=myName`, with `myName` being an IN parameter instead of an OUT parameter. – Gord Thompson Mar 25 '16 at 15:32
  • Yes exactly I want to search by SECTION_NAME. When I set my `myID` as OUT Parameter and register it. It says `No output parameters returned by procedure.` actually I set `myID` as output parameter but didn't return values. Thank you so much for responding! – Francisunoxx Mar 25 '16 at 16:38
0

you should use delimiter to change the delimiter to something different than ";" when you create the procedure:

delimiter //
CREATE PROCEDURE getSECTION_NAME(IN ID INT, OUT NAME VARCHAR(50)) 
BEGIN 
  SELECT SECTION_NAME INTO NAME FROM allsections_list WHERE SECTION_ID = ID; 
END    
//
delimiter ;

The first delimiter statement sets the delimiter to "//". This way, the ";" in your stored procedure code is not interpreted as a delimiter anymore. Your CREATE PROCEDURE statement then correctly ends at the "//". Aftwerwards, the second delimiterstatement changes the delimiter back to ";".

Lars Gendner
  • 1,816
  • 2
  • 14
  • 24
  • @Mia Legaspi Could you please post the stack trace of the NullPointerException? Thanks – Lars Gendner Mar 23 '16 at 21:04
  • Sorry, but: Do you know what a stack trace of an Exception is?Look here: http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – Lars Gendner Mar 24 '16 at 12:14
  • There's no already NullPointerException in my program. The stored procedure is working properly. But when I run my program and tried to enter existing values, it shows nothing. Thanks for responding. – Francisunoxx Mar 24 '16 at 12:24
  • @MiaLegaspi okay, then please use the debugger to step through your method to see what's happening. – Lars Gendner Mar 24 '16 at 13:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/107241/discussion-between-lars-gendner-and-mia-legaspi). – Lars Gendner Mar 24 '16 at 15:38