Java中調用Oracle中的預存程序的單元測試代碼

來源:互聯網
上載者:User

Oracle中的預存程序:

/*

建立一個儲存函數,返回指定員工的姓名,薪水和年度營收

*/

create or replace function queryEmp2(eno in number, empname out VARCHAR2,empsal out NUMBER)

--返回年度營收

return NUMBER

as

begin

  select ename,sal into empname, empsal from emp where empno=eno;

  --返回年度營收

  return empsal*12 + nvl(empsal,0);


end;

/

調用上面的預存程序的單元測試:

package demo;


import java.sql.CallableStatement;

import java.sql.Connection;

import java.sql.DriverManager;


import org.junit.Test;


public class Demo {

@Test

public void testQueryEmpl() throws Exception {

//註冊驅動

Class.forName("oracle.jdbc.OracleDriver");

//注意如果連接埠不是1521時,這時要給他改掉。

String url = "jdbc:oracle:thin:@localhost:1521:orcl";

//預設使用的是orcale中的使用者scott

String user = "scott";

//scott的使用者名稱和密碼是tiger

String password = "tiger";

//調用預存程序。

String sql = "{call queryEmpl2(?,?,?)}";


Connection conn = DriverManager.getConnection(url,user,password);

CallableStatement call = conn.prepareCall(sql);


//賦參數值

call.setInt(1, 7839);

//對於out參數

//下面的方法是告訴輸出的資料的參數類型,即Oracle中的varchar類型。

call.registerOutParameter(2, oracle.jdbc.OracleTypes.VARCHAR);

call.registerOutParameter(3, oracle.jdbc.OracleTypes.NUMBER);


//執行

call.execute();

//取結果,獲得名字和薪水

String name = call.getString(2);

double sal = call.getDouble(3);


System.out.println(name + " " + sal);


//關閉資源

call.close();

conn.close();

}

}

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.