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 https://www.dropbox.com/s/201r9vrxe6ym50x/project.zip

Steps:

  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.

BlobProject_test

|

|——MANIFEST.MF

|——blobproject

|           |—-maingui.java

|           |—-dbengine.java

|——lib

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

|—–icon

|           |—not_avail.png

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

Writing an Manifest file:

MANIFEST.MF

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 maingui.java file with two textfield, three buttons and one label..

maingui.java

package blobproject;

/**

*

* @author Harish Manohar

*/

public class maingui extends javax.swing.JFrame {

public maingui() {

initComponents();

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();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

getContentPane().setLayout(null);

upload_btn.setText(“Upload”);

getContentPane().add(upload_btn);

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

browse_btn.setText(“Browse”);

getContentPane().add(browse_btn);

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

getContentPane().add(filelocationtext);

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

getContentPane().add(id_field);

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

get_btn.setText(“Get”);

getContentPane().add(get_btn);

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

getContentPane().add(pic_box);

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

getContentPane().add(jSeparator1);

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

pack();

}

/**

* @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/maingui.java

java -cp . blobproject.maingui

Now you can see the form

Mainform gui

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

dbengine.java

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 = “127.0.0.1”;

public static int Port = 3306;

//Connection

public java.sql.Connection dbconn() throws Exception

{

//Load JDBC Driver

try

{

Class.forName(CLIENT_DRIVER).newInstance();

}

catch (Exception e) {

System.out.println(e.getMessage());

}

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

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

properties.setProperty(“user”,”root”);

properties.setProperty(“password”,”yourpassword”);

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

}

public void Connectionclose(Connection conn)

{

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

if(conn!=null){

try {

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

conn.close();

} catch (SQLException ex) {

System.out.println(ex.getMessage());

}

}

}

}

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 maingui.java with the variable name Picturebrowser.

// Variables declaration

private javax.swing.JFileChooser Picturebrowser;

// …

private void initComponents() {

// ….

Picturebrowser = new javax.swing.JFileChooser();

Picturebrowser.setApproveButtonText(“Choose”);

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) {

browse_btnActionPerformed(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) {

java.io.File f = Picturebrowser.getSelectedFile();

if (f != null) {

path = f.getAbsolutePath();

filelocationtext.setText(path);

Phupload = true;

} else {

filelocationtext.setText(“”);

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.

dbengine.java

//imports

import java.io.ObjectOutputStream;

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));

oos.writeObject(ii);

oos.close();

pre.setBlob(1, blob);

pre.execute();

Connectionclose(conn);

} catch (Exception e) {

System.out.println(e);

}

}

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

}

maingui.java

//.. 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) {

upload_btnActionPerformed(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.

dbengine.java

//Imports

import java.io.ObjectInputStream;

import java.sql.ResultSet;

///….

public ImageIcon readimage(int id)

{

ImageIcon image = null;

try{

java.sql.Connection Conn = dbconn();

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

PreparedStatement pre = Conn.prepareStatement(sql);

ResultSet rs = pre.executeQuery();

if(rs.next() == true)//Data found

{

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

if(photo != null) {

ObjectInputStream ois = null;

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

image = (ImageIcon) ois.readObject();

}else{

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

}

}else{

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

}

Connectionclose(Conn);

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

return image;

}

////….

maingui.java

private void initComponents() {

//….

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

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

get_btnActionPerformed(evt);

}

});

//…

}

//…

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

pic_box.setIcon(db.readimage(Integer.parseInt(id_field.getText())));

}

//…

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

Here is the link to create jar archieve

https://harishmanohar.wordpress.com/2014/06/04/java-to-create-jar-file-included-with-jar-libraries/

Result:

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.