oracle jdbc引用存储过程和函数

public class TestOracle {
    private static String url="jdbc:oracle:thin:@//127.0.0.1:1521/orcl";
    private static String username="system";
    private static String password="oracle";
    private static String driverClass="oracle.jdbc.driver.OracleDriver";
    @Test
    public void test() throws Exception {
        Class.forName(driverClass);
        Connection conn= DriverManager.getConnection(url,username,password);
        System.out.println(conn);
        Statement sm=conn.createStatement();
        String sql="select * from scott.emp";
        ResultSet rs=sm.executeQuery(sql);
        while (rs.next()){
            System.out.println(rs.getString("empno")+"-"+rs.getString("ename"));

        }
        rs.close();
        sm.close();
        conn.close();


    }

    @Test
    public void testProcedure() throws Exception {
        Class.forName(driverClass);
        Connection conn= DriverManager.getConnection(url,username,password);
        String sql="{call get_emp_by_eno_proc(?,?,?)}";//调用函数的sql语句
        CallableStatement csm=conn.prepareCall(sql);
        //设置动态参数
        csm.setString(1,"7369");
        csm.registerOutParameter(2, OracleTypes.VARCHAR);//出参2
        csm.registerOutParameter(3, OracleTypes.VARCHAR);//出参3
        csm.execute();//执行存储过程
        String ename=csm.getString(2);
        String dname=csm.getString(3);
        System.out.println("查询结果:"+ename+","+dname);
        csm.close();
        conn.close();
    }

    @Test
    public void testFunction() throws Exception {
        Class.forName(driverClass);
        Connection conn= DriverManager.getConnection(url,username,password);
        String sql="{?=call get_longesthired_emp()}";
        CallableStatement csm=conn.prepareCall(sql);
        csm.registerOutParameter(1,OracleTypes.CURSOR);//出参
        csm.execute();//执行函数
        ResultSet rs=((OracleCallableStatement)csm).getCursor(1);//第一个出参按游标类型获取
        while (rs.next()){
            System.out.println(rs.getString("ename")+"-"+rs.getString("入职天数"));
        }
        csm.close();
        conn.close();

    }
}

测试:

7369-SMITH
7499-ALLEN
7521-WARD
7566-JONES
7654-MARTIN
7698-BLAKE
7782-CLARK
7788-SCOTT
7839-KING
7844-TURNER
7876-ADAMS
7900-JAMES
7902-FORD
7934-MILLER

你可能感兴趣的:(Oracle,oracle)