Cannot retrieve the value I desired to Select using Stored Procedure

后端 未结 2 850
囚心锁ツ
囚心锁ツ 2020-12-04 02:51

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

相关标签:
2条回答
  • 2020-12-04 03:38

    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
    
    0 讨论(0)
  • 2020-12-04 03:41

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

    0 讨论(0)
提交回复
热议问题