Java named parameter's name (for Oracle JDBC function result) - java

I'm going to call a function, and set some parameters by name, example:
Connection c = null;
ResultSet rs = null;
String query;
PreparedStatement ps;
CallableStatement cs = null;
try {
c = DbUtils.getConnection();
cs = c.prepareCall("{? = call get_proc_name(?, ?) }");
cs.registerOutParameter(1, OracleTypes.VARCHAR);
cs.setInt("in_proc_type", ProcTypes.SELECT);
cs.setLong("in_table_id", tableId);
// here I should use something like cs.registerOutParameter("result", OracleTypes.VARCHAR);
cs.execute();
PL/SQL function parameters are:
CREATE OR REPLACE FUNCTION get_proc_name
(
in_proc_type IN NUMBER, /*1 - insert, 2 - update, 3 - delete, 4 - select*/
in_table_name IN VARCHAR2 := NULL,
in_table_id IN NUMBER := NULL,
in_table_type_id IN NUMBER := NULL,
is_new IN NUMBER := 0
) RETURN VARCHAR2
The question is how to register result as an out parameter, and then get it from oracle to java?
I can register in/out parameters by name, because I know theirs names from function, but I don't know how go get function result, what variable name use for it.
Manuals describe only usage in/out params with procedures, not functions.
Oracle version: 11.1.0.6.0
Java version: 1.6.0_14

The solution is to use only indexes for settings parameters. Such code works as expected (mixing indexes and named parameters doesn't work; so, the problem of using named parameter for result variable could not be solved, imho):
c = DbUtils.getConnection();
cs = c.prepareCall("{? = call get_proc_name(in_proc_type => ?, in_table_id => ?) }");
cs.registerOutParameter(1, java.sql.Types.VARCHAR);
cs.setInt(2, ProcTypes.SELECT);
cs.setLong(3, tableId);
cs.execute();
String procName = cs.getString(1);
cs.close();

CallableStatement has a bunch of registerXXX methods that take index.
That's how you register the result. It is parameter number 1.
In your case,
cs.registerOutParameter( 1, java.sql.Types.VARCHAR);
<SPECULATION>
BTW, because you are using index for result, you may need to use index-oriented setXXX methods and provide a full parameter list.
</SPECULATION>

You register the function result as if it were the first parameter. Obviously, this shifts the numbering of the actual parameters.
Your already existing line
cs.registerOutParameter(1, OracleTypes.VARCHAR);
is all it takes. After the call, get your result like this:
String result = cs.getString(1);

Related

How to call the oracle function from java. Function returns number

How should I call an Oracle function from Java? The function is supposed to return a number.
CallableStatement cstmt = mJConn.prepareCall("{? = call fnd_request.submit_request( application => 'FND', program => 'JAVACONINSERT', description => 'CSV to DB Insert via Java' ,start_time => sysdate ,sub_request => FALSE, argument1 => '/home/TEST/java/t1.txt')}");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.executeUpdate();
int reqId = cstmt.getInt(1);
System.out.println(reqId);
Try replacing
String call = "{?= CALL Proc(?)}";
with
String call = "{CALL Proc(?, ?)}";
The former syntax is for calling a stored function, and the new one is for a stored procedure.
You can also to swap the order of the bind parameters :
cs.setString(1, "String");
cs.registerOutParameter(2, Types.INTEGER);

java get stored procedure response

how do i get the Store procedure response in java ?
when i run this in SQL i get a response
DECLARE
result NUMBER;
begin
result := apps.xx01_cpc_ap_pkg.xx01_create_invoice_f(8309, 4795, 146.00);
dbms_output.put_line(result);
end;
this is my java code
i tried many option - but i keep failing on how to fetch the response
in this part resultSet.getInt(4))
CallableStatement stmt = null;
String spCallRequest = "{? = call apps.xx01_cpc_ap_pkg.xx01_create_invoice_f(?, ?, ? )}";
stmt = oraAppUtils.connection.prepareCall(spCallRequest);
stmt.setString(1,paymentRequest.healthFacilityCode);
stmt.setString(2,paymentRequest.batchId);
stmt.setDouble(3,Double.parseDouble(paymentRequest.tariffAmount));
stmt.registerOutParameter(4, java.sql.Types.INTEGER);
resultSet = stmt.executeQuery();
System.out.println ("invoice id ="+resultSet.getInt(4));
ok - just for documentation in case some else needs it... this is the SP it has a function
CREATE OR REPLACE PACKAGE APPS.XX01_CPC_AP_PKG
AS
PROCEDURE XX01_CREATE_INVOICE (P_HF_CODE IN VARCHAR2,
P_BATCH_ID IN VARCHAR2,
P_AMOUNT IN NUMBER,
x_invoice_id OUT NUMBER/*,
x_error_code OUT VARCHAR2,
x_error_msg OUT VARCHAR2,
x_err_comments OUT VARCHAR2,
x_code OUT NUMBER,
x_source OUT VARCHAR2*/);
FUNCTION XX01_CREATE_INVOICE_F (P_HF_CODE IN VARCHAR2,
P_BATCH_ID IN VARCHAR2,
P_AMOUNT IN NUMBER) RETURN NUMBER;
so originaly i called the function - it didn't work - i change the code to the following code and it works
String spCallRequest = "BEGIN apps.xx01_cpc_ap_pkg.xx01_create_invoice(?, ?, ?,? ); END ; ";
stmt = oraAppUtils.connection.prepareCall(spCallRequest);
stmt.setString(1,paymentRequest.healthFacilityCode);
stmt.setString(2,paymentRequest.batchId);
stmt.setDouble(3,Double.parseDouble(paymentRequest.tariffAmount));
stmt.registerOutParameter(4, java.sql.Types.INTEGER);
stmt.execute();
System.out.println ("invoice id ="+stmt.getInt(4));
TL;DR
You did not call ResultSet#next()
Reason
From linked docs:
A ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
Fix
Your code should look like this:
stmt.registerOutParameter(4, java.sql.Types.INTEGER);
resultSet = stmt.executeQuery();
if(resultSet.next()) {
System.out.println ("invoice id ="+resultSet.getInt(4));
} else {
//this should not happen
}
Your question didn't explicitly mention JDBC as the API that you must use, so perhaps, you're open to third party utilities that work on top of JDBC? For example, jOOQ's code generator can be used to generate stubs for all of your stored procedures. In your case, you could simply call the stub like this:
int result = Xx01CpcApPkg.xx01CreateInvoiceF(
configuration, // This object contains your JDBC Connection
paymentRequest.healthFacilityCode,
paymentRequest.batchId,
Double.parseDouble(paymentRequest.tariffAmount)
);
These objects are generated by jOOQ:
Xx01CpcApPkg: A class representing your PL/SQL package
xx01CreateInvoiceF(): A method representing your stored function
Behind the scenes, this does exactly what the accepted answer does, but:
You don't have to work with strings
You don't have to remember data types and parameter order
When you change the procedure in your database, and regenerate the code, then your client code stops compiling, so you'll notice the problem early on
Disclaimer: I work for the company behind jOOQ.

Setting the out parameter in callable statement

I'm trying to run a stored procedure that returns a resultSet using oracle jdbc.
The procedure is as follows.
create or replace procedure display_players (rset OUT sys_refcursor)
as
Begin
open rset for select * from player_data;
End;
/
The java code is as follows
try {
sql = "{call display_players()}";
call = conn.prepareCall(sql);
call.execute();
rs = call.getResultSet();
while(rs.next()){
System.out.println(rs.getString("name") + " : " + rs.getString("club"));
}
I tried to register the out parameter as
call = conn.prepareCall("{call display_players(?)}");
call.registerOutParameter(1, OracleTypes.CURSOR);
But that dint work nor is the current code working as i get a null pointer exception which means the result set is not being returned.
how do i achieve this?
I think you haven't quite worked out how to get the result set from an OUT parameter from a stored procedure call.
Firstly, you need to register the OUT parameter, as in your second code sample:
call = conn.prepareCall("{call display_players(?)}");
call.registerOutParameter(1, OracleTypes.CURSOR);
However, once you've executed the statement, it's not correct to call.getResultSet() to get at the result set in the OUT parameter. For example, suppose you were calling a stored procedure that had two OUT parameters returning cursors. Which one should call.getResultSet() return?
The trick is to use call.getObject(...) to get the value of the parameter from call as an Object and then cast this to a ResultSet. In other words, replace the line
rs = call.getResultSet();
with
rs = (ResultSet)call.getObject(1);

Call pl/sql function in java?

So I've got a function that checks how many cancellations are in my booking table:
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;
/
To execute his in sql I use:
set serveroutput on
DECLARE
c number;
BEGIN
c := total_cancellations();
dbms_output.put_line('Total no. of Cancellations: ' || c);
END;
/
My result is:
anonymous block completed
Total no. of Cancellations: 1
My question is can someone help me call the function in JAVA, I have tried but with no luck.
Java provides CallableStatements for such purposes .
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);
will print the same as you do in the pl/sql. As per docs 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.
You can also pass parameters for the function . for ex ,
conn.prepareCall("{? = CALL total_cancellations(?)}");
cstmt.setInt(2, value);
will pass the values to the function as input parameter.
Hope this helps !
Prepare a Callable Statement
There are two formats available, the
familiar block syntax used by Oracle and the ANSI 92 standard syntax.
In the case of our sample program, the block syntax has the form:
CallableStatement vStatement =
vDatabaseConnection.prepareCall( "begin ? := javatest( ?, ? ); end;" );
The ANSI 92 syntax has the form:
CallableStatement vStatement =
vDatabaseConnection.prepareCall( "{ ? = call javatest( ?, ? )}");
source
If you receive the below error, you might want to use the first format.
total_cancellations is not a procedure or is undefined error.
Sample code.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#xx.xxx.xx.xxx:1521:xxx", "user","pass");
CallableStatement cstmt = conn.prepareCall("begin ? := TEST_FUNC(?,?); end;");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.setString(2, "Test");
cstmt.setInt(3, 1001);
cstmt.execute();
int result = cstmt.getInt(1);
System.out.print("Result: " + result);
cstmt.close();
conn.close();

ORA-03115: unsupported network data type or representation

Before issuing this question, i have googled a while, however now result found. My code attempts to call a procedure in oracle package(i am not very familiar with oracle package), and always get "ORA-03115: 不支持的网络数据类型或表示法", in english it should be 'unsupported network data type or representation'.
Below is my packagke:
create or replace
PACKAGE PKG_ACTIVITY_REPORT
IS
TYPE activity_report_item_type IS RECORD
( emp_id MERCHANT.merchant_id%TYPE,
emp_name MERCHANT.MERCHANT_NAME%TYPE,
emp_gender MERCHANT.MERCHANT_CODE%TYPE );
TYPE activity_report_items_type IS TABLE OF activity_report_item_type INDEX BY BINARY_INTEGER;
-- Procedure to retrive the activity report of given operator
PROCEDURE enquiry_activity_report(activity_report_items OUT activity_report_items_type);
END PKG_ACTIVITY_REPORT;
create or replace
PACKAGE BODY PKG_ACTIVITY_REPORT
IS
PROCEDURE enquiry_activity_report (activity_report_items OUT activity_report_items_type)
IS
activity_report_item activity_report_item_type;
BEGIN
activity_report_item.emp_id := 300000000;
activity_report_item.emp_name := 'Barbara';
activity_report_item.emp_gender := 'Female';
activity_report_items(1) := activity_report_item;
activity_report_item.emp_id := 300000008;
activity_report_item.emp_name := 'Rick';
activity_report_item.emp_gender := 'Male';
activity_report_items(2) := activity_report_item;
FOR i IN 1..activity_report_items.count LOOP
DBMS_OUTPUT.PUT_LINE('i='||i||', emp_id ='||activity_report_items(i).emp_id||', emp_name ='
||activity_report_items(i).emp_name||', emp_gender = '||activity_report_items(i).emp_gender);
END LOOP;
END enquiry_activity_report;
END PKG_ACTIVITY_REPORT;
I wanna return a array from the procedure, and call this procedure from java:
conn = ds.getConnection();
String storedProc = "{call pkg_activity_report.enquiry_activity_report(?)}";
CallableStatement cs = conn.prepareCall(storedProc);
// register output parameter
cs.registerOutParameter(1, java.sql.Types.ARRAY);
cs.execute();
Array array = cs.getArray(1);
System.out.println(array);
cs.close();
when run it, the exception thrown out. How do I map the OUT parameter to a java type? Pls help.
NOTE: when run this procedure from oracle sqldeveloper, it works properly.
DECLARE
ACTIVITY_REPORT_ITEMS RAMON.PKG_ACTIVITY_REPORT.ACTIVITY_REPORT_ITEMS_TYPE;
BEGIN
PKG_ACTIVITY_REPORT.ENQUIRY_ACTIVITY_REPORT(
ACTIVITY_REPORT_ITEMS => ACTIVITY_REPORT_ITEMS
);
END;
DBMS outputs the result:
i=1, emp_id =300000000, emp_name =Barbara, emp_gender = Female
i=2, emp_id =300000008, emp_name =Rick, emp_gender = Male
Now I created 2 schema-level type:
CREATE OR REPLACE TYPE activity_report_item_type AS OBJECT(
emp_id NUMBER,
emp_name VARCHAR2(30),
emp_gender VARCHAR2(30)
);
CREATE OR REPLACE TYPE activity_report_items_type AS TABLE OF activity_report_item_type;
And move PROCEDURE enquiry_activity_report out of package, make it independently, then call it from java successfully.
conn = ds.getConnection();
String storedProc = "{call enquiry_activity_report(?)}";
CallableStatement cs = conn.prepareCall(storedProc);
// register output parameter
cs.registerOutParameter(1, OracleTypes.ARRAY, "ACTIVITY_REPORT_ITEMS_TYPE");
cs.execute();
Array array = cs.getArray(1);
ResultSet rs = array.getResultSet();
while (rs.next()) {
// why getObject(2) instead of getObject(1)?
Object elements[] = ((STRUCT) rs.getObject(2)).getAttributes();
System.out.println(elements[0]);
System.out.println(elements[1]);
System.out.println(elements[2]);
}
cs.close();
If I put type declaration and procedure in package, java code will throw exception inform that 'no type definition found of "ACTIVITY_REPORT_ITEMS_TYPE".

Categories

Resources