1

How do I store an image into an Oracle database? And how do I retrieve an image from that database? Here is my code:

import java.io.*; 
import java.sql.*; 
import java.util.*; 
class Pic3 
{ 
    public static void main(String args[]) throws Exception 
    { 
        Statement s; 
        Connection c; 
        FileInputStream fis; 
        PreparedStatement ps; 
        File file; 
        try 
        { 
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
            c=DriverManager.getConnection("Jdbc:Odbc:sidhu","system","system"); 
            s=c.createStatement(); 
            s.execute("Create table Img1(Image_No number(5),Photo blob)"); 
        } 
        catch(Exception e1) 
        { 
            e1.printStackTrace(); 
        } 

        try 
        { 
            file=new File("f:/image.jpeg"); 
            fis=new FileInputStream(file); 

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
            c=DriverManager.getConnection("Jdbc:Odbc:sidhu","system","system"); 

            String str="insert into Img1 values(?,?)"; 
            ps=c.prepareStatement(str); 
            ps.setInt(1,(int)file.length()); 
            ps.setBinaryStream(2,fis,(int)file.length()); 

            //System.out.println("success"); 
            ps.execute(); 

            ps.close(); 
            c.close(); 
        } 
            catch(SQLException e) 
        { 
            e.printStackTrace(); 
        } 
    } 
} 
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Bhaskar
  • 13
  • 1
  • 1
  • 3
  • 3
    Don't store images in DB .. store the images in a location and then store the path of the image in the DB. Retrieve the image from the location when ever required. http://stackoverflow.com/questions/1212991/do-you-think-its-a-good-idea-to-save-billions-of-images-into-database – Amarnath Nov 18 '12 at 06:45

1 Answers1

1

change thess lines like this

Class.forName("oracle.jdbc.driver.OracleDriver");
ps.setBinaryStream(2,fis,(byte)file.length());  

instead of

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
ps.setBinaryStream(2,fis,(int)file.length());  

because

JDBC-ODBC bridge driver doesn't support blobs, even if the underlying database does.

sunleo
  • 10,589
  • 35
  • 116
  • 196