Sunday, February 13, 2011

Fetching database rows using ResultSet in JDBC

The basic approach to fetching rows from DB:

Connection con = // Secure a connection using this approach
Statement stat;
try
{
stat = con.createStatement();
ResultSet rs = stat.executeQuery("select * from emp");
while ( rs.next() ) // Move cursor 1 row forward, false returned means last row
{ // next | previous | first | last | beforeFirst | afterLast |
// relative (int) | absolute(int)
String empName = rs.getString("EMP_NAME"); // or getString()
int empId - rs.getInt("EMP_ID");
..
}
} catch( SQLException e)
{
...
} finally
{
stmt.close();
}

ResultSet types:

TYPE_FORWARD_ONLY [DEFAULT]: Only scroll forward (not backward) - insensitive to changes made by others (Contains results as they existed at query execution time or as rows are retrieved - depends on how db generated results)

TYPE_SCROLL_INSENSITIVE: Scrolls back, forward and to absolute or relative position. insensitive to changes made by others (Contains results as they existed at query execution time or as rows are retrieved - depends on how db generated results)

TYPE_SCROLL_SENSITIVE: Scrolls back, forwards and to absolute or relative position. Changes made by others at the data source are reflected in the ResultSet.

ResultSet concurrency:

CONCUR_READ_ONLY [DEFAULT]: No support for updates using ResultSet Interface
CONCUR_UPDATABLE: Supports updates using ResultSet. Not supported by all JDBC drivers. Call DatabaseMetaData.supportsResultSetConcurrency to know support.

E.g.:

Statement stmt =
con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM EMP");
rs.next();
rs.updateString("NAME", "NewName"); // Update EMP set Name="NewName";

Cursor Holdability:
When connection.commit() is invoked, all ResultSets opened as part of the transaction are, by default, closed. If they are not to be closed, then the ResultSet object's holdability needs to be changed.

HOLD_CURSORS_OVER_COMMIT: When connection.commit() is invoked, do not close the ResultSet objects opened during the connection. Useful with read only result sets.
CLOSE_CURSORS_AT_COMMIT: On connection.commit() close ResultSets. Some applications get performance improvements in doing do.

Use JDBCTutorialUtilities.cursorHoldabilitySupport to determine support for holdability.

These are specified in Connection methods.

No comments: