如何从 Java 调用 MySQL 存储函数?

How can I call a MySQL stored function from Java?

我有 Java 的 Sakila Sample Database in my local, and I am trying to call the get_customer_balance 函数。

这是我的代码:

double callableStatementFunctionCallExample(final int customerId) throws SQLException {
    double customerBalance = -1;

    final Connection connection = DriverManager.getConnection(url, user, pass);

    final CallableStatement callableStatement = connection.prepareCall("{CALL ? = get_customer_balance(?, ?)}");
    callableStatement.registerOutParameter(1, customerBalance);
    callableStatement.setInt(2, customerId);
    final java.sql.Date date = new Date(Calendar.getInstance().getTimeInMillis());
    callableStatement.setDate(3, date);

    callableStatement.execute();
    return customerBalance;
}

这导致:

Exception in thread "main" java.sql.SQLException: Parameter number 1 is not an OUT parameter.

所以我替换了这条语句..

callableStatement.registerOutParameter(1, customerBalance);

与..

callableStatement.setDouble(1, customerBalance);

这导致:

Exception in thread "main" java.sql.SQLException: Parameter p_film_count is not registered as an output parameter.

显然我需要注册一个 out parameter,但是如何注册?为什么我的第一种方法是错误的?

在 execute() 之前按类型注册(例如整数):

final CallableStatement callableStatement = connection.prepareCall("{? = call get_customer_balance(?, ?)}");

callableStatement.registerOutParameter(1, java.sql.Types.INTEGER);

方法的签名是void registerOutParameter(int parameterIndex, int sqlType),其中sqlType被描述为"the JDBC type code defined by java.sql.Types"。

这意味着您的电话应该是:

callableStatement.registerOutParameter(1, Types.DOUBLE);

然后您在 execute() 调用后检索该值,使用:

double customerBalance = callableStatement.getDouble(1);

您用值 -1 调用它,这是 Types.LONGVARCHAR 的值。


此外,CallableStatement 的 javadoc 显示 SQL 字符串的语法是 {?= call <procedure-name>[(<arg1>,<arg2>, ...)]},这意味着您的语句应该是:

final CallableStatement callableStatement = connection.prepareCall("{? = CALL get_customer_balance(?, ?)}");

如果您阅读 javadoc,这两个问题都可以得到解决。