How to store data in CLOB field in db2 using java code

CLOB is Character Large Objects which is used to store large volume of character data. The default size for CLOB is 1 mb. It can contain up to 2 gigabytes of character data. The data is stored in the database as text and is processed the same way as a CHAR column. JDBC 2.0 provides functions for dealing directly with CLOBs.

Data is stored in CLOB field by setClob or setString method of the PreparedStatement interface and the data is retrieved by the getClob or getString method of ResultSet interface. When reading data,  a block of rows are fetched from the database.  The block of CLOBs are not moved to the ResultSet instead only pointers (LOB locators (4 byte integers)) are moved into the ResultSet.

Now we are going to see how to write CLOB data in a table using code.  For that excise, we have to create a table with CLOB field. In our example , news table is created which is having the fields of News_Id, 
News_in_Detail .

 The field News_in_Detail is a Clob field. Clob object can be created using the following ststement

               Clob clob = rset.getClob(columnno);   where rset is the result set of a table containing CLOB field.

In the below example code, 2 records are inserted. One record using pstmt.setString(..) and record another using clob object.


package com.javaonline;

import java.sql.*;
import java.lang.StringBuffer;
public class DB2CLOB {
   public static void main(String[] args) 
   throws SQLException 
       try {
         // Class.forName("");
      } catch (Exception e) {
      Connection con = DriverManager.getConnection("jdbc:db2:test");    
      Statement stmt=null;

   try {     
         stmt = con.createStatement();
       //table creation (One time only)
         stmt.executeUpdate("CREATE TABLE News (News_Id varchar (10) , Subject varchar (50) , Event_date Date,  Involved varchar (100) ,Location varchar(25),  News_in_Detail  CLOB)");
   } catch (Exception e) {
      System.out.println("Tables already created , skipping create table statement");
      String newsid, subject, eventdate, involved, location , newsindetail;
      StringBuffer buffer=new StringBuffer(5000);
       int success=0;
       PreparedStatement pstmt = con.prepareStatement("INSERT INTO News VALUES(?,?,?,?,?,?)");
//Ist record to be inserted
       subject="Sports Cricket";
       eventdate= "2011-05-20";
       involved="England , WI";
       buffer.append("Date : 20/05/2011, In the first match of the tri series, England won the toss and elected to bat and put score of 250 in 50 overs losing 8 wickets ...."  );
       newsindetail = buffer.toString();
        pstmt.setString(1, newsid);
        pstmt.setString(2, subject);
        pstmt.setString(3, eventdate);
        pstmt.setString(4, involved);
        pstmt.setString(5, location);
        pstmt.setString(6, newsindetail);
         success =    pstmt.executeUpdate();
        if(success>=1)  System.out.println("1 Row Inserted");
//IInd record to be inserted using clob object. 
        eventdate= "2011-01-20";
        buffer= new StringBuffer("Sachin is one of best the batsman in India. He is having  wonderful records in Test Matches  as well as Oneday matches ...."  );
        newsindetail = buffer.toString();     
        ResultSet rset = stmt.executeQuery("SELECT * FROM News");;
        Clob clob = rset.getClob(6);  // clob object is created
        System.out.println("News= "+clob.getSubString(1,(int)clob.length()-1)); //printing clob value
        //clob.truncate((long) 15000);  // new length can be assigned
        int nocw= clob.setString((long)18,newsindetail); // New string is stored
        pstmt.setString(1, newsid);
        pstmt.setString(2, subject);
        pstmt.setString(3, eventdate);
        pstmt.setString(4, involved);
        pstmt.setString(5, location);
        pstmt.setClob(6, clob);  // using setClob 
          success =    pstmt.executeUpdate();
        if(success>=1)  System.out.println("1 Row Inserted"); 
      con.close(); // Connection closed 

Leave a Reply

best male size enhancement pills king size male enhancement amazon size rx male enhancement formula energy pill sex tablets name for man viagra dosages drug elexan patch male enhancement extenze liquid and pills taken male enhancement and sexual health barbados penis enlargement penis enlargement natural supplement male enhancement growmax penis enlargement p ed blue pills dr c for penis enlargement sex performance enhancing drugs sarms and penis enlargement nonsurgical penis enlargement the best viagra pills gas station sex pills florida drug strength chart free trial of male enhancement drugs to cause erectile dysfunction xgain sex pills rvxadryl male enhancement joe buck ed pills magnum gold male enhancement pain pills and male sex drive ace in the hole male enhancement brazilian penis enlargement gel scenar penis enlargement cost of one viagra pill penis enlargement time ed pills for daily use pills yo make penis longer erection pills over counter knight sex pills k 9 blue pill golden lion sex pills hard sex pills 54 373 pill epic male enhancement phone number side affects of drugs male sex enhancer with sildenafil how can i get viagra pills male enlargment pills about viagra tablets green pill e 7 denver penis enlargement collagen rx gold male enhancement review male enhancement pills call center campaigns cnc non prescription erection pills

what are the best weight loss pills best pills for weight loss and energy 500 calorie diet weight loss results most effective otc weight loss pill keto advanced diet pills review weight loss diet in tamil free recipes for the keto diet kids weight loss diet keto diet recipes best supplement drinks to lose weight keto diet recipes for camping dr oz green tea weight loss pill lose weight quickly detox diet the protein shake diet for weight loss easy diet to lose weight fast for free 4life weight loss pills what is a good supplements to lose weight beginner diet for weight loss acv tablets for weight loss anti naflammatory diet for weight loss science diet weight loss system for dogs amino acid weight loss supplement fast weight loss free diets no meat diet for weight loss ketodiet cookbook cheap weight loss pills that work 2020 how to begin the keto diet keto vegetarian diet recipes folic acid pills weight loss where to buy turmeric pills weight loss types of birth control pills for weight loss does high protein low carb diet cause weight loss meridian health plan insurance weight loss pills mega t green tea weight loss pills side effects aid weight loss pills most healthy diet for weight loss the best pills for weight loss uk why does ketogenic diet cause weight loss warrior diet rapid weight loss natural pills to lose weight weight loss diet for diverticulitis weight loss bodybuilding diet plan laxatives for weight loss diet diet pills fast weight loss canned soup diet weight loss statin drugs weight loss health weight loss diet plan fast paced diet for weight loss olivia munn diet body weight loss best diets for weight loss 2020 high fibre diet for weight loss model weight loss diet plan

cbd thc ratio for pain cbd from industrial hemp cbd influencers cbd dosage for humans straight hemp cbd how to use cbd oil for breast cancer cbd dental care cbd oil sold near me what is cbd in medical terms how to use cbd oil for nausea cbd oil skin benefits hemp cbd strains cbd water reviews cbd oil shopify cbd oil santa barbara cbd oil green roads which cbd oil is best for cancer how long does cbd oil last redfit cbd oil and leukemia price for cbd oil cbd ebooks od on cbd effects of cbd on fetus cost of 500 mg cbd oil cbd oil cold pressed black cbd oil cbd cream psoriasis diamond cbd synthetic cbd capsules 25mg amazon cbd oil following surgery pain relief from cbd oil cbd american shaman coupon code how many cbd drops northstar naturals cbd oil cbd oil superior wi cbd oil plus coupon where to buy cbd oil in myrtle beach sc gold cbd oil for sale golden oil cbd cubed cbd cbd oil for vision cbd and heart health how much cbd oil from plant new you cbd oil hempamericana cbd oil can cbd cause anxiety seattle cbd oil companies whats the highest concentration cbd oil high quality cbd oil grapefruit physicians preferred cbd cbd cannabidiol oil vs hemp oil cbd oil business