Java Clob getSubString()

In this guide, you will learn about the Clob getSubString() method in Java programming and how to use it with an example.

1. Clob getSubString() Method Overview

Definition:

The getSubString() method of the Clob interface retrieves a part of the CLOB value designated by this Clob object as a String. This allows you to fetch a portion of large text data without loading the whole Clob content into memory.

Syntax:

String getSubString(long pos, int length) throws SQLException

Parameters:

- pos: is the first character of the substring to be extracted. The first character is at position 1.

- length: is the number of consecutive characters to be copied.

Key Points:

- The method returns a String object containing the substring of length from the CLOB value designated by this Clob object.

- The getSubString() method throws an SQLException if the pos is less than 1, the length is less than 0, or the starting position plus length is greater than the length of the CLOB value.

- The method should be used when you need a part of CLOB data, as retrieving large Clob data fully can be expensive in terms of memory and performance.

2. Clob getSubString() Method Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Clob;
import java.sql.SQLException;

public class GetSubStringExample {

    public static void main(String[] args) {

        String url = "jdbc:your_database_url";
        String user = "your_database_user";
        String password = "your_database_password";

        String selectSql = "SELECT clob_column FROM your_table WHERE id = 1";

        try (Connection connection = DriverManager.getConnection(url, user, password);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(selectSql)) {

            if (resultSet.next()) {
                Clob clob = resultSet.getClob("clob_column");
                String subString = clob.getSubString(1, 200); // Retrieve first 200 characters
                System.out.println(subString);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Output:

[The first 200 characters of the CLOB data]

Explanation:

In this example, a connection to the database is established, and a SELECT query is executed to retrieve a Clob object from the database. 

The getSubString() method of the Clob interface is then used to fetch the first 200 characters of the CLOB data. This substring is then printed to the console. If a SQLException occurs at any point in this process, it is caught and printed to the console.

Comments