How do I read BLOBs data from database?

This example shows you how to read BLOBs data from database table.

package org.kodejava.jdbc;

import java.sql.*;

public class BlobReadDemo {
    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 name, image FROM product_images";

            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while ( {
                String name = rs.getString("name");

                File image = new File(name);
                try (FileOutputStream fos = new FileOutputStream(image)) {
                    byte[] buffer = new byte[1024];

                    // Get the binary stream of our BLOB data
                    InputStream is = rs.getBinaryStream("image");
                    while ( > 0) {
                } catch (IOException e) {
        } catch (SQLException e) {

Table structure of product_images

CREATE TABLE `product_images`
    `id`          bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    `product_id`  bigint(20) unsigned NOT NULL,
    `name`        varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
    `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
    `image`       blob,
    PRIMARY KEY (`id`),
    KEY `product_id` (`product_id`),
    CONSTRAINT `product_images_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)
) ENGINE = InnoDB;

Maven dependencies


Maven Central

Leave a Reply

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