Skip to end of metadata
Go to start of metadata

Author: Milton Ghosh
Submitted: July 3, 2007

This was a requirement in my project where the xml was stored in the oracle database as JDBC type CLOB and while retrieving the xml it was to be converted to string (subsequently to string buffer) for parsing

The method to convert Clob to string is given below

import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Clob;
import java.sql.SQLException;
public class ClobStringConversion { 
public static String clobStringConversion(Clob clb) throws IOException, SQLException
     {
       if (clb == null)
      return  "";
             
       StringBuffer str = new StringBuffer();
       String strng;
               
     
     BufferedReader bufferRead = new BufferedReader(clb.getCharacterStream());
    
       while ((strng=bufferRead .readLine())!=null)
        str.append(strng);
    
       return str.toString();
     }        
}

The class to retrieve the xml from database

import java.sql.Clob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.sap.db.DataBaseConnection;
import com.sap.utils.ClobToString; 

public class ReadXML{
 public StringBuffer readXml(int xmlID) {     
   StringBuffer xmlContent = null;
   String xmlContents = null;
   Clob xmlCont;
   ResultSet rset = null;
   String query = null;
   Connection conn = null;
   Statement stmt = null;
         try {
    conn = DataBaseConnection.getConnection();
    stmt = conn.createStatement();   
    query ="select xs.xml from xmlTable xs where xmlId='"+xmlID+"'";
    rset = stmt.executeQuery(query);
    while (rset.next()) {               
       xmlCont = rset.getClob("xml");
       xmlContents = ClobStringConversion .clobStringConversion (xmlCont);
       xmlContent = new StringBuffer(xmlContents);   
   }
    } catch (Exception ex) {
    System.out.println(ex);   
  }
finally {
    try {
     stmt.close();
     conn.close();
    } catch (SQLException e) {
     
     e.printStackTrace();
    }  
 }
   return xmlContent;  }
}