Friday, 18 July 2014

JDBC Scrollable ResultSet

Enjoying This Java Tutorial?

Subscribe to our YouTube channel for clear, beginner-friendly Java and database programming tutorials!

SUBSCRIBE NOW

What is a Scrollable ResultSet?

When you execute a query in JDBC, the cursor of a standard ResultSet begins positioned right before the first row and can only navigate in a forward direction. You cannot move backward or jump directly to a previous record.

A Scrollable ResultSet eliminates this limitation. It allows your cursor to move both forward and backward, jump to specific row numbers (e.g., jump to row 5, then row 10, then back to row 8), and retrieve column data with total navigation freedom.

How to Create a Scrollable ResultSet

By default, the createStatement() method produces a forward-only, read-only ResultSet. To make it scrollable, pass specific configuration constants for ResultSet Type and Concurrency Type:

Statement stmt = connection.createStatement(
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY
);
ResultSet rs = stmt.executeQuery("SELECT * FROM Employee");

You can also create scrollable result sets using PreparedStatement by passing the query followed by the type and concurrency parameters:

PreparedStatement pstmt = connection.prepareStatement(
    sqlQuery,
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY
);

Understanding ResultSet Types & Concurrency

JDBC provides clear constants in the ResultSet interface to customize cursor behavior:

  • TYPE_FORWARD_ONLY: The default mode. The cursor moves solely forward from row to row.
  • TYPE_SCROLL_INSENSITIVE: The cursor moves both forward and backward. It creates a snapshot of data and is not sensitive to concurrent database changes.
  • TYPE_SCROLL_SENSITIVE: The cursor navigates bidirectionally and reflects live updates made to the database rows while open.
  • CONCUR_READ_ONLY: The returned ResultSet records cannot be edited or updated.
  • CONCUR_UPDATABLE: Allows modifying, inserting, or deleting rows directly using the ResultSet object.

Why Use Scrollable ResultSets?

Scrollable ResultSets give you complete control when rendering data in pagination interfaces, generating detailed reports, or scanning through datasets in reverse order without needing repeated queries to the database server.

Related Tutorials You Might Like


Click here to watch in Youtube : https://www.youtube.com/watch?v=QskO3Y16Stg

Click the below Image to Enlarge
Scrollable ResultSet
Scrollable ResultSet
Scrollable ResultSet
Scrollable ResultSet
See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Tutorials