Sunday, 3 August 2014

JDBC Updatable ResultSet

Enjoying This Java Tutorial?

Subscribe to our YouTube channel for clear, step-by-step Java database programming guides!

SUBSCRIBE NOW

What is an Updatable ResultSet?

By default, a ResultSet in JDBC is read-only, meaning you can only view or iterate through records. However, JDBC provides the ability to make your ResultSet updatable using ResultSet.CONCUR_UPDATABLE.

With an updatable ResultSet, you can update existing rows, modify column values, and even insert brand-new records into the underlying database table directly through the ResultSet object without writing manual UPDATE or INSERT SQL queries!

How to Create an Updatable ResultSet

To enable updates, you pass concurrency options when creating your Statement object:

Statement stmt = connection.createStatement(
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE
);
ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM Employee");

Combining a scrollable cursor type with CONCUR_UPDATABLE allows you to jump to any row and modify values on the fly.

Updating Existing Records Step-by-Step

Updating data in a row involves three simple operations:

  1. Navigate to the Row: Move the cursor to the target row (for example, using rs.absolute(rowNumber)).
  2. Update Column Values: Use appropriate setter methods such as rs.updateString("name", "New Value") or rs.updateInt("age", 30).
  3. Commit to Database: Call rs.updateRow() to push and persist the changes into the database.

Inserting New Rows with ResultSet

You can also insert brand-new records without executing raw INSERT INTO statements:

  • Move to Insert Buffer: Call rs.moveToInsertRow(), which positions the cursor at a dedicated staging row.
  • Assign Values: Use updateXXX() methods to supply values for each column.
  • Insert the Record: Invoke rs.insertRow() to commit the new record to your database table.

Related Tutorials You Might Like


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

Click the below Image to Enlarge
JDBC Updatable ResultSet
JDBC Updatable ResultSet
See also:

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

    Post a Comment

    Tutorials