Programming Geek
Rated 4.7/5 based on 1446 reviews

Inserting Image in Database using JDBC

The following program reads an image character by character and inserts in database:

import java.sql.*;
import java.io.*;
public class BlobImages{
 public static void main(String[] args)    throws Exception 
 {
  try {
   Class.forName("com.ibm.db2.jcc.DB2Driver");
  } catch (Exception e) {
   System.out.println(e);
   System.exit(0); 
  }
  Connection con = DriverManager.getConnection("jdbc:db2://127.0.0.1:50000/SAMPLE","db2admin","db2admin");    
  Statement stmt=null;
  try {     
   stmt = con.createStatement();
   //to create table with blob field (One time only)
   stmt.executeUpdate("CREATE TABLE EmpPhoto (EmpId varchar (10) , EmpName varchar (50) , EmpPhoto BLOB (5M), filePath varchar(100))");
  } catch (Exception e) {
   System.out.println("Tables already created , skipping table creation process");
  }
  String empId="3222";
  String empName="John";
  String empPhotoFile="D:\\v\\Bhubaneswar@Infy\\about.png"; // photo file name
  int success=0;
  PreparedStatement pstmt = con.prepareStatement("INSERT INTO EmpPhoto VALUES(?,?,?,?)");
  pstmt.setString(1, empId);
  pstmt.setString(2, empName);
  pstmt.setBytes(3,readImage(empPhotoFile));   
  pstmt.setString(4,empPhotoFile);
  success =    pstmt.executeUpdate();
  if(success>=1)  System.out.println("New Employee detail added");
  
  

  ResultSet rs = stmt.executeQuery("Select * from EmpPhoto");  

  
  
  if (rs.next()) {  

   String filename = "vvv.png";  
   Blob blob = rs.getBlob("EmpPhoto");  
   InputStream is = blob.getBinaryStream();  
   FileOutputStream fos = new FileOutputStream("D:\\" + filename);  

   int b = 0;  
   while ((b = is.read()) != -1)  
   {  
    fos.write(b);   
   }  
  }   con.close(); 
 }
 //to read image from the physical file. 
 private static byte[] readImage(String filename) {

  byte[]  imageData = null;
  FileInputStream file = null;
  try {
   file = new FileInputStream(filename);
   int size = file.available();
   imageData = new byte[size];
   file.read(imageData);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (file != null) file.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return imageData;
 }
}

No comments :

Post a Comment