Friday, January 28, 2011

Java program to insert image as byte array to postgres database

//Program to insert an image into postgres database as byte array

import java.sql.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class insertImage
{
  public static void main(String[] args)
  {
    PreparedStatement statement = null;
    {
      FileInputStream fin = null;
      try
      {
        System.out.println("Insert Image Example!");
        Class.forName("org.postgresql.Driver");
        String url = "jdbc:postgresql://x.x.x.x:5432/MYDB";
        Connection oConnection = DriverManager.getConnection(url, "username", "password");
        System.out.println("Sucessfully connected to Postgres Database");
        File imgfile = new File("myimage.jpg");
        fin = new FileInputStream(imgfile);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        for (int readNum; (readNum = fin.read(buf)) != -1;)
        {
          bos.write(buf, 0, readNum);
          byte[] bytes = bos.toByteArray();
          String sql = "INSERT INTO my_table (byte_array) VALUES (?)";
          statement = oConnection.prepareStatement(sql);
          statement.setBytes(1, bytes);
          statement.executeUpdate();
          System.out.println("Image inserted into database!");

        }
        statement.close();
        oConnection.close();
      }
      catch (Exception ex)
      {
        System.out.println("Exception:- " + ex);
      }
      try
      {
        fin.close();
      }
      catch (IOException ex)
      {
        System.out.println(" IOException:- " + ex);
      }
    }
  }
}

4 comments:

Thanks for visiting my Blog....Ur comments n suggestions are most valuable for me...Thanks