03
Oct

Save image file into database

Saving Image file into Databases..

In this post, we will show you how to save a long binary string or image file into a BLOB (Binary Large Object) column of a database table using the JDBC API.

The PreparedStatement#setBinaryStream() method is used to save the binary string into a database as a InputStream, whereas the PreparedStatement#getBinaryStream() return a OutputStream to read binary string from a database.

Table Structure:

The following is a SQL statement for table creation in MySQL database.

CREATE TABLE user_profile (

USER_ID INT NOT NULL AUTO_INCREMENT,

NAME VARCHAR(45) NOT NULL,

IMAGE BLOB NULL,

PRIMARY KEY (USER_ID));

Save image into database example

Here is an example of inserting an image file into a database.

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;

/**

* @author imssbora

*/

public class ImageFileSaveExample {

public static void main(String[] args) {

String jdbcUrl = “jdbc:mysql://10.9.121.6:3306/DBName”;

String username = “username”;

String password = “pwd”;

String sql = “INSERT INTO USER_PROFILE(NAME,IMAGE) VALUES(?,?)”;

try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password);) {

File image = new File(“sample.jpg”);

try (FileInputStream inputStream = new FileInputStream(image);

PreparedStatement stmt = conn.prepareStatement(sql);) {

stmt.setString(1, “Mike”);

stmt.setBinaryStream(2, inputStream, image.length());

stmt.executeUpdate();

System.out.println(“Image saved successfully.”);

} catch (IOException e) {

e.printStackTrace();

}

} catch (SQLException e) {

e.printStackTrace();

}

}

}

Output:

Image saved successfully.