Insert and Retrieve Images from MySQL Table Using Java [JDBC]

In this tutorial, we will learn how to insert and retrieve images from a MySQL database using Java JDBC. This is particularly useful for storing and displaying profile pictures, product images, or any other binary data in your application.

Table of Contents

  1. Introduction
  2. Setting Up the MySQL Database
  3. JDBC Driver and Dependencies
  4. Inserting Images into MySQL Database
  5. Retrieving Images from MySQL Database
  6. Example Code
  7. Conclusion

1. Introduction

Storing images in a database can be a useful feature for many applications. This tutorial will guide you through the process of inserting and retrieving images from a MySQL database using Java JDBC.

2. Setting Up the MySQL Database

First, ensure that MySQL is installed and running. Create a new database and table for this example.

CREATE DATABASE test_db;

USE test_db;

CREATE TABLE images (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    image LONGBLOB NOT NULL
);

3. JDBC Driver and Dependencies

To connect to MySQL from Java, you need the MySQL JDBC driver. You can download it from the MySQL website. Add the downloaded JAR file to your project's build path. 

If you are using Maven, add the following dependency to your pom.xml:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>

4. Inserting Images into MySQL Database

To insert an image into the database, you need to read the image file into a byte array and then use a PreparedStatement to insert it into the database.

Insert Image Example

package com.example.jdbc;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertImageExample {

    private static final String URL = "jdbc:mysql://localhost:3306/test_db?useSSL=false";
    private static final String USER = "root";
    private static final String PASSWORD = "root";

    private static final String INSERT_IMAGE_SQL = "INSERT INTO images (name, image) VALUES (?, ?);";

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {

            PreparedStatement preparedStatement = connection.prepareStatement(INSERT_IMAGE_SQL);
            preparedStatement.setString(1, "Sample Image");

            // Read the image file and set it as a binary stream
            try (FileInputStream inputStream = new FileInputStream("path/to/your/image.jpg")) {
                preparedStatement.setBinaryStream(2, inputStream, inputStream.available());
                preparedStatement.executeUpdate();
                System.out.println("Image inserted successfully!");
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (SQLException e) {
            printSQLException(e);
        }
    }

    public static void printSQLException(SQLException ex) {
        for (Throwable e : ex) {
            if (e instanceof SQLException) {
                e.printStackTrace(System.err);
                System.err.println("SQLState: " + ((SQLException) e).getSQLState());
                System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
                System.err.println("Message: " + e.getMessage());
                Throwable t = ex.getCause();
                while (t != null) {
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }
}

5. Retrieving Images from MySQL Database

To retrieve an image from the database, you need to use a PreparedStatement to query the image and then read the binary data from the ResultSet.

Retrieve Image Example

package com.example.jdbc;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class RetrieveImageExample {

    private static final String URL = "jdbc:mysql://localhost:3306/test_db?useSSL=false";
    private static final String USER = "root";
    private static final String PASSWORD = "root";

    private static final String SELECT_IMAGE_SQL = "SELECT name, image FROM images WHERE id = ?;";

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {

            PreparedStatement preparedStatement = connection.prepareStatement(SELECT_IMAGE_SQL);
            preparedStatement.setInt(1, 1); // Assume we are retrieving the image with ID 1

            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                String name = resultSet.getString("name");
                InputStream inputStream = resultSet.getBinaryStream("image");

                // Save the image to a file
                try (FileOutputStream outputStream = new FileOutputStream("output_image.jpg")) {
                    byte[] buffer = new byte[1024];
                    while (inputStream.read(buffer) > 0) {
                        outputStream.write(buffer);
                    }
                    System.out.println("Image retrieved and saved as 'output_image.jpg'!");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (SQLException e) {
            printSQLException(e);
        }
    }

    public static void printSQLException(SQLException ex) {
        for (Throwable e : ex) {
            if (e instanceof SQLException) {
                e.printStackTrace(System.err);
                System.err.println("SQLState: " + ((SQLException) e).getSQLState());
                System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
                System.err.println("Message: " + e.getMessage());
                Throwable t = ex.getCause();
                while (t != null) {
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }
}

6. Conclusion

Inserting and retrieving images from a MySQL database using Java JDBC is a straightforward process. By using PreparedStatement for insertion and retrieval, you can handle binary data efficiently. This tutorial covered setting up the MySQL database, inserting an image, and retrieving it back to a file. Using these techniques, you can manage image data in your Java applications effectively.

Comments