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

标签 java mysql stored-functions

我有 Sakila Sample Database在我的本地,我正在尝试调用 get_customer_balance来自 Java 的函数。

这是我的代码:

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,但是如何注册呢?为什么我的第一种方法是错误的?

最佳答案

方法的签名是 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,这两个问题都可以得到解决。

关于java - 如何从 Java 调用 MySQL 存储函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44481095/

相关文章:

Java "Runtime"继承

php - 如何在 Google Visualization API 中使用 PHP 变量来定义数据行

mysql - 六边形架构的 MySQL(加上 Redis)上的单查询或 JOIN 实现

mysql - 如何自定义从 Mysql 到 HBase 的 Sqoop 导入序列化?

sql - 为什么在 SQL 中使用表值函数而不是临时表?

java - 门面模式和管理类

JavaFX ListView setItems() 无法解析符号

mysql - 错误: structure of query does not match function result type

java - 如何在一个返回语句中返回两个字符串?

postgresql - 如何创建可以从 DBeaver 调用的 PostgreSQL 函数?