Home Jdbc Jdbc-mysql Inserting Image in Database Table
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Inserting Image in Database Table

Advertisement
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.*;
import java.io.*;

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;
  try{
  Class.forName(driverName);
  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(?,?,?)");
  pre.setInt(1,5);
  pre.setString(2,"Durga");
  pre.setBinaryStream(3,fin,(int)imgfile.length());
  pre.executeUpdate();
  System.out.println("Inserting Successfully!");
  pre.close();
  con.close();  
  }
  catch (Exception e){
  System.out.println(e.getMessage());
  }
  }
} 

Download this code.

Output of this Program:

C:\Roseindia\vinod\jdbc4.0>javac insertImage.java

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

C:\Roseindia\vinod\jdbc4.0>

Table Name: Image

Durga.jpg

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  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.

Posted on: October 25, 2007

Related Tutorials

Ask Questions?    Discuss: Inserting Image in Database Table   View All Comments

Post your Comment


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

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.
DMCA.com