반응형

출처(Reference) : http://www.javafaq.nu/java-example-code-141.html


// -----------------------------------------------------------------------------
// CLOBFileExample.java
// -----------------------------------------------------------------------------

/*
 * =============================================================================
 * Copyright (c) 1998-2005 Jeffrey M. Hunter. All rights reserved.
 *
 * All source code and material located at the Internet address of
 * http://www.idevelopment.info is the copyright of Jeffrey M. Hunter, 2005 and
 * is protected under copyright laws of the United States. This source code may
 * not be hosted on any other site without my express, prior, written
 * permission. Application to host any of the material elsewhere can be made by
 * contacting me at jhunter@idevelopment.info.
 *
 * I have made every effort and taken great care in making sure that the source
 * code and other content included on my web site is technically accurate, but I
 * disclaim any and all responsibility for any loss, damage or destruction of
 * data or any other property which may arise from relying on it. I will in no
 * case be liable for any monetary damages arising from such loss, damage or
 * destruction.
 *
 * As with any code, ensure to test this code in a development environment
 * before attempting to run it in production.
 * =============================================================================
 */
 
import java.sql.*;
import java.io.*;
import java.util.*;

// Needed since we will be using Oracle's CLOB, part of Oracle's JDBC extended
// classes. Keep in mind that we could have included Java's JDBC interfaces
// java.sql.Clob which Oracle does implement. The oracle.sql.CLOB class
// provided by Oracle does offer better performance and functionality.
import oracle.sql.*;

// Needed for Oracle JDBC Extended Classes
import oracle.jdbc.*;


/**
 * -----------------------------------------------------------------------------
 * Used to test the functionality of how to load and unload text data from an
 * Oracle CLOB.
 *
 * This example uses an Oracle table with the following definition:
 *
 *      CREATE TABLE test_clob (
 *            id               NUMBER(15)
 *          , do*****ent_name    VARCHAR2(1000)
 *          , xml_do*****ent     CLOB
 *          , timestamp        DATE
 *      );
 * -----------------------------------------------------------------------------
 * @version 1.0
 * @author  Jeffrey M. Hunter  (jhunter@idevelopment.info)
 * @author  http://www.idevelopment.info
 * -----------------------------------------------------------------------------
 */
 
public class CLOBFileExample  {

    private String          inputTextFileName   = null;
    private File            inputTextFile       = null;

    private String          outputTextFileName1  = null;
    private File            outputTextFile1      = null;

    private String          outputTextFileName2  = null;
    private File            outputTextFile2      = null;
   
    private String          dbUser              = "SCOTT";
    private String          dbPassword          = "TIGER";
    private Connection      conn                = null;
   

    /**
     * Default constructor used to create this object. Responsible for setting
     * this object's creation date, as well as incrementing the number instances
     * of this object.
     * @param args Array of string arguments passed in from the command-line.
     * @throws java.io.IOException
     */
    public CLOBFileExample(String[] args) throws IOException {
       
        inputTextFileName  = args[0];
        inputTextFile = new File(inputTextFileName);
       
        if (!inputTextFile.exists()) {
            throw new IOException("File not found. " + inputTextFileName);
        }

        outputTextFileName1 = inputTextFileName + ".getChars.out";
        outputTextFileName2 = inputTextFileName + ".Streams.out";
       
    }


    /**
     * Obtain a connection to the Oracle database.
     * @throws java.sql.SQLException
     */
    public void openOracleConnection()
            throws    SQLException
                    , IllegalAccessException
                    , InstantiationException
                    , ClassNotFoundException {

        String driver_class  = "oracle.jdbc.driver.OracleDriver";
        String connectionURL = null;

        try {
            Class.forName (driver_class).newInstance();
            connectionURL = "jdbc:oracle:thin:@melody:1521:JEFFDB";
            conn = DriverManager.getConnection(connectionURL, dbUser, dbPassword);
            conn.setAutoCommit(false);
            System.out.println("Connected.\n");
        } catch (IllegalAccessException e) {
            System.out.println("Illegal Access Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        } catch (InstantiationException e) {
            System.out.println("Instantiation Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        } catch (ClassNotFoundException e) {
            System.out.println("Class Not Found Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        }
           
    }
   
   
    /**
     * Close Oracle database connection.
     * @throws java.sql.SQLException
     */
    public void closeOracleConnection() throws SQLException {
       
        try {
            conn.close();
            System.out.println("Disconnected.\n");
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Closing Connection).");
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException e2) {
                    System.out.println("Caught SQL (Rollback Failed) Exception.");
                    e2.printStackTrace();
                }
            }
            throw e;
        }

    }
   
   
    /**
     * Method used to print program usage to the console.
     */
    static public void usage() {
        System.out.println("\nUsage: java CLOBFileExample \"Text File Name\"\n");
    }


    /**
     * Validate command-line arguments to this program.
     * @param args Array of string arguments passed in from the command-line.
     * @return Boolean - value of true if correct arguments, false otherwise.
     */
    static public boolean checkArguments(String[] args) {
       
        if (args.length == 1) {
            return true;
        } else {
            return false;
        }

    }


    /**
     * Override the Object toString method. Used to print a version of this
     * object to the console.
     * @return String - String to be returned by this object.
     */
    public String toString() {
   
        String retValue;

        retValue  = "Input File         : " + inputTextFileName    + "\n" +
                    "Output File (1)    : " + outputTextFileName1  + "\n" +
                    "Output File (2)    : " + outputTextFileName2  + "\n" +
                    "Database User      : " + dbUser;
        return retValue;
   
    }


    /**
     * Method used to write text data contained in a file to an Oracle CLOB
     * column. The method used to write the data to the CLOB uses the putChars()
     * method. This is one of two types of methods used to write text data to
     * a CLOB column. The other method uses Streams.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void writeCLOBPut()
            throws IOException, SQLException {
       
        FileInputStream     inputFileInputStream    = null;
        InputStreamReader   inputInputStreamReader  = null;
        BufferedReader      inputBufferedReader     = null;
        String              sqlText                 = null;
        Statement           stmt                    = null;
        ResultSet           rset                    = null;
        CLOB                xmlDo*****ent             = null;
        int                 chunkSize;
        char[]              textBuffer;
        long                position;
        int                 charsRead               = 0;
        int                 charsWritten            = 0;
        int                 totCharsRead            = 0;
        int                 totCharsWritten         = 0;
       
        try {

            stmt = conn.createStatement();
           
            inputTextFile = new File(inputTextFileName);
            inputFileInputStream = new FileInputStream(inputTextFile);
            inputInputStreamReader = new InputStreamReader(inputFileInputStream);
            inputBufferedReader = new BufferedReader(inputInputStreamReader);
       
            sqlText =
                "INSERT INTO test_clob (id, do*****ent_name, xml_do*****ent, timestamp) " +
                "   VALUES(1, '" + inputTextFile.getName() + "', EMPTY_CLOB(), SYSDATE)";
            stmt.executeUpdate(sqlText);
           
            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 1 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");
           
            chunkSize = xmlDo*****ent.getChunkSize();
            textBuffer = new char[chunkSize];
           
            position = 1;
            while ((charsRead = inputBufferedReader.read(textBuffer)) != -1) {
                charsWritten = xmlDo*****ent.putChars(position, textBuffer, charsRead);
                position        += charsRead;
                totCharsRead    += charsRead;
                totCharsWritten += charsWritten;
            }
           
            inputBufferedReader.close();
            inputInputStreamReader.close();
            inputFileInputStream.close();

            conn.commit();
            rset.close();
            stmt.close();
           
            System.out.println(
                "==========================================================\n" +
                "  PUT METHOD\n" +
                "==========================================================\n" +
                "Wrote file " + inputTextFile.getName() + " to CLOB column.\n" +
                totCharsRead + " characters read.\n" +
                totCharsWritten + " characters written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value - Put Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value - Put Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }

    }

   
    /**
     * Method used to write the contents (data) from an Oracle CLOB column to
     * an O/S file. This method uses one of two ways to get data from the CLOB
     * column - namely the getChars() method. The other way to read data from an
     * Oracle CLOB column is to use Streams.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void readCLOBToFileGet()
            throws IOException, SQLException {

        FileOutputStream    outputFileOutputStream      = null;
        OutputStreamWriter  outputOutputStreamWriter    = null;
        BufferedWriter      outputBufferedWriter        = null;
        String              sqlText                     = null;
        Statement           stmt                        = null;
        ResultSet           rset                        = null;
        CLOB                xmlDo*****ent                 = null;
        long                clobLength;
        long                position;
        int                 chunkSize;
        char[]              textBuffer;
        int                 charsRead                   = 0;
        int                 charsWritten                = 0;
        int                 totCharsRead                = 0;
        int                 totCharsWritten             = 0;

        try {

            stmt = conn.createStatement();

            outputTextFile1 = new File(outputTextFileName1);
            outputFileOutputStream = new FileOutputStream(outputTextFile1);
            outputOutputStreamWriter = new OutputStreamWriter(outputFileOutputStream);
            outputBufferedWriter = new BufferedWriter(outputOutputStreamWriter);

            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 1 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");
           
            clobLength = xmlDo*****ent.length();
            chunkSize = xmlDo*****ent.getChunkSize();
            textBuffer = new char[chunkSize];
           
            for (position = 1; position <= clobLength; position += chunkSize) {
               
                // Loop through while reading a chunk of data from the CLOB
                // column using the getChars() method. This data will be stored
                // in a temporary buffer that will be written to disk.
                charsRead = xmlDo*****ent.getChars(position, chunkSize, textBuffer);

                // Now write the buffer to disk.
                outputBufferedWriter.write(textBuffer, 0, charsRead);
               
                totCharsRead += charsRead;
                totCharsWritten += charsRead;

            }

            outputBufferedWriter.close();
            outputOutputStreamWriter.close();
            outputFileOutputStream.close();
           
            conn.commit();
            rset.close();
            stmt.close();
           
            System.out.println(
                "==========================================================\n" +
                "  GET METHOD\n" +
                "==========================================================\n" +
                "Wrote CLOB column data to file " + outputTextFile1.getName() + ".\n" +
                totCharsRead + " characters read.\n" +
                totCharsWritten + " characters written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value to file - Get Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value to file - Get Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }

    }
   
   
    /**
     * Method used to write text data contained in a file to an Oracle CLOB
     * column. The method used to write the data to the CLOB uses Streams.
     * This is one of two types of methods used to write text data to
     * a CLOB column. The other method uses the putChars() method.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void writeCLOBStream()
            throws IOException, SQLException {

        FileInputStream     inputFileInputStream    = null;
        OutputStream        clobOutputStream        = null;
        String              sqlText                 = null;
        Statement           stmt                    = null;
        ResultSet           rset                    = null;
        CLOB                xmlDo*****ent             = null;
        int                 bufferSize;
        byte[]              byteBuffer;
        int                 bytesRead               = 0;
        int                 bytesWritten            = 0;
        int                 totBytesRead            = 0;
        int                 totBytesWritten         = 0;

        try {

            stmt = conn.createStatement();

            inputTextFile = new File(inputTextFileName);
            inputFileInputStream = new FileInputStream(inputTextFile);
           
            sqlText =
                "INSERT INTO test_clob (id, do*****ent_name, xml_do*****ent, timestamp) " +
                "   VALUES(2, '" + inputTextFile.getName() + "', EMPTY_CLOB(), SYSDATE)";
            stmt.executeUpdate(sqlText);
           
            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 2 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");
           
            bufferSize = xmlDo*****ent.getBufferSize();
           
            // Notice that we are using an array of bytes as opposed to an array
            // of characters. This is required since we will be streaming the
            // content (to either a CLOB or BLOB) as a stream of bytes using
            // using an OutputStream Object. This requires that a byte array to
            // be used to temporarily store the contents that will be sent to
            // the LOB. Note that they use of the byte array can be used even
            // when reading contents from an ASCII text file that will be sent
            // to a CLOB.
            byteBuffer = new byte[bufferSize];
           
            clobOutputStream = xmlDo*****ent.getAsciiOutputStream();
           
            while ((bytesRead = inputFileInputStream.read(byteBuffer)) != -1) {
           
                // After reading a buffer from the text file, write the contents
                // of the buffer to the output stream using the write()
                // method.
                clobOutputStream.write(byteBuffer, 0, bytesRead);
               
                totBytesRead += bytesRead;
                totBytesWritten += bytesRead;

            }

            // Keep in mind that we still have the stream open. Once the stream
            // gets open, you cannot perform any other database operations
            // until that stream has been closed. This even includes a COMMIT
            // statement. It is possible to loose data from the stream if this
            // rule is not followed. If you were to attempt to put the COMMIT in
            // place before closing the stream, Oracle will raise an
            // "ORA-22990: LOB locators cannot span transactions" error.

            inputFileInputStream.close();
            clobOutputStream.close();
           
            conn.commit();
            rset.close();
            stmt.close();

            System.out.println(
                "==========================================================\n" +
                "  OUTPUT STREAMS METHOD\n" +
                "==========================================================\n" +
                "Wrote file " + inputTextFile.getName() + " to CLOB column.\n" +
                totBytesRead + " bytes read.\n" +
                totBytesWritten + " bytes written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value - Stream Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value - Stream Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }

    }
   
   
    /**
     * Method used to write the contents (data) from an Oracle CLOB column to
     * an O/S file. This method uses one of two ways to get data from the CLOB
     * column - namely using Streams. The other way to read data from an
     * Oracle CLOB column is to use getChars() method.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void readCLOBToFileStream()
            throws IOException, SQLException {

        FileOutputStream    outputFileOutputStream      = null;
        InputStream         clobInputStream             = null;
        String              sqlText                     = null;
        Statement           stmt                        = null;
        ResultSet           rset                        = null;
        CLOB                xmlDo*****ent                 = null;
        int                 chunkSize;
        byte[]              textBuffer;
        int                 bytesRead                   = 0;
        int                 bytesWritten                = 0;
        int                 totBytesRead                = 0;
        int                 totBytesWritten             = 0;

        try {

            stmt = conn.createStatement();

            outputTextFile2 = new File(outputTextFileName2);
            outputFileOutputStream = new FileOutputStream(outputTextFile2);

            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 2 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");

            // Will use a Java InputStream object to read data from a CLOB (can
            // also be used for a BLOB) object. In this example, we will use an
            // InputStream to read ASCII characters from a CLOB.
            clobInputStream = xmlDo*****ent.getAsciiStream();
           
            chunkSize = xmlDo*****ent.getChunkSize();
            textBuffer = new byte[chunkSize];
           
            while ((bytesRead = clobInputStream.read(textBuffer)) != -1) {
               
                // Loop through while reading a chunk of data from the CLOB
                // column using an InputStream. This data will be stored
                // in a temporary buffer that will be written to disk.
                outputFileOutputStream.write(textBuffer, 0, bytesRead);
               
                totBytesRead += bytesRead;
                totBytesWritten += bytesRead;

            }

            outputFileOutputStream.close();
            clobInputStream.close();
           
            conn.commit();
            rset.close();
            stmt.close();
           
            System.out.println(
                "==========================================================\n" +
                "  INPUT STREAMS METHOD\n" +
                "==========================================================\n" +
                "Wrote CLOB column data to file " + outputTextFile2.getName() + ".\n" +
                totBytesRead + " characters read.\n" +
                totBytesWritten + " characters written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value to file - Streams Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value to file - Streams Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }
       
    }
   
   
    /**
     * Sole entry point to the class and application.
     * @param args Array of string arguments passed in from the command-line.
     */
    public static void main(String[] args) {
   
        CLOBFileExample cLOBFileExample = null;
       
        if (checkArguments(args)) {

            try {
               
                cLOBFileExample = new CLOBFileExample(args);
               
                System.out.println("\n" + cLOBFileExample + "\n");
               
                cLOBFileExample.openOracleConnection();
               
                cLOBFileExample.writeCLOBPut();
                cLOBFileExample.readCLOBToFileGet();
               
                cLOBFileExample.writeCLOBStream();
                cLOBFileExample.readCLOBToFileStream();
               
                cLOBFileExample.closeOracleConnection();

            } catch (IllegalAccessException e) {
                System.out.println("Caught Illegal Accecss Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (InstantiationException e) {
                System.out.println("Instantiation Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e) {
                System.out.println("Class Not Found Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (SQLException e) {
                System.out.println("Caught SQL Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (IOException e) {
                System.out.println("Caught I/O Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            }

        } else {
            System.out.println("\nERROR: Invalid arguments.");
            usage();
            System.exit(1);
        }
       
        System.exit(0);
    }

반응형
반응형
제품 : JDBC

작성날짜 :

FILE을 CLOB에 INSERT하고, 반대로 컬럼을 읽어 FILE로 WRITE하는 JDBC PROGRAM 예제 (JDBC 8.1 이상)



PURPOSE

text file을 읽어서 CLOB column 에 저장하는 방법과, CLOB column의 데이타를
읽어서 file로 write하는 방법을 예제를 통해서 살펴본다.


Explanation



oracle.sql package에서 제공하는 CLOB class를 이용한다.
file의 내용을 읽어 CLOB type에 저장할 때는 CLOB.getCharacterOutputStream을
이용하고, 반대로 file에 write를 위해 CLOB type을 읽을 때는
clob.getCharacterStream() 를 이용한다.

Oracle JDBC driver 8.1.x 이상 version의 classes12.zip file이 CLASSPATH에
지정되어 있어야 한다. JDK는 1.2 이상을 사용한다.

[참고] 화일을 이용하지 않고 직접 text를 CLOB에 입력하고, 입력된 CLOB
데이타를 화면에 display하기 위해서는 아래 bulletin을 참고한다.
<Bulletin No: 19360>: Subject: ORACLE.SQL.CLOB CLASS를 이용하여
4000 BYTES이상의 CLOB TEXT 데이타를 저장하고, 조회하는 예제

Example


1. 테이블의 생성과 데이타 입력

미리 다음 작업이 수행되어 있어야 하며, 이 작업도 java application내에
statement.execute를 통해 포함시킬 수 있다.

sqlplus scott/tiger
SQL> create table test_clob(id number, c clob);
SQL> insert into test_clob values (1, empty_clob());

2. ClobFile.java

다음 내용을 ClobFile.java라는 이름으로 생성한 후,

os>javac ClobFile.java
os>java ClobFile
후 out.txt file내용을 확인하고, scott.TEST_CLOB table의 데이타도 조회하여
수해이 잘 되었는지 확인한다.

import java.sql.*;
import java.io.*;
import java.util.*;
import oracle.jdbc.driver.*;

import oracle.sql.*;

public class ClobFile {

public static void main (String args []) throws Exception {

try {
Connection conn;

DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver() );
conn = DriverManager.getConnection( "jdbc:oracle:thin:@krint-5:1521:ORA920"

, "scott","tiger" );

conn.setAutoCommit (false);

CLOB clob = null;

Statement stmt = conn.createStatement ();

String cmd = "select * from test_clob for update";
ResultSet rset = stmt.executeQuery(cmd);
while (rset.next())
clob = ((OracleResultSet)rset).getCLOB(2);

// 아랫부분에 file로 부터 데이타를 읽어 CLOB column에 저장하는
// readFromFile()이 작성되어 있다.

readFromFile(clob);
stmt.execute("commit");

rset = stmt.executeQuery ("select * from test_clob where id=1");

if (rset.next ())
{
clob = ((OracleResultSet)rset).getCLOB(2);
String st = rset.getString(2);

if (clob != null)
System.out.println ("clob length = "+clob.length ());
}

// 아랫부분의 CLOB 컬럼의 데이타를 읽어 다시 다른 file로 write하는
// writeToFile()을 호출한다.

writeToFile(clob);
}

catch (SQLException sqle) {
System.out.println("SQL Exception occured: " + sqle.getMessage());
sqle.printStackTrace();
}

catch(FileNotFoundException e) {
System.out.println("File Not Found");
}

catch (IOException ioe) {
System.out.println("IO Exception" + ioe.getMessage());
}
}

//


// test.txt file을 읽어 test_clob.c column에 저장한다.

static void readFromFile (CLOB clob) throws Exception {
File file = new File("/home/ora920/eykim/test.txt");
FileReader in = new FileReader(file);
Writer out = clob.getCharacterOutputStream();

int chunk = clob.getChunkSize();
System.out.print("The chunk size is " + chunk);
char[] buffer = new char[chunk];
int length;

while ((length = in.read(buffer,0,chunk)) != -1)
out.write(buffer, 0, length);

in.close();
out.close();
}

//------------------------------------------------------------------
// test.clob.c column의 데이타를 읽어 out.txt file로 write한다.

static void writeToFile (CLOB clob) throws Exception {
int chunk = clob.getChunkSize();

int length;
char[] buffer = new char[chunk];
FileWriter outFile = null;
outFile = new FileWriter("/home/ora920/eykim/out.txt");
Reader instream = clob.getCharacterStream();

while ((length = instream.read(buffer)) != -1) {
outFile.write(buffer, 0, length);
}

instream.close();
outFile.close();
}

}


Reference Documents


SCR #998


반응형
반응형

LOB 정보가 기간이 지나 삭제가 필요할때...

LOB 정보가 있는 테이블 : LOB_TABLE
LOB 정보가 있는 필드 : LOB_DATA

-- LOB_TABLE 있는 LOG_DATA 필드의 값을 모두 없는 것으로 처리
UPDATE LOB_TABLE
     SET LOG_DATA = EMPTY_CLOB()
 WHERE 조건

-- LOB 공간 SHRINK 할수 있도록 데이터 압축해 놓기
ALTER TABLE LOB_TABLE
MODIFY LOB(LOB_DATA) (SHRINK SPACE COMPACT);

* 만약 에러가 나면 ROW MOVEMENT ENABLE 설정을 참고 !

-- LOB 공간 실제 SHRINK 하기
ALTER TABLE LOB_TABLE
MODIFY LOB(LOB_DATA) (SHRINK SPACE);
반응형
반응형

1) import 시켜야할 API

① oracle.sql.BLOB

② oracle.sql.CLOB

③ oracle.jdbc.driver.OracleResultSet

2) CLOB

① DB에 CLOB 데이터형 쓰기

       // UPDATE 또는 INSERT 명령으로 DB 에 공간 확보
     String query = "UPDATE TABLE SET CLOB_DATA = EMPTY_CLOB() " ;
     stmt.executeUpdate(query);

     // 그런 다음 다시 요놈을 다시 SELECT
     query = "SELECT CLOB_DATA  FROM TABLE WHERE ~ " ;   

     stmt = dbConn.createStatement();
     rs = stmt.executeQuery(query);

     if(rs.next()) {
          CLOB clob = null;
          Writer writer = null;
          Reader src = null;
          char[] buffer = null;
          int read = 0;  

          clob = ((OracleResultSet)rs).getCLOB(1);        
          writer = clob.getCharacterOutputStream();

          // str -> DB에 넣을 내용
          src = new CharArrayReader(str.toCharArray());
          buffer = new char[1024];
          read = 0;
          while ( (read = src.read(buffer,0,1024)) != -1) {
               writer.write(buffer, 0, read); // write clob.
          }
          src.close();        
          writer.close();
     }

     dbConn.commit();
     dbConn.setAutoCommit(true);


 ② DB에서 CLOB 데이터형 읽기

      // SELECT
     String query = "SELECT CLOB_DATA  FROM TABLE WHERE ~ " ;   

     stmt = dbConn.createStatement();
     rs = stmt.executeQuery(query);

     if(rs.next()) {

          StringBuffer output = new StringBuffer();
          Reader input = rs.getCharacterStream("CLOB_DATA");
          char[] buffer = new char[1024];
          int byteRead = 0;
          while((byteRead=input.read(buffer,0,1024))!=-1){
               output.append(buffer,0,byteRead);
          }
         

          // contents -> CLOB 데이터가 저장될 String
          String contents = output.toString();


     }

     dbConn.commit();
     dbConn.setAutoCommit(true);


3) BLOB

① DB에 BLOB 데이터형 쓰기

      // UPDATE 또는 INSERT 명령으로 DB 에 공간 확보
     String query = "UPDATE TABLE SET BLOB_DATA = EMPTY_BLOB() " ;
     stmt.executeUpdate(query);

     // 그런 다음 다시 요놈을 다시 SELECT
     query = "SELECT BLOB_DATA  FROM TABLE WHERE ~ " ;   

     stmt = dbConn.createStatement();
     rs = stmt.executeQuery(query);

     if(rs.next()) {

          BLOB blob = null;
          BufferedOutputStream out = null;
          BufferedInputStream in = null;
          byte[] buf = null;
          int bytesRead= 0;  

          blob = ((OracleResultSet)rs).getBLOB(1);
          out = new BufferedOutputStream(blob.getBinaryOutputStream());

          // str -> DB에 넣을 내용
          in = new BufferedInputStream(new StringBufferInputStream(str));
          int nFileSize = (int)str.length();
          buf = new byte[nFileSize];
         
          while ((bytesRead = in.read(buf)) != -1){
               out.write(buf, 0, bytesRead);

          }

          in.close();
          out.close();
     }

     dbConn.commit();
     dbConn.setAutoCommit(true);


 ② DB에서 BLOB 데이터형 읽기

      // SELECT
     String query = "SELECT CLOB_DATA  FROM TABLE WHERE ~ " ;   

     stmt = dbConn.createStatement();
     rs = stmt.executeQuery(query);

     if(rs.next()) {

          BLOB blob = ((OracleResultSet)rs).getBLOB(1);

          BufferedInputStream in = new BufferedInputStream(blob.getBinaryStream());
          int nFileSize = (int)blob.length();
          byte[] buf = new byte [nFileSize];   
          int nReadSize = in.read(buf, 0, nFileSize);
          in.close();

           // contents -> BLOB 데이터가 저장될 String

          String contents = new String(buf);
     }

     dbConn.commit();
     dbConn.setAutoCommit(true);


출처 : http://lambert.egloos.com/3069062
반응형
반응형

/**
 CLOB 자료를 오라클 DB에 넣기 위한 자바 소스 파일
 
 1. CLOB 자료형인 column을 오라클의 empty_clob()을 이용해 초기화를 해야 한다.
    : 또는 CLOB column의 기본값을 empty_clob()으로 하던가..
    
 2. setAutoCommit(false)를 꼭 해야 한다.
 
 3. select clob_column from table where pk = value for update
    : for update를 이용해 CLOB column을 lock한다.
    : stream을 이용해 CLOB column을 업데이트 하는동안 다른 process의 접근을 막는다.
    : 또한 stream을 이용해 자료를 넣기 전까지는 실제로 commit되지 말아야 하기 때문에
      2번의 auto commit을 false로 했던 것이다. (이것때문에 하루 보냄 ㅜㅜ;;)
    : 모두 쓰고 나서는 commit() <-- 옵션
    : setAutoCommit(true) <-- 옵션
      
 4. 여기서 특이한 점은 오라클의 jdbc 드라이버의 OracleResultSet과 CLOB을 이용한다는 것이다.
    : java.sql.ResultSet과 java.sql.Clob을 이용하면 오라클 JDBC 드라이버가 해석시에 에러를 발생시킨다.
    : 아마도 오라클 jdbc 드라이버의 문제점이 아닐까 하는 생각이 든다.
    : 아니면 표준과 싸우는 오라클인가? ㅡㅡ;;
    
 5. 나머지 부분은 Stream을 이용한 input과 output이므로 언급을 생략하겠다.
*/

import java.io.*;
import java.net.*;
import java.sql.*;

import oracle.sql.*;
import oracle.jdbc.driver.*;

public class ClobTest {
 public static void main(String[] argv) {
 
  String drv = "oracle.jdbc.driver.OracleDriver";
  String dburl = "jdbc:oracle:thin:@192.168.3.30:1521:GRDB21";
  String user = "scott";
  String password = "tiger";
 
  Connection conn = null;
  Statement st;
  ResultSet rs;
 
  try {
         Class.forName(drv);         
         System.out.println("Drive Loading...");
            conn = DriverManager.getConnection(dburl, user, password);
            System.out.println("Connecting...");
            st = conn.createStatement();
            
            // 입력할 텍스트 만들기
            StringBuffer sb = new StringBuffer();
            String clobTest = "한글 테스트입니다\nIt is difficult\n";
            for (int i = 0; i < 300; i++)
    sb.append(clobTest);
   
   
   
   // 1. CLOB 데이터 입력하기 위해, empty_clob() 생성
            try {
             st.executeUpdate("insert into test_clob values ('02', empty_clob())");
            } catch (Exception ee) {
             ee.printStackTrace(System.out);
            }
   
   // 2. setAutoCommit을 false로 꼭 해야 한다.
   conn.setAutoCommit(false);
   
   
   // 3. CLOB column에 대한 lock을 얻는다.
   rs = st.executeQuery("select desc2 from test_clob where code = '02' for update");
   if (rs. next()) {
   
    // 4. 오라클의 함수들을 사용하기 위해 cast 하였다.
    CLOB cl = ((OracleResultSet)rs).getCLOB("desc2");
    
    // 스트림을 이용한 값 저장
    BufferedWriter writer = new BufferedWriter(cl.getCharacterOutputStream());
    writer.write(sb.toString());
    writer.close();
   }
   conn.commit();
   conn.setAutoCommit(true);
                
   // 입력한 값 읽어 오기     
   rs = st.executeQuery("select * from test_clob where code = '02'");
   
   if (rs.next()) {
    String code = rs.getString("code");
    
    // CLOB column에 대한 스트림을 얻는다.
    Reader rd = rs.getCharacterStream("desc2");
    
    sb = new StringBuffer();
    char[] buf = new char[1024];
    int readcnt;
    while ((readcnt = rd.read(buf, 0, 1024)) != -1) {
     // 스트림으로부터 읽어서 스트링 버퍼에 넣는다.
     sb.append(buf, 0, readcnt);
    }
    rd.close();
    
    System.out.println("code : " + code);
    System.out.println("desc2 : " + sb.toString());
   }
 
 
  }
  catch (Exception e) {
   e.printStackTrace(System.out);
  }
 }
}

출처 : http://djnine.tistory.com/
반응형

+ Recent posts