'DataBase/Oracle'에 해당되는 글 32건

  1. 2005.10.09 Grouping(), ROLLUP, CUBE Study
  2. 2004.07.13 Oracle에서..MySQL의 desc와 같은 결과 가져오기
  3. 2004.07.13 오라클 특정 테이블의 PK 뽑아내는 쿼리
  4. 2003.09.26 [테스트] 9iR2 에서의 XMLDB사용시와 RDB사용시의 성능테스트와 주의사항 3
  5. 2003.09.26 [ORA-01704] Loading a large XML Document into the Database
  6. 2003.09.26 [소스]Create the CLOB object 1
  7. 2003.09.26 [소스]Loading an XML document into the database using the CLOB object
  8. 2003.09.21 명령어 정리되어져 있는 사이트..
  9. 2003.09.21 [SQL] 순번을 자동으로 메길때 중간에 '0'이 일정자리수 만큼 들어가게 하는 방법
  10. 2003.09.20 [프로시져] 프로시져 사용하는 방법예제
  11. 2003.09.19 [9i XMLQuery] 샘플들... (기억에 남기기.. ㅡㅡ;; )
  12. 2003.09.19 SQL-PLUG이용시 오류:ORA-12154 발생시 체크사항...
  13. 2003.09.09 9i설치후 8080 포트 사용하는 것 바꾸기
  14. 2003.09.08 [오라클] Java and Java Bean APIs for XMLType (자바에서 XMLType사용 방법..)
  15. 2003.09.07 [참고] 오라클에서 XML insert ..
  16. 2003.09.05 XMLType를 sqlplus에서 검색시에 짤려서 보이는거 다 보이게하기...
  17. 2003.09.05 오라클 9i에서 XML Query 예제.. 1
  18. 2003.09.05 오라클에서의 XMLType의 성능상의 논의 (퍼온글)
  19. 2003.09.05 오라클 9iR2이상에서의 XMLTYPE에 데이터 넣는 참고예제..
  20. 2003.08.28 Java and Java Bean APIs for XMLType
  21. 2003.08.28 엑셀과 데이터베이스를 연동하는 tabler(odbc)
  22. 2003.08.28 엑셀과 데이터베이스를 연동하는 tabler(오라클버젼)
  23. 2003.08.28 Oracle9i XML API Reference - XDK and Oracle XML DB
  24. 2003.08.28 Oracle9i Web Services
  25. 2003.08.28 Oracle XML Developer's Kit for Java
  26. 2003.08.28 오라클 Sample Code
  27. 2003.08.28 XML 파일을 PLSQL을 이용해서 CLOB에 저장하는 예제 1
  28. 2003.08.28 INTERMEDIA TEXT - XML 문서 검색 방법
  29. 2003.08.28 OC4J의 DATA-SOURCES.XML 파일 셋업 및 활용
  30. 2003.08.28 OC4J DATA-SOURCES.XML 파일에서 OCI 방식을 이용한 DB 접속 방법

^^ 링크 참조
Posted by 아름프로
mysql의 desc의 결과 내용

Field      |       Type     |       Null     |     Key     |  ....
===================================
             |                    |                  |                |


---------------------------------------------------

select t1.table_name, t1.column_name, t1.data_type, t2.pk, t2.nval
from   (
          select table_name,column_name,sum(pk) pk,sum(nullvalue) nval
          from   (
                    select distinct t2.table_name,t1.column_name,
                        decode(t2.constraint_type,'P',1,0) pk,
                        decode(t2.constraint_type,'C',1,0) NUllvalue
                    from   user_cons_columns t1,user_constraints t2
                    where  t2.constraint_type in ('P','C')
            and    t2.constraint_name = t2.constraint_name
            and    t2.table_name = t1.table_name
            and    t1.owner = t2.owner
            and    t1.table_name = '해당테이블'
            --and    t2.owner = '테이블 유저'
            order by t2.table_name,t1.column_name
          )
          group by table_name,column_name
            ) t2,
            (
            select table_name, column_name, data_type
            from   user_tab_cols
            where  table_name = '해당테이블'
            ) t1
where  t1.column_name = t2.column_name(+)
and    t1.table_name = t2.table_name(+)
Posted by 아름프로

select
a.table_name,
b.column_name
from user_constraints a, user_cons_columns b
where a.constraint_type = 'P'
and a.constraint_name = b.constraint_name
and a.table_name = b.table_name
and a.table_name='MAP_USER_MENU'
Posted by 아름프로
개발을 하면서 성능의 차이가 얼마나 나는지 간단한 테스트를 해봤습니다.

- 조건 : 같은 데이터가 들어 있고 데이터껀수는 911건입니다.
- 네트워크 : 9i설치된 PC에서 테스트 (Local)
- PC사양 : P4-1.6, 512M
- XML 설계에 따른 이슈 : 중요한 요소인데 이 설계 부분은 공개할 수 없기에 생략.
- 방법 : TOAD를 이용하여 SQL을 날리고 그 결과를 TOAD에서 제공되는 결과 속도를 체크.
*편의상 테이블명은 AAA(XMLTable)와 BBB(R)로 한다.


상황1) 칼럼을 하나로 놓고 검색 (20회 반복해서 실행 varchar(20)인)
SELECT extractValue (T.doc,'/MIX/MusicIdentifier/KMID')
FROM AAA T

select kmid
FROM BBB

XMLDB : 100~120 msecs (간혹 큰 숫자 발생)
RDB : 10 msecs

====================================
상황2) 칼럼을 두개로 놓고 검색 (20회 반복해서 실행 varchar(20), varchar2(128)인)

SELECT extractValue(T.doc,'/MIX/MusicIdentifier/KMID'), extractValue(T.doc,'/MIX/Title/OriginalTitle')  
FROM AAA T

select kmid , title
FROM BBB

XMLDB : 200~230 msecs (간혹 큰 숫자 발생)
RDB : 10 msecs

=====================================
상황3) 칼럼을 세개로 놓고 검색 (20회 반복해서 실행 varchar(20), varchar2(128), varchar2(20)인)

SELECT extractValue(T.doc,'/MIX/MusicIdentifier/KMID'),
           extractValue(T.doc,'/MIX/Title/OriginalTitle'),
           extractValue(T.doc,'/MIX/SongDetailInformation/SongMediaInformation/RunningTime')  
FROM AAA T

select kmid , title, runningtime
FROM BBB

XMLDB : 300~320 msecs
RDB : 10 msecs (간혹 20)

=====================================
상황4) 상황3에 WHERE조건으로 검색 추가
SELECT extractValue(T.doc,'/MIX/MusicIdentifier/KMID'),
           extractValue(T.doc,'/MIX/Title/OriginalTitle'),
           extractValue(T.doc,'/MIX/SongDetailInformation/SongMediaInformation/RunningTime')  
FROM AAA T
WHERE extractValue( T.doc,'/MIX/MusicIdentifier/KMID') = '20000520020006'

select kmid , title, runningtime
FROM BBB
WHERE kmid=020000520020006;

XMLDB : 2 secs
RDB : 10 msecs (간혹 20)

==========================================
상황5) 상황3에 WHERE조건으로 검색 추가 (또다른 검색방법)
SELECT extractValue(T.doc,'/MIX/MusicIdentifier/KMID'),
           extractValue(T.doc,'/MIX/Title/OriginalTitle'),
           extractValue(T.doc,'/MIX/SongDetailInformation/SongMediaInformation/RunningTime')  
FROM AAA T
WHERE existsNode( T.doc,'/MIX/MusicIdentifier[KMID="020000520020006"]') = 1

select kmid , title, runningtime
FROM BBB
WHERE kmid=020000520020006;

XMLDB : 2secs
RDB : 10 msecs (간혹 20)

==========================================
상황6) 상황3에 WHERE조건으로 검색 추가 like 검색 (결과값 25개 나옴)
SELECT extractValue(T.doc,'/MIX/MusicIdentifier/KMID'),
           extractValue(T.doc,'/MIX/Title/OriginalTitle'),
           extractValue(T.doc,'/MIX/SongDetailInformation/SongMediaInformation/RunningTime')  
FROM AAA T
WHERE extractValue( T.doc,'/MIX/MusicIdentifier/KMID') like '%20000%'

select kmid , title, runningtime
FROM BBB
WHERE kmid like '%020000%';

XMLDB : 510~550 msecs
RDB : 10~20 msecs

==========================================
상황7) 상황3에 WHERE조건으로 검색 추가 like 검색 + order by 시키기
SELECT extractValue(T.doc,'/MIX/MusicIdentifier/KMID') A,
           extractValue(T.doc,'/MIX/Title/OriginalTitle') B,
           extractValue(T.doc,'/MIX/SongDetailInformation/SongMediaInformation/RunningTime') C
FROM AAA T
WHERE extractValue( T.doc,'/MIX/MusicIdentifier/KMID') like '%20000%'
order by A

select kmid a  , title b, runningtime c
FROM BBB
WHERE kmid like '%020000%';
order by a

XMLDB : 5 secs (5000 msecs)
RDB : 10~20 msecs
==========================================

특이사항
위의 결과는 그래도 '/MIX/Title/OriginalTitle'와 같이 단일 노드(부모자식간)로
구성되었을때 결과는 나오더라도 성능의 차이를 보이는 결과를 가지지만..
아래와 같이..
'/MIX/SongDetailInformation/CorporateInformation/CorporateName'
여기에서 CorporateInformation이 * (0 or 무한대)인 경우를 아래와 같이
검색하면 ...

SELECT extractValue(T.doc,'/MIX/MusicIdentifier/KMID'), extractValue (T.doc,'/MIX/SongDetailInformation/CorporateInformation/CorporateName')
FROM AAA T
WHERE extractValue (T.doc,'/MIX/SongDetailInformation/CorporateInformation/CorporateName') like 'SM기획'
----------------------------------------
ERROR:
ORA-19025: EXTRACTVALUE는 하나의 노드 값만 반환
45 개의 행이 선택되었습니다.
-------------------------------------------
이와 같은 결과를 낸다.

=>
SELECT extractValue(T.doc,'/MIX/MusicIdentifier/KMID'), extractValue (T.doc,'/MIX/SongDetailInformation/CorporateInformation/CorporateName')
FROM doc_xdoclong_km T
WHERE existsNode( T.doc,'/MIX/SongDetailInformation/CorporateInformation[CorporateName="SM기획"]') = 1
이렇게 해결..

============================================
추가1>
SELECT extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsType') a,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsID') b,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/Name') c
FROM doc_xdoclong_km T
로는 값이 나오는데 여기에  ORDER BY 하면
SELECT extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsType') a,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsID') b,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/Name') c
FROM doc_xdoclong_km T
ORDER BY a
----------------------------------------
ERROR:
ORA-19025: EXTRACTVALUE는 하나의 노드 값만 반환
45 개의 행이 선택되었습니다.
-------------------------------------------

==============================================
추가2>
SELECT extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsType') as result,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsID') b,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/Name') c
FROM doc_xdoclong_km T
로 결과 나옴.
그런데 멀티노드가 있는 조건이 붙으면 에러..
- 아래 둘중에 하나 붙으면 에러..
WHERE docid=634

WHERE existsNode(T.doc,'/MIX/SongDetailInformation/RightsInformation[RightsID="01200300073"]') = 1

----------------------------------------
ERROR:
ORA-19025: EXTRACTVALUE는 하나의 노드 값만 반환
45 개의 행이 선택되었습니다.
-------------------------------------------
=============================================
추가>
SELECT extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsType') as result,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsID') b,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/Name') c,
           extractValue(T.doc,'/MIX/Title/OriginalTitle') d
FROM doc_xdoclong_km T
WHERE extractValue(T.doc,'/MIX/Title/OriginalTitle') like '%사랑%'

저작권에서 정보 검색을 위해 사랑이라는 단어가 포함된 검색일 경우
결과가 하나면 제대로 나오고 복수면 ORA-19025에러

---------------------------------------------------------
SELECT extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsType') as result,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsID') b,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/Name') c,
           extractValue(T.doc,'/MIX/Title/OriginalTitle') d
FROM doc_xdoclong_km T
WHERE existsNode(T.doc,'/MIX/Title[OriginalTitle="사랑"]') = 1

이 방식의 경우엔 사랑이라는 단어로의 멀티 결과는 가져오지만,
사랑이 표함된 SQL의 % % 처리를 XPath에서 불가능

SELECT extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsType') as result,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/RightsID') b,
           extractValue(T.doc,'/MIX/SongDetailInformation/RightsInformation/Name') c,
           extractValue(T.doc,'/MIX/Title/OriginalTitle') d
FROM doc_xdoclong_km T
WHERE existsNode(T.doc,'/MIX/Title[starts-with(OriginalTitle, "사랑")]') = 1
이와 같은 편법도 ORA-19025에러 남..
==============================================




***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
Loading a large XML Document into the Database
After completing this snippet you should be able to:

Load large XML documents containing more than 4000 characters into XMLType tables or XMLType columns in the database
IntroductionOracle XML DB is a set of built-in high-performance storage and retrieval technologies developed especially for XML. Oracle XML DB fully absorbs the World Wide Web Consortium (W3C) XML data model into Oracle9i database and provides new standard access methods for navigating and querying XML. You get all the advantages of relational database technology and XML technology at the same time. Oracle XML DB can be used to store, query, update, transform, or otherwise process XML, and access the same XML data using the SQL queries.


In this snippet we are providing PL/SQL approach and JDBC approach for loading large XML documents into XMLType tables or XMLType columns.

Pre-requisites for running the snippetOracle9i database (version 9.2.0.1 and above).

Classes12.zip or Classes12.jar available under the ORACLE_HOMEjdbclib directory should be included in the CLASSPATH environment variable for the JDBC approach.
SQL Script that will create the required database table. Please execute the following SQL before running the code examples.

  CREATE TABLE poTable (purchaseOrder XMLType) ;
Note: For demonstration purpose we have considered loading the XML document into an XMLType column. The same approach can be used for XMLType tables also.

Code SnippetPL/SQL approach
JDBC approach
PL/SQL approachThe correct way of inserting large documents into XMLType column is using a CLOB and not VARCHAR2 since VARCHAR2 can be used to load maximum of 4000 characters only. Instead a CLOB can hold maximum of 4GB characters and can be used to load XML containing more than 4000 characters. If VARCHAR2 is used for inserting large XML document (containing more than 4000 characters) into an XMLType column, a database error "ORA-01704: string literal too long" is encountered. The following example provides a way to solve this problem by using a CLOB to hold the XML document.

The loading of a large XML document is demonstrated using a PL/SQL procedure 'loadPurchaseOrder'. In this procedure a CLOB object 'poXML' is declared to hold the XML content that needs to be stored into the database. The XML will be stored into an XMLType column 'purchaseOrder' of the table 'poTable'. The XML that CLOB object holds is a large XML document containing more than 4000 characters.

CREATE or REPLACE PROCEDURE loadPurchaseOrder IS
  -- Declare a CLOB variable
  poXML CLOB;
BEGIN  
  -- Store the Purchase Order XML in the CLOB variable
  poXML := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
            <PurchaseOrder>
              <PONum>1001</PONum>
              <Company>Oracle Corp</Company>
              .
              .
              .
            </PurchaseOrder>';
  -- Insert the Purchase Order XML into an XMLType column
  INSERT INTO potable (purchaseOrder) VALUES (XMLTYPE(poXML));

--Handle the exceptions
EXCEPTION
  WHEN OTHERS THEN
    raise_application_error(-20101, 'Exception occurred in loadPurchaseOrder procedure :'||SQLERRM);
END loadPurchaseOrder;

PL/SQL procedure similar to the above mentioned example can be used for loading large XML documents into an XMLType column.

Limitation: In PL/SQL, a String constant can take a maximum size of 64K. If an XML document > 64k is to be loaded into the XML DB, the best approach is to load the document from a file. For details on this approach, please refer to the "Oracle XML DB Utilities Package" in the XML DB Sample Corner at /sample_code/tech/xml/xmldb/index.html.

JDBC approachIf a large XML document (typically greater than 4000 characters) is inserted into an XMLType column using a String object in JDBC, the run-time error "java.sql.SQLException: Data size bigger than max size for this type" is encountered. This problem can be solved by using a CLOB object to hold the large XML documents.

The following code demonstrates the loading of large XML documents using Java CLOB Object. The CLOB object is created using oracle.sql.CLOB class on the client side to hold the XML. The oracle.sql.CLOB class is the Oracle JDBC driver's implementation of standard JDBC java.sql.Clob interface.

To load the XML, the first step is to create a CLOB object at the client side that will hold the XML content. Once the CLOB object holding the XML content is created, the next step is to bind the CLOB object to the JDBC prepared statement that is used for insertion of XML data into the XMLType column.

Step 1: Create the CLOB object The following method getCLOB() creates and returns a CLOB object that holds the specified XML data. This method can be used to insert the XML string into the database XMLType column.


Click here to view the code for the getCLOB() method

Step 2: Loading an XML document into the database using the CLOB object.The CLOB object containing the XML needs to be bound to the JDBC prepared statement that is used for the insertion of the data into the XMLType column in the database. Following method insertXML() demonstrates the insertion of an XML data into the XMLType column. This method uses the prepared statement to execute the database query. It makes a call to the getCLOB() method described above to create and return a CLOB object that holds the XML data.

Click here to view the code for the insertXML() method.

ResourcesOracle9i XML Database Developer's Guide - Oracle XML DB
Oracle9i Application Developer's Guide - Large Objects (LOBs)




***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
@param xmlData => Data to be inserted into the XMLType column
@param conn => Database Connection Object (Oracle Connection Object)
@return CLOB Object

...
import oracle.sql.CLOB;
import java.sql.Connection;
import java.sql.SQLException;
import java.io.Writer;
...

private CLOB getCLOB(String xmlData, Connection conn) throws SQLException{
  CLOB tempClob = null;
  try{
    // If the temporary CLOB has not yet been created, create new
    tempClob = CLOB.createTemporary(conn, true, CLOB.DURATION_SESSION);

    // Open the temporary CLOB in readwrite mode to enable writing
    tempClob.open(CLOB.MODE_READWRITE);
    // Get the output stream to write
    Writer tempClobWriter = tempClob.getCharacterOutputStream();
    // Write the data into the temporary CLOB
    tempClobWriter.write(xmlData);

    // Flush and close the stream
    tempClobWriter.flush();
    tempClobWriter.close();

    // Close the temporary CLOB
    tempClob.close();    
  } catch(SQLException sqlexp){
    tempClob.freeTemporary();
    sqlexp.printStackTrace();
  } catch(Exception exp){
    tempClob.freeTemporary();
    exp.printStackTrace();
  }
  return tempClob;
}





***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
@param xmlData => Data to be inserted into the XMLType column
@param conn => Database Connection Object (Oracle Connection Object)

import oracle.sql.CLOB;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
...

private void insertXML(String xmlData, Connection conn) {
  CLOB clob = null;
  String query;
    // Initialize statement Object
  PreparedStatement pstmt = null;
  try{
    query = "INSERT INTO potable (purchaseOrder) VALUES (XMLType(?)) ";
    // Get the statement Object
    pstmt = conn.prepareStatement(query);

    // xmlData is the string that contains the XML Data.
    // Get the CLOB object using the getCLOB method.
    clob = getCLOB(xmlData, conn);
    // Bind this CLOB with the prepared Statement
    pstmt.setObject(1, clob);
    // Execute the Prepared Statement
    if (pstmt.executeUpdate () == 1) {
    System.out.println ("Successfully inserted a Purchase Order !");
    }
  } catch(SQLException sqlexp){
    sqlexp.printStackTrace();
  } catch(Exception exp){
    exp.printStackTrace();
  }
}



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
명령어 정리되어져 있는 사이트..



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
우선 시퀀스 넘버는 시퀀스 테이블을 사용해서 자동증가하는데
그 값이 AA000001,AA000002 이케 들어가야 합니다
가운데 그 빈자리만큼 0을 넣는 것을 어떻게 처리해야 하는지
알고 싶습니다
==================================
insert into table_name(col1)
values ( 'AA' || to_char(sequence_name.nextval,'000000') );

SELECT to_char(nvl(max(seq),0)+1, '00000') FROM temp_kcinfo WHERE ctype='01'



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
conn.setAutoCommit(false);
CallableStatement cstmt = conn.prepareCall(sql);
for (int i=1 ; i <= 10 ; i++) {
cstmt.clearParameters();
cstmt.setInt(1, i);                                
cstmt.setString(2, request.getParameter("name"+i) );
cstmt.executeQuery();

}
conn.commit();
conn.setAutoCommit(true);




***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
SELECT T.doc.extract('/MIX/Title/OriginalTitle/text()').getStringVal()    
FROM doc_xdoclong_km T
WHERE docid=646        

SELECT extractValue(T.doc, '/MIX/Title/OriginalTitle'),
           extractValue(T.doc, '/MIX/MusicIdentifier/KMID'),
           extract(T.doc, '/MIX/SongDetailInformation/RightsInformation').getStringVal()  
FROM doc_xdoclong_km T
WHERE docid=646

SELECT extract(T.doc, '/MIX').getStringVal()  
FROM doc_xdoclong_km T
WHERE docid=481

SELECT extract(T.doc, '/MIX/SongDetailInformation/RightsInformation/RightsType').getclobval() as result1,
           extract(T.doc, '/MIX/SongDetailInformation/RightsInformation/RightsID').getclobval() as result2,
           extract(T.doc, '/MIX/SongDetailInformation/RightsInformation/Name').getclobval() as result3
FROM doc_xdoclong_km T

SELECT T.doc.getClobVal() FROM doc_xdoclong_km T where docid=646

SELECT T.doc.extract('/MIX/Title/OriginalTitle/text()').getStringVal()    
FROM doc_xdoclong_km T
WHERE docid=646



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
network/admin
에 tnsnames.ora 쪽에 이상이 없는데도 계속해서 ORA-12154
에러가 발생되면..
sqlnet.ora 파일에 보면..

NAMES.DEFAULT_DOMAIN =

요부분이 설정되어 있으면

#NAMES.DEFAULT_DOMAIN =

이것을 막아보시고 해보세요.
그럼 잘 됩니다.

이것 때문에 20분 고생했네요.. 훔..



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
^^

1. 프로그램그룹-OracleHome92-?-'Database configuration assistant 실행
2. 수행하고자 하는 작업선택 화면에서 '데이터베이스의 데이터베이스 옵션구성' 을 선택
3. 옵션을 구성하고 자하는 DB를 선택(아마 설치시에 DB생성 하신걸로 가정)
4. '데이터베이스 기능창'에서 '표준데이터베이스 기능' 이라는 버튼클릭 하고 '사용자정의' 버튼클릭
5. 그러면 'Oracle XML DB'창이 뜨는데 그창 하단에 '포트번호' 바꾸시고 '확인'버튼 누르고 적용
6. 3으로 돌아가서 목록에 있는 다른 DB를 선택하고 같은 작업 3-5까지 수행

여기 적어놓은 것은 포트를 변경 시킨다는 것이구요, 포트를 아예 안쓰고 싶다면
5번 단계에서 'XML 프로토콜 비활성화'를 체크하심 됩니다. 보다 강력한 방법은
XML DB OPTION을 제거 하는 것이겠지요?!! ^-^

Oracle XML DB와 포트설정에 관련되서 아주 자세히 알 고 싶으시면
"XML Database Developer s Guide - Oracle XML DB"이 책의 21장
"Configuring Oracle XML DB with Enterprise Manager"을 참고 하세욤.




***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
자바에서 XMLType사용 방법..입니다.
어렵게 어렵게 구해지네요..
에공..




***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
다른곳에 있는 에러가 났다는 내용을 게시물인데
일단 이러한 방식으로 처리가 되기도 한다는 모습을 보이는거 같아서
붙여놔 봅니다.
시간되면 함 테스트 해봐야겠네요.
그럼 이만.. ^^

===============================================

---------- java ----------
java.lang.NoClassDefFoundError: oracle/jdbc2/Clob
at testInsert.main(testInsert.java:9)
Exception in thread "main"
출력 완료 (1초 경과) - 정상 종료

OracleXMLSave sav = new OracleXMLSave(conn, "scott.emp");

위 라인입니다.
위와 비슷한 소스 몇개의 테스트를 해도 계속 위

OracleXMLSave 에서  실행시 에러발생합니다..

자르 화일도 분명 있구요 클래스도 혹시 풀어서 같은 폴더에도 저장을 한후에
실행을 하여도

여전히 같은 에러가 나옵니다.

고수님들의 조언을 부탁드립니다.  



===================================
clob_test .java
===================================
import oracle.xml.sql.dml.*;
import java.sql.*;
import oracle.jdbc.driver.*;
import oracle.jdbc.*;
import java.net.*;
import oracle.xml.sql.dml.OracleXMLSave;

public class clob_test extends Object {
  public static void main(String args[]) throws SQLException
  {
    String tabName = "xml_test";                   // table into which to insert
    String fileName = "i:/xml_test/xml_insert.xml";            
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn =
  DriverManager.getConnection
("jdbc:oracle:thin:@127.0.0.1:1521:take","scott","password");
    OracleXMLSave sav = new OracleXMLSave(conn, tabName);
URL url = sav.getURL(fileName);
    int rowCount = sav.insertXML(url);
    System.out.println(" successfully inserted "+rowCount+ " rows into "+ tabName);
    conn.close();
  }
}

=============================================
xml : xml_insert.xml
=============================================




            

                           7369

                           SMITH

                           STUDENT

            

            

                           7499

                           ALLEN

                           SALESMAN

            

            

                           7521

                           WARD

                           SALESMAN

            



=============================================
xml_test.sql
=============================================
create table xml_test(

  2  empno number,

  3  ename varchar2(20),

  4  job clob);

=============================================
제가 가진 패스 화일
=============================================
D:>set classpath
CLASSPATH=.;D:Program Filesj2sdk_nbj2sdk1.4.2lib ools.jar;E:oracleora90j
dbclibclasses12.zip;i:OracleXSU111libxsu111.jar;i:OracleXSU111libxmlpars
erv2.jar;E:oracleora90oem_webstageoraclesysmanvtm hin;D:Program
FilesOracleInventoryComponents;
==============================================

물론 : jar 화일은 /자바홈/jre/lib/ext 에 조심스럽게
가져다 놓았구요 ...
컴파일은 아무 이상이 없이 잘 됩니다.
실행시 위와 같은 에러가 나옵니다.

고수님의 고견을 듣고 싶습니다.
흑흑흑 지금 몇일째 ....
읽어오기는 잘 합니다.





***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
아래와 같이 실행한 후에 select를 하면 됩니다.
9999라는 값은 상황에 따라서 변화를 주면 됩니다.

SQL>SET LONG 9999
SQL>select ... ~~



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
SELECT docid FROM doc_xdoclong_ka T WHERE extractValue( T.doc,'/AIX/AlbumIdentifier/KAID') = '11746'

SELECT docid  FROM doc_xdoclong_ka T
where existsNode( T.doc,'/AIX/AlbumIdentifier[KAID=11746]') = 1
and existsNode( T.doc,'/AIX/AlbumContributor[AlbumContributorName="신해철"]') = 1


SELECT docid,extractValue (T.doc,'/AIX/AlbumIdentifier/KAID') as result0 ,
           extractValue (T.doc,'/AIX/AlbumInformation/Title/OriginalTitle') as result1 ,
           extractValue (T.doc,'/AIX/AlbumContributor/AlbumContributorName') as result2  
FROM doc_xdoclong_ka T where existsNode(T.doc,'/AIX/AlbumIdentifier[KAID=11746]') = 1
and existsNode( T.doc,'/AIX/AlbumContributor[AlbumContributorName="신해철"]') = 1

select * from KAInfo where kaid='11746'



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
안그래도 이 부분에 대한 것이 궁금했는데..
정확하지는 않지만 관련 글이 있어서 붙여봅니다.
보는데로 더 살을 붙이도록 하죠.
-----------------------------------------------------------------------------
9i에서부터 XMLType을 지원하고 있는것으로 압니다.
하지만 document에 보면 XMLType의 사용법만 나와있을뿐 실제로 어느정도 XML문서를 빠르게 search할수 있는지 또 저장된 XML문서 수정시 수정된부분만 변경하는 것인지 아니면 interMedia처럼 전체 XML문서를 삭제하고 다시 insert하는것인지 이러한 성능에 관한 언급은 못본것 같습니다.

이러한 XMLType의 성능면에서 XMLtype을 논하고 싶습니다. document에서는 view를 만들면 다른 컬럼 select하는 것과 마찬가지로 XML문서를 search할수 있다고 하지만 성능역시 다른(XMLType이 아닌컬럼)과 같은지를 알고 싶습니다.
-----------------------------------------------------------------------------
개인적인 의견입니다.

xmltype이 얼마나 빠르게 search할 수 있는지
속도에 관해서는 별로 말할게 없을 것 같네요..

추측으로는 xml관련 연산에 맞게 크게 최적화된게 아니라
xmltype이란 것 자체가, xdk for pl/sql이 단순결합된 타입이겠죠..

사용자에게 오라클의 xml지원을 알리기 위한 시간이 너무나 짧아서,
사용자들이 dbxml package등의 사용법과 습득을 귀찮아해서
기존의 것에 얹는식으로 개발했기 때문에.. 이런 등의 이유가 있겠죠..

수정시 수정된 부분만 변경하는게 아니라 전체를 변경합니다.
문서 전체를 읽어들인 뒤에 다시 씁니다.
이건 xmltype의 효율성의 문제가 아니라,
xml data를 설계할 당시 부적합한 설계의 문제라고 봐야겠죠..

xmltype의 성능이란 건, 통으로 document를 프로세싱하는 연산에 관해서
다른 방식과 비교하면 언뜻생각해도 가장 나은 성능을 보이겠구나 싶죠..
(비교해보지 않아도 직관적으로 생각할 때 얻을 수 있는 답이라 생각합니다.

어쨌든 9i의 xml지원은 mssql,db2보다는 사용법이 매우직관적이고,
고수준까지 지원되게 되어 있다는 것만은 사실이고,
xmltype은 통연산에 관한한 가장 나은 퍼포먼스를 보일겁니다...^^
(누가 프로세싱타임 비교좀 해주시는게..^^
(최근엔 오라클을 쓰고 싶어도 role이 바뀌어서 말이죠.. T-T



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
public static void main(String args[]) throws Exception
{
        Connection conn = null;
        OraclePreparedStatement stmt = null;
        InputStream in = null;

        try {
                DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                conn = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:ORa92", "xmldb", "xmldb");
                in = new java.io.FileInputStream("D:\xmldir\po.xml");
                String statment = "insert into tb_doc_table values(1,?)";
                stmt = (OraclePreparedStatement)conn.prepareStatement(statment);
                oracle.sql.CLOB clob = createCLOB(conn,in);
                XMLType xt = XMLType.createXML(conn,clob);
                stmt.setObject(1, xt);
                int k = stmt.executeUpdate();
                conn.commit();
                System.out.println(k);
        }catch(SQLException e) {
                int errorCode = e.getErrorCode();
                System.out.println("ERROR_CODE = " + errorCode);
                e.printStackTrace();
                if(conn != null) { try{ conn.rollback(); }catch(Exception exc) { exc.printStackTrace(); } }
        }finally{
                if(stmt != null) { try{ stmt.close(); }catch(Exception exc) { exc.printStackTrace(); } }
                if(conn != null) { try{ conn.close(); }catch(Exception exc) { exc.printStackTrace(); } }
        }
}



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
Java and Java Bean APIs for XMLType




***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
엑셀과 데이터베이스를 연동하는 tabler(odbc)



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
엑셀과 데이터베이스를 연동하는 tabler(오라클버젼)



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
Oracle9i XML API Reference - XDK and Oracle XML DB



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로

Oracle9i Web Services

2003. 8. 28. 16:33
Oracle9i Web Services



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
Oracle XML Developer's Kit for Java



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로

오라클 Sample Code

2003. 8. 28. 16:30
샘플들 있는 곳입니다.




***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
    
                
No. 20161

XML 파일을 PLSQL을 이용해서 CLOB에 저장하는 예제
================================================



PURPOSE
-------

간단한 xml 문서를 PLSQL을 이용해서 database 에
저장하고 PLSQL parser 를 이용해 validate 하는 방법을
예제를 통해 알아 봅니다.


Example
-------

Step1
-----

xml 문서를 저장할 table 을 생성합니다.

CREATE TABLE xml_doc (
docname    VARCHAR2(100) PRIMARY KEY,
doc        CLOB,
insertdate DATE DEFAULT SYSDATE);


Step 2
------

XML 문서는 os 의 physical directory 에 있으므로 oracle database
에 logical directory 를 만들어 mapping 시켜주어야 합니다.

SQL> CREATE DIRECTORY xmldocs AS 'C:XML';


만일 ORA-1031 에러가 발생할 경우 SYS 또는 SYSTEM user 로 접속해서
다음 명령으로 권한을 줍니다.

SQL> grant create any directory to scott;
Grant succeeded.


Step 3
------

database 에 넣을 XML 문서를 만듭니다.

<!--emp.xml -->
<EMPTABLE>
  <EMPLOYEE ENAME="Scott">
    <EMPNO>7844</EMPNO>
    <JOB>Manager</JOB>
    <SAL>100000</SAL>
  </EMPLOYEE>
  <EMPLOYEE ENAME="King">
    <EMPNO>100</EMPNO>
    <JOB>President</JOB>
    <SAL>200000</SAL>
  </EMPLOYEE>
</EMPTABLE>


위에서 만든 emp.xml 파일을 db 에 insert 할 PLSQL procedure 를 생성합니다.


CREATE OR REPLACE PROCEDURE insertXML (dirname IN VARCHAR2,
                                      filename IN VARCHAR2)
IS
  xmlfile BFILE;
  myclob  CLOB;
BEGIN
  INSERT INTO xml_doc (docname, doc)
  VALUES (filename, empty_clob())
  RETURNING doc into myclob;  
  
  -- get a handle to the xml file on the OS
  xmlfile := Bfilename(dirname,filename);

  -- open the file
  DBMS_LOB.fileOpen(xmlfile);

  -- copy the contents of the file into the empty clob
  DBMS_LOB.loadFromFile(myclob, xmlfile, dbms_lob.getLength(xmlfile));

END insertXML;
/

Execute the Procedure

SQL> EXEC insertXML('XMLDOCS', 'emp.xml');

PL/SQL procedure successfully completed.



Step 4
------

insert 된 data 를 확인해 봅니다.

SQL> select * from xml_doc;

DOCNAME         DOC                                      INSERTDATE
--------------- ---------------------------------------- ---------------
emp.xml         <!--emp.xml -->
                         27-OCT-00
                <EMPTABLE>                  
                  <EMPLOYEE ENAME="Scott">                                
                    <EMPNO>7844</EMPNO>

Reference Documents
-------------------
NOTE:123491.1
    
           



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
    
                
No. 17052

INTERMEDIA TEXT - XML 문서 검색 방법
====================================



PURPOSE
-------
XML 형식의 문서를 Intermedia text 를 통해 어떻게 검색할 수 있는 지
알아보자.



Explanation
-----------
Intermeida text 에서는 XML_SECTION_GROUP과 AUTO_SECTION_GROUP 을
통해서 XML 문서의 검색을 실행할 수 있다. 이 두 가지 GROUP에 대해
확인해 보자.


1. XML_SECTION_GROUP

Oracle 8.1.6 intermedia text 부터 xml 지원이 강화되어
XML_SECTION_GROUP 의 기능이 향상되었다. 다음과 같은 기능들을 이용할
수 있다.

(1) 이름공간을 이용하여 서로 다른 DTD 의 태그들을 구분할 수 있다.
  => 구분된 태그에 대해 질의어가 가능하다 .

EX) ctx_ddl.add_field_section('my_section_group','section_name','tag_name');

(2) XML 속성 (Attribute)에 대해서 인덱스를 생성할 수 있고
  속성의 값을 이용하여 검색할 수 있다 .

EX) ctx_ddl.add_attr_section('my_section_group','section_name','tag_name@attr_name');

(3) XML 문서가 변경된 경우, 예를 들어 새로운 태그가 추가되거나 새로운
  doctype 으로 변경되는 경우, 인덱스를 재구축하지 않고 새로운 섹션를
  추가할 수 있다 .

EX) alter index <index_name> rebuild parameters
       ('add (zone|field) section <section_name> tag <tag_name>');

(4) XML 내의 한글 검색이 지원된다.


2. AUTO_SECTION_GROUP

8.1.6 에서는 XML 검색을 위한 AUTO_SECTION_GROUP 이 새롭게 추가되었다.
AUTO_SECTION_GROUP은 XML_SECTION_GROUP과 비슷하지만 다른 점은 섹션
(section)을 미리 정의하지 않아도 non-empty 태그가 자동적으로 태그와
같은 섹션이름을 가지고 zone section 으로 인덱싱된다는 점이다.

예를 들어, 다음의 XML 문서를 보자.

<book>
<author>Neal Stephenson</author>
<title>The Diamon Age</title>
<description> Decades into our future...</description>
</book>

위 예에서 auto sectioner는 book, author, title, description 의 이름을
가진 zone section 을 생성하게 되어 "diamond within description"과
같은 질의어 처리를 가능하게 된다.
여기서 주의할 점은 섹션 이름이 case-insensitive 하다는 점이다. XML에서
태그 이름은 case-sensitive 하기 때문에 "diamond within description"과
"diamond within DESCRIPTION" 은 차이가 있어야 함에도 불구하고 위 두개의
질의어가 같이 취급된다.

AUTO_SECTION_GROUP은 모든 태그들에 대해 인덱싱을 하기 때문에 실제로
질의에 사용되지 않은 태그들에 대해서는 인덱싱을 할 필요가 없다.
이를 위해서 다음과 같이 add_stop_section 을 사용한다 .

ctx_ddl.add_stop_section(‘mysg’,’author’)

또는

alter index <index name> rebuild
parameters (‘add stop section author’)

을 사용할 수 있다.



Example
-------
1. Test Script 1

rem -----------------------------------------------
rem 이름 충돌이 발생하지 않도록 section 을 만든 경우
rem -----------------------------------------------

set echo on
drop table xmlsect;

create table xmlsect(
id number(5) primary key,
text varchar2(200) );

set define off

insert into xmlsect values (1, '<!DOCTYPE contact> <contact>
<address>506 Blue Pool Road</address> <email>dudeman@radical.com</email>
</contact>');

insert into xmlsect values (2, '<!DOCTYPE mail> <mail> <address>
dudeman@radical.com </address></mail>');

commit;
set echo on
drop index xmlsect_idx;

exec ctx_ddl.drop_section_group('my_xml_section_group');
begin
ctx_ddl.create_section_group ('my_xml_section_group','xml_section_group');
ctx_ddl.add_field_section ('my_xml_section_group','email','email');
ctx_ddl.add_field_section ('my_xml_section_group','address','address');
ctx_ddl.add_field_section ('my_xml_section_group','email','(mail)address');
end;
/

create index xmlsect_idx on xmlsect ( text )
indextype is ctxsys.context
parameters ( 'section group my_xml_section_group' );


위의 스크립트는 이름공간을 이용하여 서로 다른 DTD 의 태그들을 구분할 수
있는 예를 보인 것이다. 따라서, 다음의 질의 처리 시 email section 내의
'radical'을 모두 찾아 주게 된다.

select * from xmlsect where contains (text, 'radical within email') > 0;



2. Test script 2:

rem ------------------------------------------------------------
rem Attribute 를 가진 경우와 Attribute 에 한글을 포함한 경우의 시험
rem ------------------------------------------------------------

set echo on
drop table xmlsect;

ctx_ddl.drop_preference('my_han_pref');

create table xmlsect(
id number(5) primary key,
text varchar2(200) );

set define off

rem (1) Normal Attribute 의 경우 --> OK
rem insert into xmlsect values ( 1,
rem '<comment author="jeeves"> I really like InterMedia Text </comment>');
rem (2) Attribute 가 한글 일 경우 --> OK
rem insert into xmlsect values ( 2,
rem '<comment 작가 ="jeeves"> I really like InterMedia Text </comment>');
rem (3) Attribute 가 한글 일 경우 --> OK

insert into xmlsect values ( 3,
'<comment 작가 ="제임스 "> I really like InterMedia Text </comment>');
commit;

set echo on
drop index xmlsect_idx;

exec ctx_ddl.drop_section_group('my_xml_section_group');
begin
ctx_ddl.create_section_group ( 'my_xml_section_group', 'xml_section_group');
-- (1)의 remark 가 제거된 경우
-- ctx_ddl.add_attr_section('my_xml_section_group', 'author', 'comment@author');
-- (2)와 (3)의 remark 가 제거된 경우
ctx_ddl.add_attr_section ( 'my_xml_section_group', '작가 ', 'comment@작가 ');
end;/

rem KOREAN_LEXER 를 사용하면 한글 처리에 있어 유사형태의 한글 token 을 생성해준다 .
rem exec ctx_ddl.create_preference('my_han_pref','KOREAN_LEXER');

create index xmlsect_idx on xmlsect ( text )
indextype is ctxsys.context
parameters ( 'section group my_xml_section_group');

rem 한글 LEXER 를 사용할 때 위의 ctx_ddl.create_preference('my_han...')의 remark 제거
rem parameters ( 'section group my_xml_section_group lexer my_han_pref' );

XML 속성 (Attribute)에 대해서 인덱스를 생성할 수 있고 속성의 값을
이용하여 검색할 수 있는 예를 보인 스크립트이다. 그리고, 한글일 경우에
대해서도 함께 테스트를 해 보았다. 따라서 아래의 질의어 수행이 가능하다.

¨ 위의 Test script1 에서 (1)의 경우
rem select * from xmlsect where contains (text, 'jeeves within author') > 0;

¨ 위의 Test script1 에서 (2)의 경우
rem select * from xmlsect where contains (text, 'jeeves within 작가 ') > 0;

¨ 위의 Test script1 에서 (3)의 경우
rem select * from xmlsect where contains (text, '제임 within 작가 ') > 0;


3. Test script 3

rem --------------------------------------------------------
rem 이름 충돌이 발생하지 않도록 section 을 만든 경우
rem --------------------------------------------------------

set echo on
drop table xmlsect;

create table xmlsect(
id number(5) primary key,
text varchar2(200) );

set define off

insert into xmlsect values (
1, '<!DOCTYPE contact> <contact> <address>506 Blue Pool Road</address>
<email>dudeman@radical.com</email></contact>');
commit;

set echo on
drop index xmlsect_idx;

exec ctx_ddl.drop_section_group('my_xml_section_group');
begin
ctx_ddl.create_section_group ( 'my_xml_section_group', 'xml_section_group');
ctx_ddl.add_field_section ( 'my_xml_section_group', 'email', 'email');
ctx_ddl.add_field_section ( 'my_xml_section_group', 'address', 'address');
end;
/


create index xmlsect_idx on xmlsect ( text )
indextype is ctxsys.context
parameters ( 'section group my_xml_section_group' );

insert into xmlsect values (
2, '<!DOCTYPE contact> <contact><title>Hello World</title> <address>BSKO
</address><email>bsko@oracle.com</email></contact>');

alter index xmlsect_idx rebuild
parameters ('add field section mytest tag title');

select token_text from dr$xmlsect_idx$i;
select * from xmlsect where contains (text,'Hello within title')>0;


XML 문서가 변경된 경우, 예를 들어 새로운 태그가 추가되거나 새로운
doctype 으로 변경되는 경우, 인덱스를 재구축하지 않고 새로운 섹션을
추가할 수 있다. 위의 스크립트는 이미 XMLSECT_IDX 인덱스를 만든 상태에서
XML 문서에 새로운 태그인 'title'을 추가한 예이다. 물론, 태그의 변경사항
은 인덱스가 이미 구성된 문서에 대해서는 적용되지 않는다 .



Reference Documents
-------------------
Oracle8i Intermedia Text Reference Manual

    
           



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
    
                
No. 12237

OC4J의 data-sources.xml 파일 셋업 및 활용
========================================

/* OC4J(Oracle Container For J2EE)는 IAS 1.0.2.2 에서부터
제공되는 J2EE Container로, 현재 모든 J2EE Spec 1.2 및 1.3
Spec 일부를 지원하고 있다. J2EE에 관한 추가 정보는 Sun
Homepage에서 찾아볼 수 있다. 본 document는 oc4j 1.0.2.2
version을 기준으로 작성되었다.
/*

data-sources.xml 파일은 JDBC 2.0 확장 API인 dataSource
Object를 지원하기 위해 OC4J에서 제공하는 configuration
파일 이다.

dataSource Object를 이용함으로써 동일한 logical name으로
Standard Connection 및 Connection Pooling을 이용한
Connection, 둘 다를 얻어 사용할 수 있으며, DB 관련 정보들이
변경되는 경우가 발생하더라도 data-sources.xml 파일 안에 해당
내용을 반영해주면 소스 레벨의 수정없이 프로그램이 동작하는 것등
많은 장점이 있다.

일반적으로 필드에서 Connection Pooling을 다루는데
엔지니어가 가장 골머리를 썩는 부분은 다음과 같은 프로그램
실수 및 환경이다.

- connection을 획득한 후 release하지 않는다.
- release된 connection을 같은 jsp에서 다시 사용한다.
- 한번 cache된 connection이 물리적인 오류로 끊어진 경우,
이를 복구할 방법이 없다.

일반적으로 현재 존재하는 DB Connection Pooling driver에는
위의 문제에 대한 명확한 해답을 가지고 있는 것이 없는 관계로,
개발자의 이런 문제를 회피하려는 노력이 무엇보다도 중요하다.

일단 본 자료에서는 OC4J에서 제공하는 DB Connection Pooling을
활용하는 방법과 그 사용 샘플 코드를 살펴보겠다.

1. data-sources.xml 파일
1.1. 위치 : $OC4J_HOMEconfig
1.2 내용 :
<data-source
  class="com.evermind.sql.DriverManagerDataSource"
  name="OracleDS"
  location="jdbc/OracleDS"
  pooled-location="jdbc/pooled/OracleDS"
  xa-location="jdbc/xa/OracleDS"
  ejb-location="jdbc/ejb/OracleDS"
  connection-driver="oracle.jdbc.driver.OracleDriver"
  min-connections="5"
  max-connections="25"
  inactivity-timeout="360000"
  username="scott"
  password="tiger"
  url="jdbc:oracle:thin:@152.69.42.30:1521:ora817"
/>
1.3. entry 내용 설명 :
  location <= Standard Connection Object를 얻어내기 위한 logical name
  pooled-location <= Pooled Connection으로부터 Connection을 얻어내기
  위해 기술하는 logical name
  username/password : db의 schema명과 password
  url : db 접속을 위한 jdbc url string.

* location entry는 일반적인 connection을 활용할 때 참조하기 위해
entry이고, pooled-location 부분이 connection pooling을 활용할 때
참조되는 entry이며, 이름은 임의의 유일한 값이 부여되면 된다.

1.4. 코드에서 DataSource 참조하는 방법은 다음과 같다.

<html>
<body>
<%@ page contentType="text/html;charset=EUC-KR"%>
<%@ page import="java.util.*, java.sql.*, javax.sql.*, javax.naming.InitialContext" %>

<%
InitialContext ic = null;
DataSource ds = null;
Connection conn = null;
String mydate = null;
Statement stmt = null;
ResultSet rset = null;

try {
  ic = new InitialContext();
  ds = (DataSource) ic.lookup("jdbc/pooled/OracleDS"); <= pooled-location entry의 값.
  conn = ds.getConnection();
  stmt = conn.createStatement();
  rset = stmt.executeQuery("select sysdate from dual");
  rset.next();
  mydate = rset.getString(1);
%>

Current Server Date = <%= mydate %> <br>
<%
} catch (Exception e) {
%>
Exception : <%= e %>
<%
} finally {
  if (rset != null) try { rset.close(); } catch (Exception e) {}
  if (stmt != null) try { stmt.close(); } catch (Exception e) {}
  if (conn != null) try { conn.close(); } catch (Exception e) {}
}
%>
</body>
</html>

=> resultSet, Statement, Connection object에 대해서는 finally 구문
안에서 close를 시켜주어야 한다. 그렇지 않고 일반 block에서
close를 하는 경우에는 runtime error 발생시 해당 object가 반환되지
않는 문제에 접할 수 있다.




    
           



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로
    
                
No. 12238

oc4j data-sources.xml 파일에서 oci 방식을 이용한 db 접속 방법
===========================================================

1. oci를 이용한 connection이 가능한지 여부를 확인하기 위한 사전작업

1.1. sql*net 8.1.7 이상이 설치되어 있는지 확인

1.1.2 환경변수 설정
=> sql*net 8.1.7 이상이 설치되어 있는 경우 OS가 win32 계열의 경우
ocijdbc8.dll 파일이 있는 위치가 OS의 Path 환경변수 값에 잡혀 있어야 합니다.
Unix 계열의 경우는 libocijdbc8.so 파일이(일반적으로 $ORACLE_HOME/lib 위치에
있습니다.)  os user의 환경변수인 LD_LIBRARY_PATH에 잡혀 있어야 합니다.

1.1.3. oci-thin jdbc driver 파일 셋업
=> $OC4J_HOME/lib 디렉토리 아래에 있는 classes12.jar 파일은 백업후
해당 위치에서 삭제하시고, 8.1.7용 jdbc driver인 classes12.zip 파일과 nls_charset12.zip
파일을 $OC4J_HOME/lib 위치에 카피하시기 바랍니다.
(두 개의 파일은 첨부파일로 보내드립니다.)

1.1.4 data-sources.xml 파일 수정
=> 다른 entry는 적절하게 세팅하시고 url 항목을 oci에 맞게 수정하시기 바랍니다.
( ex) url="jdbc:oracle:oci8:@ora817")

1.1.5 oc4j startup 후 테스트해보시기 바랍니다.

    
           



***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 16:49)
Posted by 아름프로

BLOG main image

카테고리

분류 전체보기 (539)
이야기방 (19)
토론/정보/사설 (16)
IBM Rational (9)
U-IT (0)
SOA/WS/ebXML (110)
개발방법론/모델링 (122)
J2SE (34)
J2EE (60)
DataBase (39)
MS-SQL (0)
MySQL (1)
DB2 (0)
PostgreSQL (1)
SAPDB (0)
miniSQL (0)
Informix (0)
Sybase (0)
LDAP (0)
Access (1)
Derby (1)
공통 (3)
Oracle (32)
Open Projects (30)
BP/표준화 (50)
Apache Projects (15)
Web/보안/OS (22)
Tools (7)
AJAX/WEB2.0 (1)
Linux/Unix (1)
영어 (0)
비공개방 (0)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

달력

«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

글 보관함

Total :
Today : Yesterday :