Thursday, January 20, 2011

Insert blob files into Oracle using Java




In this article  I will discuss how to insert a image into database table using PreparedStatement interface of java. All other blob files can be handled in same way. You will need ojdbc6.jar as the oracle driver. If you try to use ojdbc14.jar you may get the following exception :

Exception in thread "main" java.lang.AbstractMethodError:
 Theoracle.jdbc.driver.T4CPreparedStatement.setBinaryStream(ILjava/io/InputStream;)V


Now let's create a database table using the following sql command.

create table imagetable ( imageid numeric(5) , image blob);

Now use the following java code to insert a image in the table.

Class.forName("oracle.jdbc.driver.OracleDriver"); 
Connection connect = DriverManager.getConnection  
                       ("jdbc:oracle:thin:@IP_ADDRESS:PORT_NUMBER/SERVICE_NAME" ,"username","password"); 
String filename = "Your filename here" ; 
InputStream input = new FileInputStream(filename); 
PreparedStatement pstmt = connect.prepareStatement("insert into imagetable values(?,?)"); 
pstmt.setBinaryStream(2, input); 
pstmt.setInt(1, 1); 
pstmt.execute();


Also change the connection parameters according to your's.

9 comments:

  1. how can you set a cblob data??? you use setString instead setBinaryStream??

    ReplyDelete
    Replies
    1. I assume cblob here actually means clob. I personally didn't worked with clob data. But it seemed to me that setCharacterStream() of PreparedStatement can help you.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Your topic is very nice and helpful to us … Thank you for the information you wrote.

    Learn Hadoop Training from the Industry Experts we bridge the gap between the need of the industry. Bangalore Training Academy provide the Best Hadoop Training in Bangalore with 100% Placement Assistance. Book a Free Demo Today.
    Big Data Analytics Training in Bangalore
    Tableau Training in Bangalore
    Data Science Training in Bangalore
    Workday Training in Bangalore

    ReplyDelete
  4. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.sap abap training in bangalore

    ReplyDelete