How do I store CLOBs data into database?

package org.kodejava.example.jdbc;

import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ClobInsertDemo {
    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)) {
            conn.setAutoCommit(false);

            String sql = "INSERT INTO book_excerpts " +
                "(book_isbn, description, data) VALUES (?, ?, ?)";

            File data = new File("java-8-in-action.txt");
            try (PreparedStatement stmt = conn.prepareStatement(sql);
                 FileReader reader = new FileReader(data)) {

                stmt.setString(1, "9781617291999");
                stmt.setString(2, "Java 8 in Action");
                stmt.setCharacterStream(3, reader, (int) data.length());
                stmt.execute();

                conn.commit();
            } catch (Exception e) {
                conn.rollback();
                e.printStackTrace();
            }
        } catch (SQLException 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

<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.17</version>
</dependency>

Maven Central

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.