Java - MySQL Calling Stored Procedure

Michael 'Maik' Ardan picture Michael 'Maik' Ardan · May 23, 2013 · Viewed 21.6k times · Source

I'm trying to call a Stored Procedure from Java. However, what I did was looking for a Function instead. What did I miss? Here's what I have tried so far;

open();

try {

    statement = conn.prepareStatement(StringConstant.PROC_GET_POSITIONS);
    ResultSet resultSet = statement.executeQuery();

    while( resultSet.next() ){

        System.out.println(resultSet.getString(0));

    }

} catch ( SQLException sqlEx ) {
    sqlEx.printStackTrace();
}

close();

Throwing this Exception;

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: FUNCTION test.get_positions does not exist

This is how the stored procedure is written (This is for the purpose of testing):

CREATE FUNCTION get_positions(OUT o_position VARCHAR(25))
BEGIN

  SELECT pos_name
  INTO o_position
  FROM master_position;

END;

The reason I made the question is that SO suggested this titles:

-automate call stored procedure 1
-How to Call a Stored Procedure within a Stored Procedure in MySQL 1
-Calling a Stored Procedure in Hibernate 2
-Call a Stored Procedure From a Stored Procedure and/or using COUNT 2
-mysql stored procedure call hibernate 2

None of those answered my question.

Answer

Jesus picture Jesus · Jul 23, 2014

I'm right now with this problem. I found this:

        Connection conn = getMySqlConnection();
        // Step-2: identify the stored procedure
        String simpleProc = "{ call simpleproc(?) }";
        // Step-3: prepare the callable statement
        CallableStatement cs = conn.prepareCall(simpleProc);
        // Step-4: register output parameters ...
        cs.registerOutParameter(1, java.sql.Types.INTEGER);
        // Step-5: execute the stored procedures: proc3
        cs.execute();
        // Step-6: extract the output parameters
        int param1 = cs.getInt(1);
        System.out.println("param1=" + param1);

I think this could be a great example.

Source: http://www.java2s.com/Code/Java/Database-SQL-JDBC/CallStoredProcedureInMySql.htm