개인정보 문제가 대두되어서 운영이 아닌 테스트에서는 실제 이름과 주민번호를 넣지 말라는 방침이 내려왔다.

주민번호 뒷자리 7자리만 '1234567' 로 update 를 하려고 한다.

update [테이블명]
set
[주민번호컬럼명]=substr([주민번호컬럼명],1,6)  || '1234567'


Posted by 쭌쓰파파
,


## LONG TYPE을 LOB TYPE으로 CONVERSION하는 방법(TO_LOB) ##

Bulletin no 12143 참고


Oracle8 부터 LONG이나 LONG RAW Type과는 별도로 LOB Type이 추가 되었습니다.

LONG 이나 LONG RAW Type을 CLOB 또는 BLOB Type으로 변경하기 위해서는 Oracle8에서는
데이타를 다시 입력해야 했지만, 오라클 8i부터는 TO_LOB Function을 이용해서 Long Type의 Data를 LOB Type으로 쉽게 Conversion할 수 있습니다.

TO_LOB Function은 보통 CREATE TABLE .. AS SELECT .. 문장이나
INSERT INTO .. SELECT .. 문장을 이용해서 쉽게 사용 할 수 있습니다.



[예제1] LONG Type의 데이타를 CLOB Type으로 옮기는 방법
아래의 예제에서 Type만 LONG RAW와 BLOB으로로 바꾸어도 가능 합니다.


-- 마이그레이션 테스트를 위한 long컬럼을 가지는 테이블을 생성 합니다.
SQL>CREATE TABLE long_data (
c1 NUMBER,
c2 LONG);

테이블이 생성되었습니다.


-- 테이블의 확인
SQL> DESC long_data

Name Null? Type
----------- ------ ----
C1 NUMBER
C2 LONG


-- 샘플 데이터를 입력 합니다.
SQL>INSERT INTO long_data
VALUES (1, 'This is some long data to be migrated to a CLOB');
1 개의 행이 만들어졌습니다.

SQL>INSERT INTO long_data
VALUES (2, 'long컬럼을 clob으로 마이그레이션 하기 위한 테스트 데이터 입니다.');
1 개의 행이 만들어졌습니다.


-- clob로 마이그레이션 하는 테이블을 생성 합니다.
SQL>CREATE TABLE test_lobs(
c1 NUMBER,
c2 CLOB);

테이블이 생성되었습니다.


-- 테이블의 확인
SQL> DESC test_lobs
Name Null? Type
----------- -------- ----
C1 NUMBER
C2 CLOB


-- LONG타입의 데이터를 CLOB타입의 데이터로 변환
SQL>INSERT INTO test_lobs
SELECT c1, to_lob(c2)
FROM long_data;
2 개의 행이 만들어졌습니다.


-- 변환된 데이터를 확인 합니다.
SQL> SELECT c2 FROM test_lobs;

C2
-----------------------------------------------------------------
This is some long data to be migrated to a CLOB
long컬럼을 clob으로 마이그레이션 하기 위한 테스트 데이터 입니다.





[예제2] LONG Type을 CLOB Type으로 바꾸어 Table 생성하는 방법


-- 새로운 테이블을 생성하면서 기존의 LONG Type의 데이터를 CLOB Type의 데이터로 변환합니다.
SQL>CREATE TABLE clob_data
AS SELECT c1, to_lob(c2) c2
FROM long_data;
테이블이 생성되었습니다.


-- 데이터를 확인해 보세요..
SQL> SELECT c2 FROM long_data;




[예제3] LONG RAW Type을 BLOB Type으로 바꾸어 Table 생성하는 방법


-- image_data테이블에 LONG RAW컬럼이 있다고 가정을 하면은
SQL> DESC image_data
Name Null? Type
------------------------------- -------- ----
C1 NUMBER
C2 LONG RAW


-- 아래의 예제와 같이 테이블을 생성하면서 쉽게 blob Type으로 변환 할 수 있습니다.
SQL>CREATE TABLE blob_data
AS SELECT c1, to_lob(c2) c2 FROM image_data;


================================================
* 오라클 정보공유 커뮤니티 oracleclub.com
* http://www.oracleclub.com
* http://www.oramaster.net
* 운영자 : 김정식 (oramaster _at_ naver.com)
================================================
※ oracleclub 강좌를 다른 홈페이지에 퍼가실 경우에는 출처를 꼭 밝혀 주시면 고맙겠습니다.~^^

Posted by 쭌쓰파파
,

Oracle 8.1.6 에서 테스트 해 본 쿼리이다.

함수를 이용하여 항상 랜덤하게 정렬을 할 수 있다.

select  *

from table_name
where code = '01'
order by dbms_random.value
 

Oracle 내에서 생성하는 임의의 수를 바탕으로 뽑아진 데이터를 랜덤하게 정렬한다.

위의 예제는 code 가 "01" 인 데이터들을 임의의 순서로 정렬하는 예제이다.

이벤트 응모자들을 랜덤하게 당첨하는 프로그램을 궁리해보다가 사랑넷에서 찾아낸 예제.


select mod(abs(dbms_random.random),99) + 1 from dual


↑ 이건 랜덤하게 0~99까지의 숫자중 하나를 뽑아서 +1 을 하여 보여주는 예제.

Posted by 쭌쓰파파
,

출처 : http://noct.pe.kr/noctbbs/ncontent.php?code=info&number=115&page=1&keyfield=&key=

[jsp][펌] pstmt에서 like에 bind variable 붙이기

from okjsp.pe.kr powerbox님 팁
powerbox 2003-10-07 11:34:58

[간단팁] pstmt에서 like에 bind variable 붙이기
ex) Oracle...

select *

from user

where name like '%이%'

=> 보통 stmt쓸때죠...


select *

from user

where name like '%?%'

=> ORA-01006: bind variable does not exist

?는 반드시 '' 밖에 존재해야 합니다.


select *

from user

where name like '%'||?||'%'

=> 오케바리~

Posted by 쭌쓰파파
,


오라클에서 rownum 과 index 칼럼을 사용하여
72000건 이상의 테이블에서 제일 마지막 페이지를 가져오는 쿼리


SELECT {$칼럼들} FROM
(
   SELECT ROWNUM AS RNUM, {$칼럼들} FROM
   (
      SELECT /*+ INDEX_DESC (board_description SYS_C005873) */ {$칼럼들} FROM board_description
   )
   WHERE ROWNUM <= 72220
)
WHERE RNUM > 72210  and RNUM <= 72220


index 칼럼을 이용하지 않을 때는 INDEX가 들어가는 쿼리 부분을 칼럼들을 가져오는 쿼리문으로 바꿔서 가상의 테이블을 생성.

Posted by 쭌쓰파파
,

원문 발췌 :
http://javaservice.net/~java/bbs/read.cgi?m=qna&b=qna2&c=r_p_p&n=1087876976

제목 : Re: Clob은 empty_clob()함수를 이용해 초기화 해야 합니다.
글쓴이: 이승배(telarin) 2004/06/21 06:49:20 조회수:376 줄수:8
CLOB형의 데이터들은 별도의 저장공간에 저장되기 때문에..
핸들이 좀 특이합니다.

INSERT INTO test(testcode, content) VALUES('test1', empty_clob());
또는
UPDATE test SET content = test_clob() WHERE testcode = 'test1';

이런식으로요..
제목 : Re: 오라클 Clob 타입 selec시에 데이터가 없을때는 수행되지 않게끔 하시면 됩니다.
글쓴이: 송원만(nitto182) 2004/06/22 13:02:56 조회수:1256 줄수:318
select시에 데이터가 없을때를 대비하여 아래와 같이 if문에서 Reader가 null인지 체크
하여 주시면 될것입니다.

참고로 아래소스는 ClobUtil이라는 별도의 유틸리티 클래스를 이용하고 있는 모습니다.
(특별히 이렇게 분리 시키지 않아도 되지만 많이 사용되는만큼 분리시키시는게 편리
할것입니다.)

또한 아래 참조 소스는 clob data가 여러컬럼일때 작업하는 방법도 함께 예제로 넣었습니다.
많은 참고가 되었으면 합니다.




[ClobUtil클래스 (※전체소스는 첨부파일 참조)]

public class ClobUtil{

...
    public static String getClobOutput(Reader input) throws IOException,Exception{
        return getClobOutput(input, 4096);
    }

    public static String getClobOutput(Reader input, int buffer_size) throws IOException,Exception{

        if(input != null){  // 이부분이 Reader가 null인지 체크하는 부분
            try{
                StringBuffer output = new StringBuffer();
                char[] buffer = new char[buffer_size];
                int byteRead;

                while((byteRead=input.read(buffer, 0, buffer_size)) != -1){
                    output.append(buffer, 0, byteRead);
                }
                input.close();
                return output.toString();
            }catch(Exception e){// Trap SQL and IO errors
                throw new Exception("getClobOutput() Fail !!");    // runtime 에러시 화면에 찍힘.
            }
        }else{
            return "";
        }
    }
/*
            다른방법1 (oracle 권장 (sample sorce중에서))
            // Open a stream to read Clob data
            Reader src = p_clob.getCharacterStream();

            // Holds the Clob data when the Clob stream is being read
            StringBuffer l_suggestions = new StringBuffer();

            // Read from the Clob stream and write to the stringbuffer
            int l_nchars = 0; // Number of characters read
            char[] l_buffer = new char[10];  //  Buffer holding characters being transferred

            while ((l_nchars = l_clobStream.read(l_buffer)) != -1) // Read from Clob
                l_suggestions.append(l_buffer,0,l_nchars); // Write to StringBuffer

            l_clobStream.close();  // Close the Clob input stream

*/

...

}


[특정클래스에서]

import java.sql.*;
import java.io.*;
import java.util.*;
import oracle.sql.*;                // CLOB 때문
import oracle.jdbc.driver.*;        // OracleResultSet...때문
import common.db.DBConnHandler;
import common.utils.ClobUtil;       // CLOB 때문

public class EntpDB {


    // 여러개의 clob data를 insert하는 예제
    public boolean insert(EntpRec entity) throws SQLException,IOException,Exception{

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        StringBuffer sb = new StringBuffer(300);
        boolean rtn = false;

        try{
            db = new DBConnHandler();
            conn = db.getConnection();
            conn.setAutoCommit(false);
            sb.append(" INSERT INTO TEST_TABLE ");
            sb.append(" (id,class_code,content_1,content_2,content_3,cre_user_id,cre_dt) ");
            sb.append(" VALUES((Select NVL(MAX(id), 0)+1 id FROM TEST_TABLE),?,empty_clob(),empty_clob(),?,sysdate) ");
            pstmt = conn.prepareStatement(sb.toString());
            pstmt.setInt(1, entity.class_code);
            pstmt.setString(2, entity.cre_user_id);

            if(pstmt.executeUpdate()>0){
                pstmt.close();
                sb.setLength(0);
                sb.append(" SELECT content_1,content_2,content_3 FROM TEST_TABLE ");
                sb.append(" WHERE (id=(SELECT NVL(MAX(id), 0) id FROM TEST_TABLE)) ");
                sb.append(" FOR UPDATE");
                pstmt = conn.prepareStatement(sb.toString());
                rs = pstmt.executeQuery();

                while(rs.next()){
                    CLOB clob = ((OracleResultSet)rs).getCLOB(1);
                    Writer writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_1);

                    clob = null;
                    writer = null;
                    clob = ((OracleResultSet)rs).getCLOB(2);
                    writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_2);


                    clob = null;
                    writer = null;
                    clob = ((OracleResultSet)rs).getCLOB(3);
                    writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_3);
                }
/*
                (예전에 직접처리하던방식-불편함)
                ...
                pstmt.close();
                sb.setLength(0);
                sb.append("select bd_body_1,bd_body_2 from board_table where id=? for update");
                pstmt = conn.prepareStatement(sb.toString());
                pstmt.setInt(1, boardRec.getBd_seq);
                rs = pstmt.executeQuery();

                while(rs.next()){
                    CLOB clob = ((OracleResultSet)rs).getCLOB(1);
                    Writer writer = clob.getCharacterOutputStream();
                    Reader src = new CharArrayReader((boardRec.getBd_body_1()).toCharArray());
                    char[] buffer = new char[1024];
                    int read = 0;
                    while( (read = src.read(buffer,0,1024)) != -1){
                        writer.write(buffer, 0, read); // write clob.
                    }
                    src.close();
                    writer.close();

                    clob = null;
                    writer = null;
                    clob = ((OracleResultSet)rs).getCLOB(2);
                    writer = clob.getCharacterOutputStream();
                    Reader src = new CharArrayReader((boardRec.getBd_body_2()).toCharArray());
                    char[] buffer = new char[1024];
                    int read = 0;
                    while( (read = src.read(buffer,0,1024)) != -1){
                        writer.write(buffer, 0, read); // write clob.
                    }
                    src.close();
                    writer.close();
                    ...
                }
*/

                conn.commit();
                rtn = true;

            }else{
                logs.logIt("error","insert 처리(CLOB의 내용 제외)를 하지 못하고 db 에러남.\n"+
                                   " > entity : "+entity.toString()+"\n"+
                                   " > query : "+sb.toString()+"\n");
            }
        }catch(SQLException e){
            logs.logIt("error","insert 처리를 하지 못하고 에러남.\n"+
                               " > entity : "+entity.toString()+"\n"+
                               " > query : "+sb.toString()+"\n", e);
            if(conn != null)	conn.rollback();
            throw e;
        }finally{
            conn.setAutoCommit(true);
            if(rs != null)		rs.close();
            if(pstmt != null)	pstmt.close();
            db.release();
        }
        return rtn;
    }


    // 여러개의 clob data를 select예제
    public EntpRec select(int id) throws SQLException,IOException,Exception{

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        StringBuffer sb = new StringBuffer(1000);
        EntpRec entity = null;

        try{
            db = new DBConnHandler();
            conn = db.getConnection();
            sb.append(" SELECT id,class_code,cre_user_id,upt_user_id,to_char(cre_dt,'YYYY/MM/DD HH24:MI') cre_dt, ");
            sb.append(" to_char(upt_dt,'YYYY/MM/DD HH24:MI') upt_dt ");
            sb.append(" FROM TEST_TABLE ");
            sb.append(" WHERE (entp_id=? "+where+")");
            pstmt = conn.prepareStatement(sb.toString());
            pstmt.setInt(1, entp_id);
            rs = pstmt.executeQuery();

            if(rs.next()){
                entity = new EntpRec();
                entity.entp_id = rs.getInt("entp_id");
                entity.class_code = rs.getInt("class_code");
                entity.content_1 = ClobUtil.getClobOutput(rs.getCharacterStream("content_1"));
                entity.content_2 = ClobUtil.getClobOutput(rs.getCharacterStream("content_2"));
                entity.content_3 = ClobUtil.getClobOutput(rs.getCharacterStream("content_3"));
                entity.cre_user_id = rs.getString("cre_user_id");
                entity.upt_user_id = rs.getString("upt_user_id");
                entity.cre_dt = rs.getString("cre_dt");
                entity.upt_dt = rs.getString("upt_dt");

                Utility.fixNull(entity);
            }
        }catch(SQLException e){
            logs.logIt("error","[특정 pk에 따른 한 레코드 select하지 못하고 에러남.\n"+
                        " > id : "+id+"\n"+
                        " > query : "+sb.toString()+"\n", e);
        }finally{
            if(rs != null)        rs.close();
            if(pstmt != null)    pstmt.close();
            db.release();
        }
        return entity;
    }



    // 여러개의 clob data를 update하는 예제
    public boolean update(EntpRec entity) throws SQLException,IOException,Exception{

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        StringBuffer sb = new StringBuffer(1000);
        boolean rtn = false;

        try{
            db = new DBConnHandler();
            conn = db.getConnection();
            conn.setAutoCommit(false);
            sb.append(" UPDATE TEST_TABLE");
            sb.append(" SET class_code=?,content_1=empty_clob(),content_2=empty_clob(),content_3=empty_clob(), ");          
            sb.append(" upt_user_id=?,upt_dt=sysdate ");
            sb.append(" WHERE (id=?)");
            pstmt = conn.prepareStatement(sb.toString());

            pstmt.setInt(1, entity.class_code);
            pstmt.setString(51, entity.upt_user_id);
            pstmt.setInt(52, entity.id);

            if(pstmt.executeUpdate()>0){
                pstmt.close();
                sb.setLength(0);
                sb.append(" SELECT content_1,content_2,content_3 FROM TEST_TABLE ");
                sb.append(" WHERE (id=?)");
                sb.append(" FOR UPDATE");
                pstmt = conn.prepareStatement(sb.toString());
                pstmt.setInt(1, entity.id);
                rs = pstmt.executeQuery();

                while(rs.next()){
                    CLOB clob = ((OracleResultSet)rs).getCLOB(1);
                    Writer writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_1);

                    clob = null;
                    writer = null;
                    clob = ((OracleResultSet)rs).getCLOB(2);
                    writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_2);

                    clob = null;
                    writer = null;
                    clob = ((OracleResultSet)rs).getCLOB(3);
                    writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_3);
                }

                conn.commit();
                rtn = true;

            }else{
                logs.logIt("error","[update 처리(CLOB의 내용 제외)를 하지 못하고 db 에러남.\n"+
                            " > entity : "+entity.toString()+"\n"+
                            " > query : "+sb.toString()+"\n");
            }
        }catch(SQLException e){
            logs.logIt("error","[update 처리를 하지 못하고 에러남.\n"+
                        " > entity : "+entity.toString()+"\n"+
                        " > query : "+sb.toString()+"\n", e);
            if(conn != null)    conn.rollback();
            throw e;
        }finally{
            conn.setAutoCommit(true);
            if(rs != null)       rs.close();
            if(pstmt != null)    pstmt.close();
            db.release();
        }
        return rtn;
    }

Posted by 쭌쓰파파
,
해당강좌는 예전에 kkaok님이 강좌로 만들었던 것입니다.
현재는 그 링크가 사라져서 kkaok님의 홈페이지만을 링크로 해두었습니다.
좋은 강의와 TIP이 많은 곳이니 한번 방문해보시기 바랍니다^^

출처 :
http://www.kkaok.pe.kr/


오라클 clob 예제

Lob type이란?

lob(Large Object) 타입은 대용량 데이터를 저장하기위한 데이터 타입으로 오라클 8버전부터 지원된다.


Lob 타입의 특징

이전에 대용량 처리는 long 타입으로 처리를 할 수 밖에 없었다. 그런데 이 칼럼은 한테이블에 하나만 사용할 수 있으며 최대 크기가 2GB였다. 더군다나 검색을 구현하기가 어려워 포기를 해야 했다. 그래서 이런 문제를 보안하기 위 나온 것이 Lob 타입이다. Lob 타입은 테이블에 여러개의 컬럼을 생성할 수 있으며 최대 크기가 4GB이다. 또한 long 타입보다 훨씬 쉬운 검색기능을 제공한다.


Lob type의 종류

이전에 대용량 처리는 long 타입으로 처리를 할 수 밖에 없었다. 그런데 이 칼럼은 한테이블에 하나만 사용할 수 있으며 최대 크기가 2GB였다. 더군다나 검색을 구현하기가 어려워 포기를 해야 했다. 그래서 이런 문제를 보안하기 위 나온 것이 Lob 타입이다. Lob 타입은 테이블에 여러개의 컬럼을 생성할 수 있으며 최대 크기가 4GB이다. 또한 long 타입보다 훨씬 쉬운 검색기능을 제공한다.

BLob (Binary Large Object), 이진 바이너리 데이터의 저장시 사용된다.
CLob (Character Large Object), 문서 데이터의 저장시 사용된다.
BFILE 외부 파일에 저장된 이진 데이터가 있는 경로의 저장시 사용된다.


Clob에 저장하기

  1: import java.sql.*;
  2: import java.io.*;
  3: import oracle.sql.*;
  4: import oracle.jdbc.driver.*;
  5: ...
  6: 
  7: public void insertQuery(UploadBoard up,int re_step,int re_level) 
         throws Exception  
  8: {
  9:   ResultSet rs   = null;
 10:   PreparedStatement pstmt = null;
 11:   Connection conn = null;
 12:   String query = "insert into "+up.getTableName()+" (seq,re_step,
           re_level,name,title,pwd,email,readnum,writeday,ip,relativeCnt,
               homepage,imgInfo,content,tag) 
                   values(?,?,?,?,?,?,?,0,sysdate,?,0,?,?,empty_clob(),?)";
오라클 명령어 empty_clob()을 이용해 공간을 확보한다.
13: try{ 14: conn = DBManager.getClobConnection(); 15: conn.setAutoCommit(false);
CLOB column을 업데이트 하는동안 다른 process의 접근을 막기위해
setAutoCommit(false)를 반드시 설정해야 한다. 이부분이 가장 중요하다.
16: pstmt = conn.prepareStatement(query); 17: pstmt.setInt(1,up.getSeq()); 18: pstmt.setInt(2,re_step); 19: pstmt.setInt(3,re_level); 20: pstmt.setString(4,up.getName()); 21: pstmt.setString(5,up.getTitle()); 22: pstmt.setString(6,up.getPwd()); 23: pstmt.setString(7,up.getEmail()); 24: pstmt.setString(8,up.getIp()); 25: pstmt.setString(9,up.getHomepage()); 26: pstmt.setString(10,up.getImgInfo()); 27: pstmt.setString(11,up.getTag()); 28: pstmt.executeUpdate(); 29: pstmt.close(); 30: String query2 = " select /*+ index_desc("+up.getTableName()+ " "+up.getTableName()+"_indx) */ content from "+ up.getTableName()+" where seq = ? for update ";
for update를 이용해 CLOB column을 lock한다.
31: pstmt = conn.prepareStatement(query2); 32: pstmt.setInt(1,up.getSeq()); 33: rs = pstmt.executeQuery(); 34: if(rs.next()) { 35: CLOB clob = ((OracleResultSet)rs).getCLOB(1); 36: Writer writer = clob.getCharacterOutputStream(); 37: Reader src = new CharArrayReader(up.getContent().toCharArray()); 38: char[] buffer = new char[1024]; 39: int read = 0; 40: while ( (read = src.read(buffer,0,1024)) != -1) { 41: writer.write(buffer, 0, read); // write clob. 42: } 43: src.close(); 44: writer.close(); 45: } 46: conn.commit(); 47: conn.setAutoCommit(true);
CLOB column에 데이터을 저장하였다면 commit()을 실행시키고
conn.setAutoCommit(true)로 다시 설정한다.
48: }finally{ 49: DBManager.close(rs,pstmt,conn); 50: } 51: }


Clob 불러오기

     ...
  1: public BoardTable getViewData(String tableName,int seq) throws Exception
  2: {
  3:   BoardTable bTable = new BoardTable();
  4:   String query = " select * from "+tableName+" where seq = ? ";
  5:   ResultSet rs = null;
  6:   PreparedStatement pstmt = null;
  7:   Connection conn = null;
  8:   try{
  9:     conn = DBManager.getConnection();
 10:     pstmt = conn.prepareStatement(query);
 11:     pstmt.setInt(1,seq);
 12:     rs = pstmt.executeQuery();
 13:     if (rs.next()) {
 14:       ...
 15:       ...      
 16:       StringBuffer output = new StringBuffer();
 17:       Reader input = rs.getCharacterStream("content");
 18:       char[] buffer = new char[1024];
 19:       int byteRead;
 20:       while((byteRead=input.read(buffer,0,1024))!=-1){
 21:         output.append(buffer,0,byteRead);
 22:       }
 23:       input.close();
 24:       bTable.setContent(output.toString()); 
CLOB 데이터를 불러오기 위해서는 위에서처럼
rs.getCharacterStream("content")로 불러서 StringBuffer에 담아야 한다.
25: ... 26: ... 27: } 28: } finally { 29: DBManager.close(rs,pstmt,conn); 30: } 31: return bTable; 32: }


http://www.kkaok.pe.kr

Posted by 쭌쓰파파
,