You are on page 1of 2

CallableStatement example - Creating a procedure with input and output parameter s import java.sql.*; import java.util.

Properties; public class CallableStatementExample2 { public static void main(java.lang.String[] args) { // Register the Native JDBC driver. If we can't // register the driver, the test can't continue. try { Class.forName("com.ibm.db2.jdbc.app.DB2Driver"); // Create the connection properties Properties properties = new Properties (); properties.put ("user", "userid"); properties.put ("password", "password"); // Connect to the local iSeries 400 database Connection c = DriverManager.getConnection("jdbc:db2://*local", prop erties); Statement s = c.createStatement(); // Create a procedure with in, out, and in/out parameters. String sql = "CREATE PROCEDURE MYLIBRARY.SQLSPEX2 " + "(IN P1 INTEGER, OUT P2 INTEGER, INOUT P3 INTEGER) " + "LANGUAGE SQL SPECIFIC MYLIBRARY.SQLSPEX2 " + "EX2: BEGIN " + " SET P2 = P1 + 1; " + " SET P3 = P3 + 1; " + "END EX2 "; try { s.executeUpdate(sql); } catch (SQLException e) { // NOTE: We are ignoring the error here. We are making // the assumption that the only reason this fails // is because the procedure already exists. Other // reasons that it could fail are because the C compiler // is not found to compile the procedure or because // collection MYLIBRARY does not exist on the system. } s.close(); // Prepare a callable statement that we will use to execute the proc edure. CallableStatement cs = c.prepareCall("CALL MYLIBRARY.SQLSPEX2(?, ?, ?)"); // All input parameters must be set and all output parameters must // be registered. Notice that this means we have two calls to make // for an input output parameter. cs.setInt(1, 5); cs.setInt(3, 10); cs.registerOutParameter(2, Types.INTEGER);

cs.registerOutParameter(3, Types.INTEGER); // Execute the procedure cs.executeUpdate(); // Verify the outupt parameters have the desired values. System.out.println("The value of P2 should be P1 (5) + 1 = 6. --> " + cs.getInt(2)); System.out.println("The value of P3 should be P3 (10) + 1 = 11. --> " + cs.getInt(3)); cs.close(); // close the CallableStatement object c.close(); // close the Connection object. } catch (Exception e) { System.out.println("Something failed.."); System.out.println("Reason: " + e.getMessage()); e.printStackTrace(); } } }

You might also like