使用JDBC调用Oracle的函数详解

1.Oracle的函数

--练习:查询指定员工的年薪:(年薪=月收入*12+comm-奖金)(使用函数)
create or replace function fun1(v_classid in varchar2)
       return number
as
       --定义两个变量
       v_salary classinfo.salary%TYPE;
       v_comm classinfo.comm%TYPE;

begin
       --查询指定员工的月薪和奖金
       select salary,comm into v_salary,v_comm from classinfo where classid=v_classid;
       return v_salary*12+v_comm;
end;
/

 

2.JDBC调用Oracle的函数的Java代码

package cn.itcast.function;

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

public class Main {
	
	public static void main (String[] args) throws Exception{
		
		//加载驱动
		Class.forName("oracle.jdbc.OracleDriver");
		
		//获取连接对象
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "SCOTT", "Root123");
		
		//创建执行存储过程的语句对象
		CallableStatement call=conn.prepareCall("{? =call findClassinfoYearSal(?,?,?)}");
		
		//设置参数类型
		call.registerOutParameter(1, oracle.jdbc.OracleTypes.NUMBER);
		call.setString(2, "003");
		call.registerOutParameter(3, oracle.jdbc.OracleTypes.VARCHAR);
		call.registerOutParameter(4, oracle.jdbc.OracleTypes.NUMBER);
		
		//执行
		call.execute();
		
		//获取数据
		double yearsal=call.getDouble(1);
		String v_name=call.getString(3);
		int v_sal=call.getInt(4);
		
		System.out.println("员工:"+v_name+"的月薪是:"+v_sal+",年收入是:"+yearsal);
		
		//释放资源
		call.close();
		conn.close();
		
	}

}

 

你可能感兴趣的:(Oracle)