Scrollable Result Set Using JDBC In Java

LEVEL: Intermediate

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click  View Source “View Source” on the right of this code snippet.

Background and Explanation of the code

This program connects to MySQL database using Type-4 JDBC driver. To get and configure database driver, follow the instructions provided on following post:

http://codingzone.net/java/accessing-mysql-database-table-using-type-4-driver-in-java

In this program we are using scrollable ResultSet to retrieve data from database. A default ResultSet object has a cursor that moves forward only. You also can not set cursor on a particular position directly to fetch required data. Following syntax in the program makes the ResultSet scrollable and read only:
statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);

To compile the program: javac ScrollableResultsetDemo.java

To run the program: java ScrollableResultsetDemo

The attached output displays records from table in both direction, forward and backward.