Share on Google+Share on Google+

Inserting Image into table

Advertisement
For inserting image, table's field (in which image will be stored) must be define as "blob".
Inserting Image into table 

In this section , we will insert a image into a table. For inserting image, table's field (in which image will be stored) must be define as "blob".

First, Create table'inImage' in "mysql" as--

create table inimage(id int(5)NOT NULL auto_increment,name varchar(30),
city varchar(30),image blob,PRIMARY KEY(id))

For inserting whole image, we have to create an 'InputStream' object from this file. And through this object and "setBinaryStream() ", we pass the binary file content to the BLOB column .

Syntax of "setBinaryStream() " --

setBinaryStream(int parameterIndex, InputStream x, int length) --->The data will be read from the InputStream as needed for "length" bytes. 

insertimage.java

import java.sql.*;
import java.io.*;
 
 class insertimage
{
public static void main(String[] argsthrows SQLException {
  
  Connection con=null;
  ResultSet rs=null;
  PreparedStatement psmt=null;
  FileInputStream fis;
  String url="jdbc:mysql://192.168.10.13:3306/ankdb";
  try{
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  con=DriverManager.getConnection(url,"root","root");

  File image=new File("C:/ankit_jdbc/Child.jpg");

  psmt=con.prepareStatement("insert into inimage(name,city,image)"
  +
"values(?,?,?)");
  psmt.setString(1,"Nitika");
  psmt.setString(2,"Delhi");
  
  fis=new FileInputStream(image);
  
  psmt.setBinaryStream(3(InputStream)fis, (int)(image.length()));
  int s = psmt.executeUpdate();

  if(s>0) {
  System.out.println("Image Uploaded successfully !");
   }
  else {
  System.out.println("unsucessfull to upload image.");
  }
  con.close();
  psmt.close();
  }catch(Exception ex){
  System.out.println("Error in connection : "+ex);
  }
 }
}

 output--

inimage table

CMD O/P

Download this Code

Advertisements

Advertisement

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.