Interface ResultSet cung cấp getClob() và getCharacterStream() để truy xuất kiểu Clob (thường lưu nội dung file).
Các phương thức nhận nguyên (chỉ số cột) hoặc String (tên cột) và lấy giá trị tại cột đó. Khác biệt: getClob() trả về Clob object, getCharacterStream() trả về Reader object chứa nội dung Clob.
Ví dụ
Giả sử bảng Articles:
+---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | Article | longtext | YES | | NULL | | +---------+--------------+------+-----+---------+-------+
Đã chèn 3 bài viết: article1, article2, article3.

Ví dụ
Chương trình truy xuất nội dung bảng Articles dùng getString() và getClob(), lưu vào file:
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 {
// Đăng ký Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// Lấy kết nối
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Kết nối thành công......");
// Tạo Statement
Statement stmt = con.createStatement();
// Truy xuất dữ liệu
ResultSet rs = stmt.executeQuery("select * from Articles");
int j = 0;
System.out.println("Nội dung bảng:");
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++;
}
}
}
Kết quả
Kết nối thành công...... Nội dung bảng: article1 E:\Data\clob_output0.txt article2 E:\Data\clob_output1.txt article3 E:\Data\clob_output2.txt