JAVA JDBC – Save, Retrieve and Update Image to MySQL Database

In this tutorial you will learn:

1. What is BLOB Type?
2. How to store Image in Database using JDBC?
3. How to retrieve Image from Database?

This tutorial explains, save and retrieve image to MySQL database using JDBC. However, it is not practical to save image in database because image size is big and resources of databases servers are very costly. The most famous way is store image inside a folder and save image path to database. However, sometimes you may want to save image to database. This tutorial is about insert and retrieve picture from MySQL Database.

What is BLOB Type?

You must know what is BLOB Type. BLOB (Binary Large Objects) Type is used to define column in table that store picture. There is no way insert picture directly in the database instead it you need to convert image into binary data type then store that binary value to database. There are 4 types of BLOB that hold binary data in different sizes. You can choose one of the type according to your picture size while creating table.

TYPESIZE
TINYBLOB255 Bytes
BLOB64 KB
MEDIUMBLOB16 MB
LONGBLOB4 GB

Programming Example

Here, I will use a small image (below 64KB) to save into database. If you don’t have smaller image you can download this.

Programming Example

We have a database STOREDB and a Table ITEM inside it. We need to add an extra column SavePic for storing image in it. Here is a JDBC program for adding extra BLOB Type column in ITEM table.

STEP 1 : Adding Extra column SavePic with BLOB type in table Item.

Output

Column SavePic with BLOB Datatype is added Successfully
Closing the connection.
_

 

STEP 2: Inserting Picture to Table

Output

Image Stored Successfully
Closing the connection.
_

Retrieve Image from MySQL Database

Programming Example

Output

ID: 12 Product : MainJava Logo Price : 900
Closing the connection.
_

When you visit the folder location you will see all the images are stored there from database. In my example you can see all your image in this path.

/home/prashant/Documents/image/
 

Updating Image in MySQL Database

Programming Example

Output

Image Updated Successfully
Closing the connection.
_

Summary

In this chapter you learned how to insert, update and retrieve image/picture in JDBC using MySQL Database. Save image to database or insert picture to mysql is very easy if you have understand the basic programming of JDBC. However, I have tried to keed JDBC Image Programming as simple as I can. In the next chapter you will learn how to insert, update or delete files using JDBC.


Leave a Reply

Your email address will not be published. Required fields are marked *