Pages

Friday, May 7, 2010

JDBC- Scrollable ResultSet

JDBC- Scrollable ResultSet
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. Scrollable result sets make it easy to create a graphical interface for browsing result set data, which will probably be one of the main uses for this feature. Another important use is moving the cursor to a row so that you can make updates to that row.

Following code fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by others, and that is updatable

The updater methods may be used in two ways:
1. In a scrollable ResultSet object, the cursor can be moved backwards and forwards, to an absolute position, or to a position relative to the current row.
Code Snippet
rs.absolute(5);
rs.updateString(2, "AINSWORTH");
rs.updateRow();

2. An updatable ResultSet object has a special row associated with it that serves as a staging area for building a row to be inserted

rs.moveToInsertRow();
rs.updateString(1, "AINSWORTH");
rs.updateInt(2,35);
rs.updateBoolean(3, true);
rs.insertRow();
rs.moveToCurrentRow();

But scrollableresult associated with overhead, it needs to used only when your application using scrolling.


Full Sample Code

try {
con = DriverManager.getConnection(url, user, pass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT * FROM Users where nick=\"ian\"");
rs.first();
rs.updateString("password", "unguessable");
rs.updateRow();
rs.close();
stmt.close();
con.close();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}