JDBC에서 ResultSet 인터페이스는 getClob()과 getCharacterStream()이라는 두 가지 메서드를 제공하여 Clob 타입의 데이터를 조회할 수 있습니다. 일반적으로 파일의 내용은 이 Clob 타입으로 데이터베이스에 저장됩니다.
두 메서드 모두 컬럼의 인덱스를 나타내는 정수 값 또는 컬럼 이름을 나타내는 문자열 값을 인자로 받아, 해당 컬럼의 값을 반환합니다.
두 메서드의 차이점은 다음과 같습니다. getClob()은 Clob 객체를 반환하고, getCharacterStream()은 Clob 타입의 내용을 담고 있는 Reader 객체를 반환합니다.
예제 테이블 구조
데이터베이스에 아래와 같은 구조의 Articles 테이블이 생성되어 있다고 가정해 보겠습니다.
+---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | Article | longtext | YES | | NULL | | +---------+--------------+------+-----+---------+-------+
그리고 이 테이블에는 아래 그림과 같이 article1, article2, article3이라는 이름으로 세 개의 게시글이 저장되어 있습니다.
예제 코드
다음 프로그램은 getString()과 getClob() 메서드를 사용하여 Articles 테이블의 내용을 조회한 뒤, 지정된 경로의 파일로 저장합니다.
import java.io.FileWriter;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingFileFromDatabase {
public static void main(String args[]) throws Exception {
// 드라이버 등록
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// 연결 생성
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
// Statement 생성
Statement stmt = con.createStatement();
// 데이터 조회
ResultSet rs = stmt.executeQuery("select * from Articles");
int j = 0;
System.out.println("Contents of the table are: ");
while(rs.next()) {
System.out.println(rs.getString("Name"));
Clob clob = rs.getClob("Article");
Reader reader = clob.getCharacterStream();
String filePath = "E:\\Data\\clob_output"+j+".txt";
FileWriter writer = new FileWriter(filePath);
int i;
while ((i = reader.read())!=-1) {
writer.write(i);
}
writer.close();
System.out.println(filePath);
j++;
}
}
}실행 결과
Connection established...... Contents of the table are: article1 E:\Data\clob_output0.txt article2 E:\Data\clob_output1.txt article3 E:\Data\clob_output2.txt
코드 설명
위 코드의 핵심 흐름은 다음과 같습니다.
1. 데이터베이스 연결: JDBC 드라이버를 등록한 후, getConnection() 메서드로 MySQL 데이터베이스에 연결합니다.
2. 쿼리 실행: executeQuery() 메서드로 SELECT 문을 실행하여 결과를 ResultSet 객체로 받습니다.
3. CLOB 데이터 읽기: getClob() 메서드로 Article 컬럼의 값을 Clob 객체로 가져오고, getCharacterStream()을 호출하여 Reader 객체를 얻습니다.
4. 파일 저장: Reader에서 한 글자씩 읽어 FileWriter를 통해 로컬 파일에 기록합니다. 스트림 사용이 끝나면 반드시 close() 메서드로 자원을 해제해야 합니다.