package org.kodejava.jdbc;
import java.io.File;
import java.io.FileWriter;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.sql.*;
public class ClobReadDemo {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
public static void main(String[] args) {
try (Connection conn =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
String sql = "SELECT book_isbn, data FROM book_excerpts";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
String bookIsbn = resultSet.getString("book_isbn");
// Get the character stream of our CLOB file
Reader reader = resultSet.getCharacterStream("data");
File file = new File(bookIsbn + ".txt");
try (FileWriter writer = new FileWriter(file, StandardCharsets.UTF_8)) {
char[] buffer = new char[1];
while (reader.read(buffer) > 0) {
writer.write(buffer);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The structure of book_excerpts
table.
CREATE TABLE `book_excerpts`
(
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`book_isbn` varchar(50) NOT NULL,
`description` varchar(255) NOT NULL,
`data` longtext,
PRIMARY KEY (`id`),
KEY `book_isbn` (`book_isbn`),
CONSTRAINT `book_excerpts_ibfk_1` FOREIGN KEY (`book_isbn`) REFERENCES `books` (`isbn`)
) ENGINE = InnoDB;
Maven dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
Latest posts by Wayan (see all)
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023
Worked like magic.. Thank you for this great code snippet. Keep posting such nice stuff and keep empowering the community.