Java code to Store and Retrieve blob data from database

Java to Store and Retrieve picture from Mysql database

This article demonstrate how to store and retrieve blob data from mysql database.Blob data may be of any type of file likely picture,audio or video., here i’ll show you with picture formats.You can download this example


  1. Creating mysql table
  2. GUI and database connection with java
  3. Storing an image into database
  4. Retrieving an image from database

1. Creating mysql table:

Create a database from terminal or command prompt, by using the command

mysql> create database blobtest;

Here blobtest is the table name . Now connect the database using

mysql> connect blobtest;

Connection id: 1

current database: blobtest

Now, Create a table with blob datatype

mysql> create table pictures(id int Auto_Increment primary key, picturedata blob(65535));

That’s it now the table is ready to use..

2. GUI and database connection with java

First you need to download mysql-connector from mysql website and Create a new project like this.





|           |—

|           |—


|           |—mysql-connector-java-5.1.23-bin.jar


|           |—not_avail.png

Here two java files and one mysql library file.where is the main class..

Writing an Manifest file:


Manifest-Version: 1.0

Created-By: Harish Manohar

Class-Path: lib/mysql-connector-java-5.1.23-bin.jar

Main-Class: blobproject.maingui

Now we have to create the file with two textfield, three buttons and one label..

package blobproject;



* @author Harish Manohar


public class maingui extends javax.swing.JFrame {

public maingui() {


this.setSize(400, 300);


private void initComponents() {

upload_btn = new javax.swing.JButton();

browse_btn = new javax.swing.JButton();

filelocationtext = new javax.swing.JTextField();

id_field = new javax.swing.JTextField();

get_btn = new javax.swing.JButton();

pic_box = new javax.swing.JLabel();

jSeparator1 = new javax.swing.JSeparator();





upload_btn.setBounds(260, 60, 90, 28);



browse_btn.setBounds(240, 20, 100, 28);


filelocationtext.setBounds(20, 20, 200, 28);


id_field.setBounds(20, 120, 119, 28);



get_btn.setBounds(100, 160, 60, 28);


pic_box.setBounds(160, 120, 184, 116);


jSeparator1.setBounds(30, 100, 310, 10);




* @param args the command line arguments


public static void main(String args[]) {

/* Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new maingui().setVisible(true);




// Variables declaration

private javax.swing.JButton browse_btn;

private javax.swing.JTextField filelocationtext;

private javax.swing.JButton get_btn;

private javax.swing.JTextField id_field;

private javax.swing.JSeparator jSeparator1;

private javax.swing.JLabel pic_box;

private javax.swing.JButton upload_btn;

// End of variables declaration


Open up terminal or command prompt and perform compilation process like this

Navigate to BlobProject_test using cd command.

javac -cp . blobproject/

java -cp . blobproject.maingui

Now you can see the form

Mainform gui

Next . It contains connection to mysql and methods to perform sql operations

package blobproject;

import java.sql.Connection;

import java.sql.SQLException;

import java.util.Properties;



* @author Harish Manoharan


public class dbengine {

public static String CLIENT_DRIVER = “com.mysql.jdbc.Driver”;

public static String Host = “”;

public static int Port = 3306;


public java.sql.Connection dbconn() throws Exception


//Load JDBC Driver





catch (Exception e) {



String Url = “jdbc:mysql://”+Host+”:”+Port+”/blogtest”;

Properties properties = new java.util.Properties();



return java.sql.DriverManager.getConnection(Url, properties);


public void Connectionclose(Connection conn)


/*Close the connection after use (MUST)*/


try {

System.out.println(“**Database Connection Closed”);


} catch (SQLException ex) {






Now the basic steps for database connection and frame is completed.don’t forget to change the password to your mysql password.

Next we are going to see how to add selected image into database

3.Storing an Image into database:

3.1.Add jFileChooser to with the variable name Picturebrowser.

// Variables declaration

private javax.swing.JFileChooser Picturebrowser;

// …

private void initComponents() {

// ….

Picturebrowser = new javax.swing.JFileChooser();


Picturebrowser.setDialogTitle(“Choose Picture”);

// …


3.2 Now create an action event for browse button.

// Variables declaration

private String path = “”;

private boolean Phupload = false;


private void initComponents() {

// …..

//Add this before pack() at the last line of initComponents method

browse_btn.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {




// …


// …. Add this at above main method

private void browse_btnActionPerformed(java.awt.event.ActionEvent evt) {

int returnval = Picturebrowser.showOpenDialog(this);

if (returnval == javax.swing.JFileChooser.APPROVE_OPTION) { f = Picturebrowser.getSelectedFile();

if (f != null) {

path = f.getAbsolutePath();


Phupload = true;

} else {


Phupload = false;





Here Phupload (boolean) is used to check whether the user actually selected the file or not.

If you run and click on the Browse button an file chooser window appears to choose the file and full path will be displayed on its corresponding text field.

3.4 Creating an action event for upload button:

Here we going to see how to save an choosed image into database using query.



import java.sql.Blob;

import java.sql.PreparedStatement;

import javax.swing.ImageIcon;


public void uploadimage(boolean Choosed,String filepath)


if (Choosed == true) {

try {

java.sql.Connection conn = dbconn();

String sql =”insert into pictures(picturedata) values(?)”;

PreparedStatement pre = conn.prepareStatement(sql);

Blob blob = conn.createBlob();

//This statement will scale the image into 96 px X 96 px.

java.awt.Image img = java.awt.Toolkit.getDefaultToolkit().createImage(filepath).getScaledInstance(96, 96, 0);

ImageIcon ii = new ImageIcon(img);

ObjectOutputStream oos;

oos = new ObjectOutputStream(blob.setBinaryStream(1));



pre.setBlob(1, blob);



} catch (Exception e) {




else{ System.out.println(“Please choose the picture using browse button”);}


//.. Globally

dbengine db = new dbengine();


private void initComponents() {

// …..

//Add this before pack() at the last line of initComponents method

upload_btn.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {




// …


private void upload_btnActionPerformed(java.awt.event.ActionEvent evt) {

db.uploadimage(Phupload, path);


Now the selected picture will be uploaded into database by clicking upload button after file choosed.

4. Reading image from database.

This will help you to read an image from database and display it in label field.Here a simple logic plays important role that, if image data not found in database or not valid then the not_avail.png will be displayed in the label.



import java.sql.ResultSet;


public ImageIcon readimage(int id)


ImageIcon image = null;


java.sql.Connection Conn = dbconn();

String sql =”select * from pictures where id = “+id+” “;

PreparedStatement pre = Conn.prepareStatement(sql);

ResultSet rs = pre.executeQuery();

if( == true)//Data found


Blob photo = rs.getBlob(“picturedata”);

if(photo != null) {

ObjectInputStream ois = null;

ois = new ObjectInputStream(photo.getBinaryStream());

image = (ImageIcon) ois.readObject();


image = new javax.swing.ImageIcon(getClass().getResource(“/icon/not_avail.png”));



image = new javax.swing.ImageIcon(getClass().getResource(“/icon/not_avail.png”));



}catch(Exception e){System.out.println(e.getMessage());}

return image;



private void initComponents() {


get_btn.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {







private void get_btnActionPerformed(java.awt.event.ActionEvent evt) {




Now Pack project as archieve jar file and run the jar using java -jar filename.jar

Here is the link to create jar archieve


Choose file as you desired and click upload button

Screenshot from 2014-06-04 00:53:31Now enter the id number in the second text box and click Get to read from database

Screenshot from 2014-06-04 00:53:55

All done. Hope this will be useful to you in any way.

Java to create JAR file included with jar libraries

Java to create JAR file included with jar libraries

A JAR file is still a .zip file, but includes a special manifest file to identify its contents.

Suppose you have the directory structure with several .class files and images directory and some libraries used in your project. You could use the jar utility to put all these into a new JAR file which you can name it of your projectname.jar

The general format for the jar command is

jar options filenames

The first file named in the filenames list is the name of the archive.

You can study options through command.

jar -h

Basically its an help command..

Creating an jar archive:

In order to make new archive, then use

jar cf YourJar.jar *.class images/*.png lib/*.jar

If you had prepared a manifest file called MANIFEST.MF then

jar cfm YourJar.jar MANIFEST.MF *.class images/*.png lib/*.jar

Adding libraries into your classpath

Let us consider your project contains mysql-connector.jar , mail.jar and activation.jar libraries, and images and some other packages with class file for example





| |—

| |—


| |—

| |—


| |—icon.png

| |—pic.png


| |—mysql-connector.jar

| |—mail.jar

| |—activation.jar

Now you want to put all these files and folders into an jar archieve,

First, you need to create a MANIFEST.MF file, with text editor add these lines

Manifest-Version: 1.0

Created-By: Harish Manohar

Class-Path: lib/mysql-connector.jar lib/mail.jar activation.jar

Main-Class: package.mainclass

Now Compile your java files using javac command

and if you to add all your source files and class files, you can use

jar cfm Myproject.jar MANIFEST.MF -C c:/YourProject/ .

Note: it will store all your files under YourProject folder including java files.

If you want to add only class files.,then navigate to your project folder using cd command, then type

jar cfm Myproject.jar MANIFEST.MF package/*.class anotherpackage/*.class images/*.png lib/*.jar

Now execute the jar using command

java -jar Myproject.jar

All done., Hope it will be useful to you in any way.

Showing Shortcut folders in Windows

In this post , a basic page on how to show your hidden files by command prompt. This will help you when your drive files are hidden and your folders are generated as exe file..

Let us assume your drive is h:

Open command prompt and type h:

 h:>attrib -s -h /s /d *.*

this command show up all your hidden folders and files.


Hope this will be helpful in any situation..Thank you