반응형

오늘 불현듯...

User Define Cursor 에 대한 부분이 궁금해 졌다...

자바에서 오라클 패키지 호출하여 커서값을 반환하여 자유 스럽게 사용했는데

그 커서 값을 오라클에서 받아서 해볼까 하는...

사실 cursor is 구문이라던지 직접 사용했지

그동안 cursor 반환은 무관심 했었다..

방법은...

즉,  커서 out 값에  l_cursor에 받아와서

3개의 select 한 값을 return 하는데... 각 값들의 속성을 l_ename, l_empno, l_deptno 로 fetch 하여 받아가지고 옴...

참고용

SET SERVEROUTPUT ON SIZE 1000000
DECLARE
  TYPE REF_CUR IS REF CURSOR;
  l_cursor REF_CUR;
  l_ename   emp.ename%TYPE;
  l_empno   emp.empno%TYPE;
  l_deptno  emp.deptno%TYPE;
BEGIN
  get_emp_rs (p_deptno    => 30,
              p_recordset => l_cursor);
            
  LOOP 
    FETCH l_cursor
    INTO  l_ename, l_empno, l_deptno;
    EXIT WHEN v_cursor%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(l_ename || ' | ' || l_empno || ' | ' || l_deptno);
  END LOOP;
  CLOSE l_cursor;
END;
/


출처 :  http://www.oracle-base.com/articles/misc/UsingRefCursorsToReturnRecordsets.php 




Using Ref Cursors To Return Recordsets

Since Oracle 7.3 the REF CURSOR type has been available to allow recordsets to be returned from stored procedures and functions. Oracle 9i introduced the predefined SYS_REFCURSOR type, meaning we no longer have to define our own REF CURSOR types. The example below uses a ref cursor to return a subset of the records in the EMP table.

The following procedure opens a query using a SYS_REFCURSOR output parameter. Notice the cursor is not closed in the procedure. It is up to the calling code to manage the cursor once it has been opened.

CREATE OR REPLACE
PROCEDURE get_emp_rs (p_deptno    IN  emp.deptno%TYPE,
                      p_recordset OUT SYS_REFCURSOR) AS 
BEGIN 
  OPEN p_recordset FOR
    SELECT ename,
           empno,
           deptno
    FROM   emp
    WHERE  deptno = p_deptno
    ORDER BY ename;
END GetEmpRS;
/

The resulting cursor can be referenced from PL/SQL as follows.

SET SERVEROUTPUT ON SIZE 1000000
DECLARE
  l_cursor  SYS_REFCURSOR;
  l_ename   emp.ename%TYPE;
  l_empno   emp.empno%TYPE;
  l_deptno  emp.deptno%TYPE;
BEGIN
  get_emp_rs (p_deptno    => 30,
              p_recordset => l_cursor);
            
  LOOP 
    FETCH l_cursor
    INTO  l_ename, l_empno, l_deptno;
    EXIT WHEN v_cursor%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(l_ename || ' | ' || l_empno || ' | ' || l_deptno);
  END LOOP;
  CLOSE l_cursor;
END;
/

The cursor can be used as an ADO Recordset.

Dim conn, cmd, rs

Set conn = Server.CreateObject("adodb.connection")
conn.Open "DSN=TSH1;UID=scott;PWD=tiger"

Set cmd = Server.CreateObject ("ADODB.Command")
Set cmd.ActiveConnection = conn
cmd.CommandText = "get_emp_rs"
cmd.CommandType = 4 'adCmdStoredProc

Dim param1
Set param1 = cmd.CreateParameter ("deptno", adInteger, adParamInput)
cmd.Parameters.Append param1
param1.Value = 30

Set rs = cmd.Execute

Do Until rs.BOF Or rs.EOF
  -- Do something
  rs.MoveNext
Loop

rs.Close
conn.Close
Set rs     = nothing
Set param1 = nothing
Set cmd    = nothing
Set conn   = nothing

The cursor can also be referenced as a Java ResultSet.

import java.sql.*;
import oracle.jdbc.*;

public class TestResultSet  {
  public TestResultSet() {
    try {
      DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
      Connection conn = DriverManager.getConnection("jdbc:oracle:oci:@w2k1", "scott", "tiger");
      CallableStatement stmt = conn.prepareCall("BEGIN get_emp_rs(?, ?); END;");
      stmt.setInt(1, 30); // DEPTNO
      stmt.registerOutParameter(2, OracleTypes.CURSOR); //REF CURSOR
      stmt.execute();
      ResultSet rs = ((OracleCallableStatement)stmt).getCursor(2);
      while (rs.next()) {
        System.out.println(rs.getString("ename") + ":" + rs.getString("empno") + ":" + rs.getString("deptno")); 
      }
      rs.close();
      rs = null;
      stmt.close();
      stmt = null;
      conn.close();
      conn = null;
    }
    catch (SQLException e) {
      System.out.println(e.getLocalizedMessage());
    }
  }

  public static void main (String[] args) {
    new TestResultSet();
  }
}
If you are using a version of Oracle before 9i, then create the following package and replace any references to SYS_REFCURSOR with TYPES.cursor_type.
CREATE OR REPLACE PACKAGE types AS 
  TYPE cursor_type IS REF CURSOR;
END Types; 
/
Hope this helps. Regards Tim... 
반응형

'Database > ORACLE' 카테고리의 다른 글

Automatic SQL Tuning in Oracle Database 10g  (0) 2012.07.20
10G OCP 자격증 관련  (2) 2012.07.08
일정 시간 별로 쿼리 정보 조회  (0) 2012.02.20
오라클 병렬 인덱스 조회 및 수정하기  (0) 2012.01.27
AWR Report 정리본  (0) 2011.09.28
반응형


- 이클립스 상에서 오라클 DATABASE를 바로 연결하여 사용하는 방법을 기술한다.

설치에 사용된 이클립스...




Help -> SoftWare Update를 클릭


1. Add Site를 누름 

2.http://quantum.sourceforge.net/update-site/ (Location) 부분에 입력

3. OK를 클릭

4. Quantum 을 검색 한뒤

5. Install 버튼 클릭



6. NEXT를 클릭


7. 사용 조건에 승인하고 Finish 를 클릭 -> 설치 완료
  
    - 아래와 같이 설치가 완료되어 다시 시작한다는 메시지가 뜨면 YES를 누르고 이클립스를 다시 시작함.
  


8. 이클립스 상에서 Quantum 플러그인 추가

window -> open Perspective -> other



9. Other open Perspective 화면에서 Quantum DB를 선택함.


10. 정상적으로 설치되었음을 확인할 수 있다.(연결정보 설정은 당연히 현재는 안되어 있음)

11. 연결 정보를 다음과 같이 추가함.
Database Bookmarks 탭상에서 빈공간에서 마우스 우클릭 -> New Bookmark... 클릭


12.  ADD driver을 눌러 추가하자 ! (우리는 오라클을 추가할 것이다.)



13. Add External Jar.. 늘 눌러 ojbc14.jar를 추가함.


14. 아래와 같이 정보를 설정하고 Finish를 누름



15. 입력한 Oracle 드라이버를 선택후 Next> 를 클릭


16. 다음과 같이 DB 연결 정보를 입력
     userid : 연결ID
     passwd : 연결ID의 암호
     HOSTNAME : DB서버 주소
     PORT : 오라클 리스너 포트(일반적으로 1521)
     DATABASE NAME : SID NAME


17. 북마크에서 사용할 이름을 지정함


18. 17번까지의 설정을 모두 마치면 자동으로 연결되고(정보가 틀리지 않았다면)
     Quantum SQL Queries View상에서 쿼리를 입력후 초록색 ▶ 버튼을 누르면 하단의 Quantum Table View 상에서 데이터가 조회됨.





P.$ :
1. MySql 연결시에는 mysql-connector-java-5.1.6-bin.jar 파일을 다운받음
2. 드라이버 선택 -> com.mysql.jdbc.Driver
3. 연결 포트는 3306임.
반응형

+ Recent posts