【问题标题】:How can I call a MySQL stored function from Java?如何从 Java 调用 MySQL 存储函数?
【发布时间】:2017-06-11 06:41:39
【问题描述】:

我的本​​地有Sakila Sample Database,我正在尝试从Java 调用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,但是如何注册呢?为什么我的第一种方法是错误的?

【问题讨论】:

    标签: java mysql stored-functions


    【解决方案1】:

    方法的签名是void registerOutParameter(int parameterIndex, int sqlType),其中sqlType被描述为“java.sql.Types定义的JDBC类型代码”。

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

    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,这两个问题都可以解决。

    【讨论】:

    • 仍然得到:线程“main”中的异常 java.sql.SQLException:参数号 1 不是 OUT 参数。
    【解决方案2】:

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

    final CallableStatement callableStatement = connection.prepareCall("{? = call get_customer_balance(?, ?)}");
    
    callableStatement.registerOutParameter(1, java.sql.Types.INTEGER);
    

    【讨论】:

    • 还是得到:参数1不是OUT参数
    猜你喜欢
    • 2016-12-17
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多