Calling an Oracle Stored Procedure in Java - java

Here's how I'm able to execute my stored procedure through SqlDeveloper
var p refcursor;
exec DMG.Getstudentids(12342343,:p);
print p;
Output
P
-----------
STUDENT_ID
-----------
23432425
54353455
Now I'm trying execute the stored procedure the same way but in Java. Here's my code and I'm missing something about the input/output parameters or their datatypes.
Connection connection = DriverManager.getConnection(url, user, pass);
CallableStatement cs = connection.prepareCall("{call DMG.Getstudentids(?,?)}");
cs.setFloat(1, 12342343);
cs.registerOutParameter(2, Types.OTHER);
cs.execute();
List<Integer> result = (List<Integer>) cs.getArray(2);
I get the following error
java.sql.SQLException: Invalid column type: 1111
I think I'm missing something fundamental here. Anyone see where I'm failing? Thanks.

Try following:
Connection connection = DriverManager.getConnection(url, user, pass);
CallableStatement cs = connection.prepareCall("{call DMG.Getstudentids(?,?)}");
cs.setFloat(1, 12342343);
cs.registerOutParameter(2, OracleTypes.CURSOR);
cs.executeQuery();
ResultSet resultSet=cs.getObject(1);
List<Integer> result = new ArrayList<Integer>();
while(resultSet.next()){
result.add(resultSet.getInt(STUDENT_ID));
}
Note : Since the procedure is returning refcursor, you need to register OracleTypes.CURSOR as output parameter.
Nother thing to note is you need to catch the whole dataset(refcursor) into Result Set, iterate it and put the extracted value into List.

Related

Call procedure included in oracle package

I have created a package in my Oracle database which includes several procedures, now I want to call procedure from java program procedure requires two input parameter and returns nothing.
Please help me to do so, I have been using below connection to connect to database:
String i =username.getText();
String j =psswd.getText();
String k = sid.getText();
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#ora211g.home.com:1654:ora11g",username,password);
st = con.createStatement();
rs =st.executeQuery("SELECT DISTINCT SUBJECT_AREA FROM REP_SUBJECT");
This thing is working fine, now how can I call procedure by passing some parameter (say two string values)
This useful blog posting will help you
http://jameajudo.blogspot.com.br/2009/03/call-procedure-oracle-with-java-and.html
The example he uses is:
String command = "{call SALDOS(?,?)}";
CallableStatement cstmt = con.prepareCall (command);
cstmt.registerOutParameter(2, Types.DECIMAL);
cstmt.execute();
2This is what you want
st = con.prepareStatement("SELECT DISTINCT SUBJECT_AREA FROM REP_SUBJECT WHERE A = ? AND B = ?");
st.setString(1, "val1");
st.setString(2, "val2");
rs =st.executeQuery();
Using con.prepareCall().
And then using the CallableStatement object that is returned for setting params and execution.
Here I got the solution of my question so thought of posting it here so that everybody can understand in detail:
Connection con = null;
ResultSet rs = null;
Statement st = null;
Class.forName = Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection( "jdbc:oracle:thin:#host:port:SID);
CallableStatement csmt = con.prepareCall("{call PACKAGE_NAME.PROCEDURE_NAME(?,?,?,?)}");
csmt.setString(1,"abc");
csmt.setString(2,"def");
csmt.setString(3,"ghi");
csmt.registerOutParameter(4,java.sql.Types.VARCHAR);
csmt.execute();
String message =csmt.getString(4);
here '?' indicates the number of input and output parameters in your procedure. I had 3 input and 1 output parameter so number of '?' in procedure are 4.
there indexing start with 1,2,3....
my first three input parameter are a string, so i am passing them to procedure using :
csmt.setString(1,"abc");
csmt.setString(2,"def");
csmt.setString(3,"ghi");
my Procedure returns string, so in order to get receive that in java first I have to register the out parameter so I have done the same using :
csmt.registerOutParameter(4,java.sql.Types.VARCHAR); /*4 becuase out parameter is 4th*/
Then I have executed callable statement and after that I am receiving the return from procedure into
String message =csmt.getString(4);
Enjoy..... \M/

Java - MySQL Calling Stored Procedure

I'm trying to call a Stored Procedure from Java. However, what I did was looking for a Function instead. What did I miss? Here's what I have tried so far;
open();
try {
statement = conn.prepareStatement(StringConstant.PROC_GET_POSITIONS);
ResultSet resultSet = statement.executeQuery();
while( resultSet.next() ){
System.out.println(resultSet.getString(0));
}
} catch ( SQLException sqlEx ) {
sqlEx.printStackTrace();
}
close();
Throwing this Exception;
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: FUNCTION test.get_positions does not exist
This is how the stored procedure is written (This is for the purpose of testing):
CREATE FUNCTION get_positions(OUT o_position VARCHAR(25))
BEGIN
SELECT pos_name
INTO o_position
FROM master_position;
END;
The reason I made the question is that SO suggested this titles:
-automate call stored procedure 1
-How to Call a Stored Procedure within a Stored Procedure in MySQL 1
-Calling a Stored Procedure in Hibernate 2
-Call a Stored Procedure From a Stored Procedure and/or using COUNT 2
-mysql stored procedure call hibernate 2
None of those answered my question.
I'm right now with this problem. I found this:
Connection conn = getMySqlConnection();
// Step-2: identify the stored procedure
String simpleProc = "{ call simpleproc(?) }";
// Step-3: prepare the callable statement
CallableStatement cs = conn.prepareCall(simpleProc);
// Step-4: register output parameters ...
cs.registerOutParameter(1, java.sql.Types.INTEGER);
// Step-5: execute the stored procedures: proc3
cs.execute();
// Step-6: extract the output parameters
int param1 = cs.getInt(1);
System.out.println("param1=" + param1);
I think this could be a great example.
Source: http://www.java2s.com/Code/Java/Database-SQL-JDBC/CallStoredProcedureInMySql.htm
You are trying to get the result from the stored procedure. Stored procedures do not return values instead Function does.
Statement stmt;
stmt = conn.createStatement();
stmt.execute(String.format("CALL swap_devices(%d,%d)", oldDeviceID, newDeviceID));

Can Java batch calls to SQL stored procedures?

Java: Insert multiple rows into MySQL with PreparedStatement covers batching multiple INSERTs into one operation. I wondered if it is possible to do the same with calls to stored procedures, more specifically with MySQL? If so, what statement class would be used?
If you have your stored procedure like this:
JDBC CallableStatement Stored procedure IN parameter example.
CREATE OR REPLACE PROCEDURE insertEMPLOYEE(
e_id IN EMPLOYEE.EMPLOYEE_ID%TYPE,
e_name IN EMPLOYEE.NAME%TYPE,
e_salary IN EMPLOYEE.SALARY%TYPE)
IS
BEGIN
INSERT INTO EMPLOYEE ("EMPLOYEE_ID", "NAME", "SALARY")
VALUES (e_id, e_name, e_salary);
COMMIT;
END;
You can just use executeBatch() to do as you intend.
Example:
Connection conn = null;
CallableStatement callableStatement = null;
String proc = "{call insertEMPLOYEE(?,?,?)}";
try{
//get connection
conn = JDBCUtil.getConnection();
//create callableStatement
callableStatement = conn.prepareCall(proc);
callableStatement.setInt(1, 7);
callableStatement.setString(2, "Harish Yadav");
callableStatement.setInt(3, 50000);
callableStatement.addBatch();
callableStatement.setInt(1, 8);
callableStatement.setString(2, "Abhishek Rathor");
callableStatement.setInt(3, 50000);
callableStatement.addBatch();
//execute query
callableStatement.executeBatch();
//close connection
callableStatement.close();
conn.close();
System.out.println("Records inserted successfully.");
}catch(Exception e){
e.printStackTrace();
}
You can use executeBatch(). See this example
Note: I haven't validated example by running in my local, but as per documentation it should work.

Getting a result back from a stored procedure in Java

I am having the hardest time calling an Oracle stored procedure from a java runtime environment. The stored procedure that I am calling has 2 parameters 1 in and 1 out. Here is how I call the stored procedure... How do you get the resultSet from an Oracle ref_cursor
ds = (DataSource)initialContext.lookup("JDBC/EPCD13DB");
conn = ds.getConnection();
callableStatement = conn.prepareCall(storedProcCall);
callableStatement.setString(1, input1);
callableStatement.registerOutParameter(2, OracleTypes.CURSOR);
callableStatement.execute();//(ResultSet) callableStatement.getObject(1);
ResultSet rs = callableStatement.getResultSet();
while(rs.next()){
Provider tempProv = new Provider();
tempProv.setResourceId(rs.getLong("res_id"));
tempProv.setFirstName(rs.getString("First_Name"));
tempProv.setLastName(rs.getString("Last_Name"));
tempProv.setMiddleName(rs.getString("Middle_Name"));
ObjList.add(tempProv);
}
rs.close();
You should be able to retrieve the ResultSet with:
ResultSet rSet = (ResultSet)callableStatement.getObject(2);
Does this help you? Seems like you have to call getObject and cast it into a result set before querying on the result set.
Credit:: http://www.mkyong.com/jdbc/jdbc-callablestatement-stored-procedure-cursor-example/
I believe it returns only one output(oracle cursor)
ResultSet rs=(ResultSet) callableStatement.getObject(2);
and then iterate your cursor result set for records inside:
while(rs.next()){
Provider tempProv = new Provider();
tempProv.setResourceId(rs.getLong("res_id"));
tempProv.setFirstName(rs.getString("First_Name"));
tempProv.setLastName(rs.getString("Last_Name"));
tempProv.setMiddleName(rs.getString("Middle_Name"));
ObjList.add(tempProv);
}
In spring framework fetching database cursor results can be easily achieved. It has inbuilt classes like maprow, storedprocedure to serve the purpose. PFB the link
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/jdbc.html#jdbc-simple-jdbc-call-1

MS SQL JDBC - SQLServerCallableStatement - execute() returns false

I have written code which should call MSSQL 2005 procedure from my servlet. The problem is the procedure is to SELECT data from table so I want to get ResultSet but the result set is never returns :( I tested the procedure with another procedure and it works, moreover, the client connection privileges are dbowner so there should be no problem with connection but still the execute returns false :(
Here is the problem code (current connection is connected I checked):
...
SQLServerCallableStatement callableStatement = null;
callableStatement = (SQLServerCallableStatement) connection.prepareCall(
"{call "+
DATABASE_NAME+
"."+
SCHEMA_NAME+
".select_item_proc(?,?,?)}");
callableStatement.setInt(1, 0);
callableStatement.setString(2, "value1");
callableStatement.setString(3, "value2");
boolean rs=callableStatement.execute();
if(rs)
{
ResultSet result=callableStatement.getResultSet();
while (result.next()) {
String col1= result.getString(1);
String col2=result.getString(2);
System.out.print(col1+",");
System.out.println(col2);
}
}
...
So I need your fresh sight what the problem really can be? Any useful comment is appreciated
Please try using ResultSet rs = callableStatement.executeQuery(); instead of the boolean rs=callableStatement.execute(); line.

Categories