Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 CLOB 타입을 문자열(String)로 변환하는 방법

CLOB(Character Large Object)는 대용량 텍스트 데이터를 저장하기 위해 사용되는 SQL 내장 데이터 타입입니다. 이 데이터 타입을 사용하면 최대 2,147,483,647자까지 저장할 수 있습니다.

JDBC API의 java.sql.Clob 인터페이스가 이 CLOB 데이터 타입을 나타냅니다. JDBC에서 Clob 객체는 SQL 로케이터(locator) 방식으로 구현되기 때문에, 실제 데이터 자체가 아니라 SQL CLOB을 가리키는 논리적 포인터를 보유하게 됩니다.

MySQL 데이터베이스는 TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT라는 네 가지 타입을 통해 CLOB 데이터 타입을 지원합니다.

CLOB 데이터를 문자열로 변환하는 절차

  • PreparedStatement 인터페이스의 getClob() 또는 getCharacterStream() 메서드를 사용하여 테이블에서 Clob 값을 가져옵니다.
Reader r = clob.getCharacterStream();
  • 가져온 문자 스트림에서 문자를 하나씩 읽어 StringBuilder 또는 StringBuffer에 순서대로 추가합니다.
int j = 0;
StringBuffer buffer = new StringBuffer();
int ch;
while ((ch = r.read())!=-1) {
   buffer.append(""+(char)ch);
}
System.out.println(buffer.toString());
j++;
  • 마지막으로, 변환된 문자열을 출력하거나 필요한 곳에 저장합니다.
System.out.println(buffer.toString());

실전 예제

먼저 다음 쿼리를 사용하여 MySQL 데이터베이스에 technologies_data라는 이름의 테이블을 생성해 보겠습니다.

CREATE TABLE Technologies (Name VARCHAR(255), Type VARCHAR(255), Article LONGTEXT);

테이블의 세 번째 열인 Article은 CLOB 타입의 데이터를 저장하는 역할을 합니다.

아래 JDBC 프로그램은 먼저 technologies_data 테이블에 레코드를 삽입하면서, 텍스트 파일의 전체 내용을 article 열(CLOB 타입)에 저장합니다.

그런 다음 테이블의 레코드를 조회하여 기술명과 아티클 내용을 화면에 출력합니다. 이 과정에서 조회된 CLOB 데이터를 문자열로 변환하여 출력하는 방법을 확인할 수 있습니다.

import java.io.FileReader;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class ClobToString {
   public static void main(String args[]) throws Exception {
      // 드라이버 등록
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      // 연결 생성
      String mysqlUrl = "jdbc:mysql://localhost/sampledatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      // Statement 객체 생성
      Statement stmt = con.createStatement();
      // 값 삽입
      String query = "INSERT INTO Technologies_data VALUES (?, ?, ?)";
      PreparedStatement pstmt = con.prepareStatement(query);
      pstmt.setString(1, "JavaFX");
      pstmt.setString(2, "Java Library");
      FileReader reader = new FileReader("E:\\images\\javafx_contents.txt");
      pstmt.setClob(3, reader);
      pstmt.execute();
      pstmt.setString(1, "CoffeeScript");
      pstmt.setString(2, "Scripting Language");
      reader = new FileReader("E:\\images\\coffeescript_contents.txt");
      pstmt.setClob(3, reader);
      pstmt.execute();
      pstmt.setString(1, "Cassandra");
      pstmt.setString(2, "NoSQL Database");
      reader = new FileReader("E:\\images\\cassandra_contents.txt");
      pstmt.setClob(3, reader);
      pstmt.execute();
      // 데이터 조회
      ResultSet rs = stmt.executeQuery("select * from Technologies_data");
      System.out.println("Contents of the table are: ");
      while(rs.next()) {
         System.out.println("Article: "+rs.getString("Name"));
         Clob clob = rs.getClob("Article");
         Reader r = clob.getCharacterStream();
         StringBuffer buffer = new StringBuffer();
         int ch;
         while ((ch = r.read())!=-1) {
            buffer.append(""+(char)ch);
         }
         System.out.println("Contents: "+buffer.toString());
         System.out.println(" ");
      }
   }
}

실행 결과

Connection established......
Contents of the table are:
Article: JavaFX
Contents: JavaFX is a Java library using which you can develop Rich Internet Applications. By using Java technology, these applications have a browser penetration rate of 76%.
Article: CoffeeScript
Contents: CoffeeScript is a lightweight language based on Ruby and Python which transcompiles (compiles from one source language to another) into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language.
Article: Cassandra
Contents: Apache Cassandra is a highly scalable, high-performance distributed database designed to handle large amounts of data across many commodity servers,
providing high availability with no single point of failure. It is a type of NoSQL database. Let us first understand what a NoSQL database does.