gpt4 book ai didi

java - 在java中调用pl/sql函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:41:46 24 4
gpt4 key购买 nike

所以我有一个函数可以检查我的预订表中有多少取消:

CREATE OR REPLACE FUNCTION total_cancellations
RETURN number IS
t_canc number := 0;
BEGIN
SELECT count(*) into t_canc
FROM booking where status = 'CANCELLED';
RETURN t_canc;
END;
/

要在 sql 中执行他,我使用:

set serveroutput on
DECLARE
c number;
BEGIN
c := total_cancellations();
dbms_output.put_line('Total no. of Cancellations: ' || c);
END;
/

我的结果是:

anonymous block completed
Total no. of Cancellations: 1

我的问题是有人可以帮我调用JAVA中的函数吗,我已经试过了,但没有成功。

最佳答案

Java 提供 CallableStatements出于此类目的。

CallableStatement cstmt = conn.prepareCall("{? = CALL total_cancellations()}");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.setInt(2, acctNo);
cstmt.executeUpdate();
int cancel= cstmt.getInt(1);
System.out.print("Cancellation is "+cancel);

将打印与您在 pl/sql 中所做的相同的内容。根据文档 Connection#prepareCall() ,

Creates a CallableStatement object for calling database stored procedures. The CallableStatement object provides methods for setting up its IN and OUT parameters, and methods for executing the call to a stored procedure.

您还可以为函数传递参数。例如,

conn.prepareCall("{? = CALL total_cancellations(?)}");
cstmt.setInt(2, value);

将值作为输入参数传递给函数。

希望对您有所帮助!

关于java - 在java中调用pl/sql函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26550465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com