Share on Google+Share on Google+

Inserting Image in Database Table

In this section, you will learn to insert an image to the MySQL database table.

Inserting Image in Database Table


In this section, you will learn to insert an image to the MySQL database table. 

Flow of the process :

This program helps the user to insert an image in the MySQL database table. To insert an image, you need to establish a connection with MySQL database. Lets' take a database hibernatetutorial, in our case. This database has a table (Image table). For inserting an image in table, we have used the SQL statement ?INSERT INTO Image values(?,?,?)? with the prepareStatement() method. Whenever an image is inserted into the database, it displays ?Inserting Successfully?. If it fails to insert an image then it throws an exception.

[Note: The table has a specified field (or data type) to store an image of type e.g. Blob]

Here is the Code of Program :

import java.sql.*;

public class insertImage{
  public static void main(String[] args) {
  System.out.println("Insert Image Example!");
  String driverName = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "hibernatetutorial";
  String userName = "root";
  String password = "root";
  Connection con = null;
  con = DriverManager.getConnection(url+dbName,userName,password);
  Statement st = con.createStatement();
  File imgfile = new File("images.jpg");
  FileInputStream fin = new FileInputStream(imgfile);
  PreparedStatement pre = con.prepareStatement("insert into Image values(?,?,?)");
  System.out.println("Inserting Successfully!");
  catch (Exception e){

Download this code.

Output of this Program:


C:\Roseindia\vinod\jdbc4.0>java insertImage
Insert Image Example!
Inserting Successfully!


Table Name: Image




Posted on: October 25, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Inserting Image in Database Table   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Swapnil And Lalit
April 2, 2011

We were facing the huge problem for uploading and downloading image through jsp in mysql by using your code. we were successful to upload the image.