One, JDBC development steps
Create a function in the Oracle database
Query the annual salary of the specified employee-use a stored procedure to achieve (pass in the parameter, the second parameter stores the value in the parameter)
parameter: is the employee number
Output: annual salary
create or replace procedure proc_gettotalsal(vempno in number,vtotalsal out number)
is
begin
select sal*12 + nvl(comm,0) into vtotalsal from emp where empno = vempno;
end;
2. Use JDBC to connect to Oracle in Eclipse, and query content through custom functions
1. Create a project project
2. Create a libs file and introduce the corresponding jar into it
3. Create packages and classes
4. Connect to the Oracle database through JDBC and
package com.itzheng.test;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import org.junit.Test;
import oracle.jdbc.driver.OracleTypes;
import oracle.jdbc.oracore.OracleType;
/*
1、导入驱动包
2、第二部注册驱动
3、获取连接
4、获取执行SQL的statement
5、封装参数
6、执行SQL
7、获取结果
8、释放资源
*/
public class TestProcedure {
@Test
public void test1() throws Exception {
//注册驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2、获取连接
//(1)设置对应的参数
String url = "jdbc:oracle:thin:@192.168.75.100:1521:orcl";
String username = "scott";
String password = "tiger";
//(2)获取连接
Connection conn = DriverManager.getConnection(url, username, password);
//prepareCall在执行存储过程之前,必须注册所有OUT参数的类型,他们的值是在执行后通过此类提供的get方法获取的。
//3、获取执行SQL的statement
//这几SQL语句的作用就是调用Oracle当中自定义的函数,一个人为输入参数,第二个为输出参数
String sql = "{call proc_gettotalsal(?,?)}";
CallableStatement state = conn.prepareCall(sql);//通过链接获取对应的statement
//向SQL当中的?设置对应的值 ---设置输入参数
state.setInt(1, 7788);//第一个索引
//注册输出参数将查询到的值放入到OracleTypes,并或 去对应的数字类型
state.registerOutParameter(2, OracleTypes.NUMBER);//第二个位Oracle执行函数返回的结果
//4、执行statement
state.execute();
//5、获取执行结果
int tatalsal = state.getInt(2);
//输出结果
System.out.println("工资:"+tatalsal);
//6、释放资源
state.close();
conn.close();
}
}
Three, JDBC call storage function
@Test
public void test2() throws Exception {
// 注册驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
// 2、获取连接
// (1)设置对应的参数
String url = "jdbc:oracle:thin:@192.168.75.100:1521:orcl";
String username = "scott";
String password = "tiger";
// (2)获取连接
Connection conn = DriverManager.getConnection(url, username, password);
// prepareCall在执行存储过程之前,必须注册所有OUT参数的类型,他们的值是在执行后通过此类提供的get方法获取的。
// 3、获取执行SQL的statement
String sql = "{?=call func_getsal(?)}";
CallableStatement state = conn.prepareCall(sql);
//4、封装参数
//注册返回值类型参数
state.registerOutParameter(1, OracleTypes.NUMBER);//将返回值存储到OracleTypes
//设置第二个参数
state.setInt(2, 7788);
//5、执行SQL
state.execute();
//6、获取结果
int int1 = state.getInt(1);//获取对应的值
System.out.println("年薪"+int1);
//7、释放资源
state.close();
conn.close();
}