Write an JDBC example to retrieve Clob value from a table using the getCharacterStream() method?

The ResultSet interface provides the method named getClob() to retrieve clob datatype from a table in a database. In addition to this it also provides a method named getCharacterStream()

Like getClob() this method also accepts an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column. The difference is unlike the getClob() method (which returns a Clob object) this method returns an object of the Reader class.


Assume we have created a table named MyData in the database with the following description.

| Field   | Type         | Null | Key | Default | Extra |
| Name    | varchar(255) | YES  |     | NULL    |       |
| Article | longtext     | YES  |     | NULL    |       |

And, we have inserted large textual data in it with name JavaFX. Following program retrieves the contents of the table MyData using the getString() and getCharacterStream() methods.

import java.io.FileWriter;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingClob_CharStream {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      //retrieving the data
      ResultSet rs = stmt.executeQuery("select * from MyData");
      int j = 0;
      System.out.println("Contents of the table are: ");
      while(rs.next()) {
         Clob clob = rs.getClob("Article");
         Reader r = clob.getCharacterStream();
         String filePath = "E:\Data\clob_output"+j+".txt";
         FileWriter writer = new FileWriter(filePath);
         int i;
         while ((i=r.read())!=-1) {


Connection established......
Contents of the table......

If you observe the file in the obtained path you can see the contents of the Clob retrieved from the table as shown below: