I am trying to call a stored function in Java. Function has no package, it's placed under user (schema) USER and returns a cursor. I tried twoways to call it and none of these works.
First one
Query query = coreDao.getEntityManager().createNativeQuery("{call USER.gen_rephead_sm_task_report(?, ?) }");
query.setParameter(1, dateFrom);
query.setParameter(2, dateTo);
List<?> queryResult = query.getResultList();
I got a not a procedure or not defined
I also tried this approach with
select gen_rephead_sm_task_report(?, ?) from dual
as a createNativeQuery parameter but with the same result.
Second one
Connection connection = dataSource.getConnection();//javax.sql.DataSource
CallableStatement statement = connection.prepareCall("{? = call USER.gen_rephead_sm_task_report(?, ?) }");
statement.registerOutParameter(1, OracleTypes.CURSOR);//oracle.jdbc.OracleTypes
statement.setDate(2, new java.sql.Date(dateFrom.getTime()));
statement.setDate(3, new java.sql.Date(dateTo.getTime()));
statement.executeQuery();
ResultSet set = ((OracleCallableStatement) statement).getCursor(1);
I got the ClassCastException on the last line (obviously OracleCallableStatement doesn't implement the CallableStatement). So which types shoud I use here?
Ok, so I found a link which solves my problem (iDevelopment). Here is what I used
connection = dataSource.getConnection();
CallableStatement statement = connection.prepareCall(TIMESHEET_QUERY);
statement.registerOutParameter(1, OracleTypes.CURSOR);
statement.setDate(2, new java.sql.Date(dateFrom.getTime()));
statement.setDate(3, new java.sql.Date(dateTo.getTime()));
statement.execute();
ResultSet set = (ResultSet) statement.getObject(1);
Everything is straight from javax.sql.* so there is no need for Oracle Specific API.
Related
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);
why we use setInt with select query instead of using getInt when value is already there in database?
try {
conn = getConnection();
ps = conn.prepareStatement("SELECT * FROM circle where id =?");
ps.setInt(1, circleId);
Circle circle = null;
rs = ps.executeQuery();
if (rs.next()) {
//String s = rs.getString(circleId);
circle = new Circle(circleId, rs.getString("name"));
}
You're setting the value of the parameter to be used in the query. The ? in the SQL represents the parameter, and here you're giving it a value.
When you call getString() later, that's getting a value from the results of the query, which are very different from the parameters sent as part of the query.
Parameterized SQL allows safe inclusion of values into queries, without needing to escape them to prevent SQL injection attacks, or worrying about data type conversions. You should read the JDBC PreparedStatement tutorial for more details.
i want to pass another database to the stored procedure in java
like
call Sel_RptDaywiseProduction(?)
how to pass DIERP database in this SP in java in callable statement
please help
thank you.
Edit: code from the comment
CallableStatement cs = con.prepareCall("{call Sel_RptDaywiseProduction(?)}");
cs.setString(1, "DIERP");
ResultSet rs1 = cs.executeQuery();
while (rs1.next()) {
System.out.println("mat_code = ");
}
I'm trying to execute a stored procedure without input variables like :
String sql2 = "{call vivek}" ;
System.out.println(sql2);
System.out.println("Executing procedure without parameters");
stmt = conn.createStatement();
stmt.executeQuery(sql2);
But its throwing an error saying :
syntax error at or near "{"
Position: 1
I'm trying to google it but not able to find anything. How do I do it ? By the way it didn't work with callablestatement also
Not tested:
CallableStatement cs = null;
cs = conn.prepareCall("{call vivek}");
cs.executeQuery();
http://docs.oracle.com/javase/tutorial/jdbc/basics/storedprocedures.html
It's similar to calling a function without arguments.
CallableStatement cat = null;
con = YourConnectionClass.getConnection();
cst = con.prepareCall("{call YOUR_PROCEDURE_NAME()}");
cst.executeQuery();
Could not find stored procedure? I will explain what it means when you get this error. Assuming our code is like this:
String sp="{call GetUnitReferenceMap}";
stmt=conn.prepareCall(sp);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
currencyMap.put(rs.getString(1).trim(), rs.getString(2).trim());
I have 4 DBs (sample1, sample2, sample3), but stmt will search location master (Default DB) then we will get an Exception.
We should provide DB name, then problem will be resolved::
String sp="{call sample1..GetUnitReferenceMap}";
Thanks for the help everyone but the following code worked for me :
sql2 += "{exec "+ proc_name2 +"}" ;
cstmt = conn.prepareCall(sql2);
cstmt.executeUpdate();
Here cstmt is the CallableStatement object by the way. And I'm using Postgresql Database hence the above code worked for me
Im trying to write sample stored functions in postgresql and call them using the CallableStatement offered by JDBC.
Here's some my test code
Consumer bean =new Consumer();
CallableStatement pstmt = null;
try {
con.setAutoCommit(false);
String query = "{ ? = call getData( ? ) }";
pstmt = con.prepareCall(query);
pstmt.registerOutParameter(1, Types.OTHER);
pstmt.setInt(2,5);
pstmt.execute(); // execute update statement
bean=(Consumer)pstmt.getObject(1);
System.out.println("bean"+bean.getConsumer_name());
And my Stored function is of the form .
CREATE FUNCTION getData(int) RETURNS SETOF db_consumer AS $$
SELECT * FROM db_consumer WHERE consumer_id = $1;
$$ LANGUAGE SQL;
However, I'm getting the following error when I try to run the code .
org.postgresql.util.PSQLException: A CallableStatement was executed with an invalid number of parameters .
Any idea why this could be happening?
I don't think you need a CallableStatement as you should be able to run select * from getData(5) directly:
PreparedStatement pstmt = con.prepareStatement("select * from getData(?)")
pstmt.setInt(1,5);
ResultSet rs = pstmt.execute();
while (rs.next()) {
System.out.println(rs.getString(1));
}
You are trying to call a SETOFF function via a Callable Statement. That's not going to happen! You'll always get an error.
PostgreSQL's stored functions can return results in two different ways. The function may return either a refcursor value or a SETOF some datatype. Depending on which of these return methods are used determines how the function should be called.
Functions that return data as a set should not be called via the CallableStatement interface, but instead should use the normal Statement or PreparedStatement interfaces.