我有 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/