Things to note:
- JDBC begins it's index's at 1, not 0. I.e. The CallableStatement object's methods such as: getObject must have a parameter with a value of at least 1.
- Once the Connection or CallableStatement objects are closed, the ResultSet will be empty. This is because it only exists as long as the database connection is open. Ensure you take your results before these objects are destroyed.
- oracle.jdbc.OracleCallableStatement and java.sql.CallableStatement offer the same outcome in this example. Therefore, I have opted to use the java.sql library.
- The '?' within the prepareCall parameter is a place holder for a parameter. This is populated (in this example) using the registerOutParameter method, declaring it's expected type.
Oracle Stored Procedure
Code Snippet
End of Code Snippet
Java Code
Code Snippet
- // Establishes and returns a new connection to the database
- {
- // Load and register Oracle driver
- // Establish a connection
- }
- // Gets a collection of all accounts within the database
- {
- Collection<Account> accounts = new ArrayList<Account>();
- try
- {
- // Connect
- conn = this.GetConnection();
- // Get ResultSet
- cstmt = conn.prepareCall("{call PACKAGENAME.GET_ACCOUNTS(?)}"); // '?' is a template for our Cursor OUT parameter
- cstmt.registerOutParameter(1, OracleTypes.CURSOR);
- cstmt.execute();
- // Index starts at 1, so we want our first result, which is the Cursor
- // process results one row at a time
- while(rs.next())
- {
- Account acc = new Account(rs.getString(1)); // Account name is the first (and only) result in our Cursor.
- accounts.add(acc); // Add account to our collection of accounts to return
- }
- }
- {
- }
- {
- e.printStackTrace();
- }
- finally
- {
- conn.close();
- cstmt.close();
- }
- return accounts; // Return collection of accounts to caller
- }
- // Account POJO
- public class Account
- {
- {
- this.accountName = accName;
- }
- return this.accountName;
- }
- this.accountName = accountName;
- }
- }
End of Code Snippet
2 comments:
If a result set is returned and cast when using GetObject, it will probably be easier to change lines 27 to 30 to:
ResultSet rs = cstmt.executeQuery();
because executeQuery(); returns a ResultSet object.
Also, you're probably better explicitly calling the column name, e.g.:
rs.getString("ACCOUNT_NAME");
That way you'll be able to change the stored procedure without worrying about changing the index of the row you're after.
I'd also print e.getSQLState() in the catch.
Look this framework (https://code.google.com/p/lindbergframework/). Easy handling of stored procedures and functions, including treatment of cursors automatically.
https://code.google.com/p/lindbergframework/
Post a Comment