简体   繁体   English

Java - MySQL 调用存储过程

[英]Java - MySQL Calling Stored Procedure

I'm trying to call a Stored Procedure from Java.我正在尝试从 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:我提出这个问题的原因是 SO 建议了这个标题:

-automate call stored procedure 1 -自动调用存储过程1
-How to Call a Stored Procedure within a Stored Procedure in MySQL 1 - 如何在 MySQL 1 中的存储过程中调用存储过程
-Calling a Stored Procedure in Hibernate 2 - 在 Hibernate 2 中调用存储过程
-Call a Stored Procedure From a Stored Procedure and/or using COUNT 2 - 从存储过程和/或使用 COUNT 2 调用存储过程
-mysql stored procedure call hibernate 2 -mysql 存储过程调用hibernate 2

None of those answered my question.这些都没有回答我的问题。

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来源: http : //www.java2s.com/Code/Java/Database-SQL-JDBC/CallStoredProcedureInMySql.htm

You are trying to get the result from the stored procedure.您正在尝试从存储过程中获取结果。 Stored procedures do not return values instead Function does.存储过程不返回值,而是 Function 。

Statement stmt;
            stmt = conn.createStatement();
            stmt.execute(String.format("CALL swap_devices(%d,%d)", oldDeviceID, newDeviceID));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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