5

I am trying to call a procedure defined with a PL/SQL package in a Java program.

I am aware one can call stored procedures using connection.prepareCall in Jdbc. But there is very little information out there on how to call a procedure within a package.

I am at a stage in development where i am still considering what db framework to use. Just wondering what are the pros and cons of using JDBC for PLSQL ? For this usecase are there better alternatives to JDBC ?

1 Answer 1

7

Follow the simple steps below:

public static final String SOME_NAME = "{call schema_name.org_name_pkg.return_something(?,?)}"; // Change the schema name,packagename,and procedure name. // Simple JDBC Connection Pooling // Here I am passing param companyId which is IN param to stored procedure which will return me some value. Connection conn = null; CallableStatement stmt = null; ResultSet rset = null; try { conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password"); stmt = conn.prepareCall(SOME_NAME);//We have declared this at the very top stmt.setString(1, companyid);//Passing CompanyID here stmt.registerOutParameter(2, OracleTypes.CURSOR);//Refcursor selects the row based upon query results provided in Package. stmt.execute(); rset = (ResultSet) stmt.getObject(2); while (rset.next()) { String orgId=rset.getString("RPT_ORG_ID"); // When using refcursor easy to get the value just by using Column name String orgName=rset.getString("RPT_ORG_NAME"); // Some Logic based what do you want to do with the data returned back from query } catch (Exception e) { LOGGER.error("Error extracting ", e); } finally { DBUtils.cleanUp(conn, stmt, rset); } // Clean and close you connection 
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks !! You seem to be using Apache's DbUtils. Is there a specific reason for using it over plain Jdbc.
Sorry, I copied from my own working project. Please Ignore that and I have updated the code. You need to add little code such as try and catch block and to clean and close connection. Hope you don't mind hard interpretation.
It's a very safe practice to use pl/sql over exposing sql directly in java code. Secondly, using pl/sql you don't have to make call to db multiple times which makes it quicker.
Seems like jdbc is a low level API , there are other high level API's like EJB , hibernate or JPA. Can i for instance use JPA or Hibernate to call PL/SQL procedures. I mean PL/SQL being oracle's procedural language.
That's right there are various API's alternative to JDBC. Well it all depends upon your project architecture,framework and the requirements.I hope the above code snippet helps if you are using jdbc.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.