Friday, November 28, 2014

Executing database Procedures and functions: CallableStatement

Procedure:
 create or replace procedure getSalary(id IN number, sal OUT number)
 as
 --Global variables goes here
 BEGIN
 select salary into sal from employees where employee_id=id;
 END getSalary;
 /

Function:
create or replace function getAverageSal(id1 IN number, id2 IN number) return number
as
sal1 number;
sal2 number;
BEGIN
  select salary into sal1 from employees where employee_id=id1;
  select salary into sal2 from employees where employee_id=id2;
  
  return (sal1+sal2)/2;
END getAverageSal;
/

JDBC Program:
package com;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Types;

public class CallableStTest {
Connection con = null;
String dbDriver = "oracle.jdbc.driver.OracleDriver",
dbUrl = "jdbc:oracle:thin:@localhost:1521:xe", dbUser = "HR",
dbPwd = "HR";

public CallableStTest() throws Exception {
Class.forName(dbDriver);

con = DriverManager.getConnection(dbUrl, dbUser, dbPwd);
}

public void callProcedure() {
CallableStatement cst = null;
ResultSet rs = null;

try {
cst = con.prepareCall("{call getSalary(?, ?)}");

cst.setInt(1, 106);
cst.registerOutParameter(2, Types.FLOAT);

cst.execute();

System.out.println(cst.getFloat(2));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (cst != null)
cst.close();
if (rs != null)
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

public void callFunction() {
CallableStatement cst = null;
ResultSet rs = null;

try {
cst = con.prepareCall("{?=call GETAVERAGESAL(?,?)}");

cst.setFloat(2, 100);
cst.setFloat(3, 101);

cst.registerOutParameter(1, Types.FLOAT);

cst.execute();

System.out.println(cst.getFloat(1));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (cst != null)
cst.close();
if (rs != null)
rs.close();
if(con != null)
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

static public void main(String[] args) throws Exception {
CallableStTest test = new CallableStTest();

test.callProcedure();
test.callFunction();
}
}

No comments:

Post a Comment