Friday, July 20, 2012

Clob datatype , oracle and java

Recently I worked with clob data of oracle. Using java , I found the following code works for the following purpose
- inserting clob data to a database table 
- retrieve clob data from database .


Assuming that reader has already executed the following sql command

create table testclob( _id numeric(5) , data clob );

variable name is not important . What is important is the table structure.


For inserting the following code suffices -
        
PreparedStatement pstmt = conn.prepareStatement("insert into testclob values(?,?)");
        
pstmt.setInt(1, 1);
pstmt.setCharacterStream(2, new FileReader(new File("hello.txt")));
pstmt.execute();
        
        
For retrieving data, the code is given below
         
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("select * from testclob");
while( result.next() )
{
     Clob clob = result.getClob(2);
     Reader in = clob.getCharacterStream();
     char[] buffer = new char[(int)clob.length()];
            
     in.read(buffer);
     System.out.println(buffer); 
} 

As oracle driver , ojdbc6.jar is used.