使用非常经典的用户scott用户做例子。
根据empno得到员工的工资是多少,使用存储过程实现。
存储过程
create or replace procedure getsalbyid(p_empno in emp.empno%type,p_sal out emp.sal%type) is
v_sal emp.sal%type;
begin
select sal into v_sal from emp where empno=p_empno;
if sql%found then
p_sal:=v_sal;
else
v_sal:=-1;
p_sal:=v_sal;
end if;
end getsalbyid;
Java代码:
1.连接Oracle数据库。
public Connection getConnection(){
Connection conn=null;
try {
Class.forName("oracle.jdbc.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:cissst","scott","tiger");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
2.调用存储过程:
public void getCallableStatement5(){
CallableStatement cs=null;
Connection conn=this.getConnection();
String sql="{call getsalbyid(?,?)}";
try {
conn.setAutoCommit(false);
cs=conn.prepareCall(sql);
cs.setInt(1, 7788);
cs.registerOutParameter(2,Types.INTEGER);
cs.executeUpdate();
int id=cs.getInt(2);
conn.commit();
System.out.println(id);
} catch (SQLException e) {
e.printStackTrace();
}
}