How to Insert Image in MySQL Database Using Java

In this short tutorial, we will learn how to insert an image into a MySQL database table using Java (JDBC).

Some developers prefer to put their images into the database, some prefer to keep them on the file system for their applications. Technical difficulties arise when we work with lots of images. Images are binary data. MySQL database has a special data type to store binary data called BLOB (Binary Large Object).

Next tutorial - How to Read Image from MySQL Database in Java.
Checkout complete JDBC tutorial at Java Database Connectivity Tutorial.
You can download source code from my GitHub repository(the link given at end of this tutorial).

Tools and Technologies Used

  1. Java 1.8+
  2. MySQL connector - 8.0.5
  3. Eclipse IDE
  4. Maven
Make sure that you have installed the MySQL server into your machine.

Add MySQL Dependency

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.15</version>
</dependency>

Database Setup

Use the following statement to create a database:
mysql> create database demo;
To hold an image in MySQL database generally blob type is used. Therefore, let's create Images table in an above-created database with a blob datatype:
mysql> CREATE TABLE Images(Id INT PRIMARY KEY AUTO_INCREMENT, Data MEDIUMBLOB);
Images are binary data. MySQL database has a special data type to store binary data called BLOB (Binary Large Object). There are four BLOB types are TINYBLOBBLOBMEDIUMBLOB, and LONGBLOB
In this example, we are using a MEDIUMBLOB type. Read more about MEDIUMBLOB type at https://dev.mysql.com/doc/refman/8.0/en/blob.html.

Insert Image into MySQL Database using Java

In the example, we read a PNG image from the current working directory and insert it into the Images table.
package net.javaguides.jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Class demonstrate Inserting Image into MySQL Database using Java
 * @author Ramesh Fadatare
 *
 */
public class JdbcWriteImage {

    public static void main(String[] args) {

        String cs = "jdbc:mysql://localhost:3306/demo?useSSL=false";
        String user = "root";
        String password = "root";

        String sql = "INSERT INTO Images(Data) VALUES(?)";

        try (Connection con = DriverManager.getConnection(cs, user, password); PreparedStatement pst = con.prepareStatement(sql)) {

            File myFile = new File("image.png");
            try (FileInputStream fin = new FileInputStream(myFile)) {

                pst.setBinaryStream(1, fin, (int) myFile.length());
                pst.executeUpdate();

            } catch (IOException ex) {

                Logger lgr = Logger.getLogger(JdbcWriteImage.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        } catch (SQLException ex) {

            Logger lgr = Logger.getLogger(JdbcWriteImage.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
}
You can check the record inserted in Images table using select statement:
select * from Images;
Let's understand the above program.
This is the SQL to insert an image:
String sql = "INSERT INTO Images(Data) VALUES(?)";
We create a File object for the image file. To read bytes from this file, we create a FileInputStream object:
File myFile = new File("image.png");
try (FileInputStream fin = new FileInputStream(myFile)) {
...
}
The binary stream is set to the prepared statement:
pst.setBinaryStream(1, fin, (int) myFile.length());
We execute the statement:
pst.executeUpdate();
Learn complete JDBC tutorial at https://www.javaguides.net/p/jdbc-tutorial.html.
The source code examples available on my GitHub Repository. 

Comments