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.
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);
I'm trying to get some data from Oracle 11.2 using java and jdbc driver.
My goal is to get data from database using CallableStatement, but with no luck - I'm not able to put table name as parameter. I would like to have configurable table name in query. However, it would be good to keep it sanitized.
Here is an example..
public void getData() throws SQLException {
Connection conn = Config.getSQLConnection();
String query = "SELECT * FROM ?";
PreparedStatement st = conn.prepareStatement(query);
st.setString(1, Config.DATATABLE_NAME);
ResultSet rs = st.executeQuery();
if (rs.next()) {
System.out.println("SUCCESS");
System.out.println("ID:" + rs.getString("ID"));
} else {
System.out.println("FAILURE");
}
}
Is this the way it should work? Or am I missing something, or misused it?
A CallableStatement is used to make call to stored procedures.
From javadoc:
The interface used to execute SQL stored procedures
Use a PreparedStament instead for a normal select.
As an additional note don't pass the name of the table as parameter.
Create the query using concatenation.
Instead of
String query = "SELECT * FROM ?";
use
String query = "SELECT * FROM " + Config.DATATABLE_NAME;
You should use PreparedStatement instead of CallableStatement.
CallableStatement is an interface which is used to call stored procedures.
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
I need to execute this SQL code:
exec ais_disp.p_lk.p_add_client
(v_sis_id => 1640,
v_proc_id => 1,
v_time_start => to_date('01032013 00:00','ddmmyyyy hh24:mi'),
v_time_end => to_date('31032013 23:59','ddmmyyyy hh24:mi'));
select * from ais_disp.v_lk_1;
commit;
And get a ResultList from this query.
I tried to do it like this:
CallableStatement stmt = connection.prepareCall("{call ais_disp.p_lk.p_add_client " +
"(1640,
1,
to_date('01032013 00:00','ddmmyyyy hh24:mi'),
to_date('31032013 23:59','ddmmyyyy hh24:mi'))}");
stmt.execute();
ResultSet rs2 = stmt.executeQuery("select * from ais_disp.v_lk_1");
System.out.println(rs2);
while (rs2.next()){
System.out.println(rs2.getString("LRP_STATUS_NAME"));
}
stmt.close();
But it returns empty ResultSet. What I did wrong?
The database is Oracle database.
UPDATE:
I have added this string to code before stmt.executeQuery("select * from ais_disp.v_lk_1"):
stmt.execute();
But it still returns no rows.
Maybe I need to add somehow select statement in callable statement. So how to do it?
Seems like your CallableStatement has never been executed, first execute your stored procedure:
ResultSet rs = stmt.executeQuery()
Your code executes selects query instead of stored procedure, and the select statement is returning no rows.
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.