Change DB2CachedRowSet data and reflect changes back to the data source

This topic provides information about making changes to rows in a DB2CachedRowSet and then updating the underlying database.

The DB2CachedRowSet uses the same methods as the standard ResultSet interface for making changes to the data in the RowSet object. There is no difference at the application level between changing the data of a RowSet and changing the data of a ResultSet. The DB2CachedRowSet provides the acceptChanges method that is used to reflect changes to the RowSet back to the database where the data came from.

Delete, insert, and update rows in a DB2CachedRowSet

DB2CachedRowSets can be updated. In the following example, the program creates a table and populates it with data using JDBC. Once the table is ready, a DB2CachedRowSet is created and is populated with the information from the table. The example also uses various methods that can be used to update the RowSet and shows how the use of the showDeleted property that allows the application to fetch rows even after they have been deleted. Further, the cancelRowInsert and cancelRowDelete methods are used in the example to allow row insertion or deletion to be undone.

Example: Delete, insert, and update rows in a DB2CachedRowSet

Note: Read the Code example disclaimer for important legal information.
import java.sql.*;
import javax.sql.*;
import com.ibm.db2.jdbc.app.DB2CachedRowSet;

public class RowSetSample2
{
  public static void main(String args[])
  {
    // Register the driver.
    try {
      Class.forName("com.ibm.db2.jdbc.app.DB2Driver");
    }
    catch (ClassNotFoundException ex) {
      System.out.println("ClassNotFoundException: " + 
	             ex.getMessage());

      // No need to go any further.
      System.exit(1);
    }

    try {
      Connection conn = DriverManager.getConnection("jdbc:db2:*local");

      Statement stmt = conn.createStatement();

      // Clean up previous runs
      try {
        stmt.execute("drop table cujosql.test_table");
      }

      catch (SQLException ex) {
        System.out.println("Caught drop table: " + ex.getMessage());
      }

      // Create test table
      stmt.execute("Create table cujosql.test_table (col1 smallint)");
      System.out.println("Table created.");

      // Insert some test rows
      for (int i = 0; i < 10; i++) {
        stmt.execute("insert into cujosql.test_table values (" + i + ")");
      }
      System.out.println("Rows inserted");

      ResultSet rs = stmt.executeQuery("select col1 from cujosql.test_table");
      System.out.println("Query executed");

      // Create a new rowset and populate it...
      DB2CachedRowSet crs = new DB2CachedRowSet();
      crs.populate(rs);
      System.out.println("RowSet populated.");
	  
      conn.close();
      System.out.println("RowSet is detached...");

      System.out.println("Delete the first three rows");
      crs.next();
      crs.deleteRow();
      crs.next();
      crs.deleteRow();
      crs.next();
      crs.deleteRow();

      crs.beforeFirst();
      System.out.println("Insert the value -10 into the RowSet");
      crs.moveToInsertRow();
      crs.updateShort(1, (short)-10);
      crs.insertRow();
      crs.moveToCurrentRow();

      System.out.println("Update the rows to be the negative of what they now are");
      crs.beforeFirst();
      while (crs.next())
        short value = crs.getShort(1);
        value = (short)-value;
        crs.updateShort(1, value);
        crs.updateRow();
      }

      crs.setShowDeleted(true);

      System.out.println("RowSet is now (value - inserted - updated - deleted)");
      crs.beforeFirst();
      while (crs.next()) {
        System.out.println("value is " + crs.getShort(1) + " " +
                   crs.rowInserted() + " " + 
                   crs.rowUpdated() + " " + 
                   crs.rowDeleted());
      }

      System.out.println("getShowDeleted is " + crs.getShowDeleted());
	  
      System.out.println("Now undo the inserts and deletes");
      crs.beforeFirst();
      crs.next();
      crs.cancelRowDelete();
      crs.next();
      crs.cancelRowDelete();
      crs.next();
      crs.cancelRowDelete();
      while (!crs.isLast()) {
        crs.next();
      }
	  	  
      crs.cancelRowInsert();
      
      crs.setShowDeleted(false);

      System.out.println("RowSet is now (value - inserted - updated - deleted)");
      crs.beforeFirst();
      while (crs.next()) {
        System.out.println("value is " + crs.getShort(1) + " " + 
                   crs.rowInserted() + " " + 
                   crs.rowUpdated() + " " + 
                   crs.rowDeleted());
      }

      System.out.println("finally show that calling cancelRowUpdates works");
      crs.first();
      crs.updateShort(1, (short) 1000);
      crs.cancelRowUpdates();
      crs.updateRow();
      System.out.println("value of row is " + crs.getShort(1));
      System.out.println("getShowDeleted is " + crs.getShowDeleted());

      crs.close();

    }

    catch (SQLException ex) {
      System.out.println("SQLException: " + ex.getMessage());
    }
  }
}

Reflect changes to a DB2CachedRowSet back to the underlying database

Once changes have been made to a DB2CachedRowSet, they only exist as long as the RowSet object exists. That is, making changes to a disconnected RowSet has no effect on the database. To reflect the changes of a RowSet in the underlying database, the acceptChanges method is used. This method tells the disconnected RowSet to re-establish a connection to the database and attempt to make the changes that have been made to the RowSet to the underlying database. If the changes cannot be safely made to the database due to conflicts with other database changes after the RowSet was created, an exception is thrown and the transaction is rolled back.

Example: Reflect changes to a DB2CachedRowSet back to the underlying database

Note: Read the Code example disclaimer for important legal information.
import java.sql.*;
import javax.sql.*;
import com.ibm.db2.jdbc.app.DB2CachedRowSet;

public class RowSetSample3
{
  public static void main(String args[])
  {
    // Register the driver.
    try {
      Class.forName("com.ibm.db2.jdbc.app.DB2Driver");
    }
    catch (ClassNotFoundException ex) {
      System.out.println("ClassNotFoundException: " + 
                 ex.getMessage());
      // No need to go any further.
      System.exit(1);
    }

    try {
      Connection conn = DriverManager.getConnection("jdbc:db2:*local");

      Statement stmt = conn.createStatement();

      // Clean up previous runs
      try {
        stmt.execute("drop table cujosql.test_table");
      }
      catch (SQLException ex) {
        System.out.println("Caught drop table: " + ex.getMessage());
      }

      // Create test table
      stmt.execute("Create table cujosql.test_table (col1 smallint)");
      System.out.println("Table created.");

      // Insert some test rows
      for (int i = 0; i < 10; i++) {
        stmt.execute("insert into cujosql.test_table values (" + i + ")");
      }
      System.out.println("Rows inserted");

      ResultSet rs = stmt.executeQuery("select col1 from cujosql.test_table");
      System.out.println("Query executed");

      // Create a new rowset and populate it...
      DB2CachedRowSet crs = new DB2CachedRowSet();
      crs.populate(rs);
      System.out.println("RowSet populated.");

      conn.close();
      System.out.println("RowSet is detached...");

      System.out.println("Delete the first three rows");
      crs.next();
      crs.deleteRow();
      crs.next();
      crs.deleteRow();
      crs.next();
      crs.deleteRow();

      crs.beforeFirst();
      System.out.println("Insert the value -10 into the RowSet");
      crs.moveToInsertRow();
      crs.updateShort(1, (short)-10);
      crs.insertRow();
      crs.moveToCurrentRow();

      System.out.println("Update the rows to be the negative of what they now are");
      crs.beforeFirst();
      while (crs.next()) {
        short value = crs.getShort(1);
        value = (short)-value;
        crs.updateShort(1, value);
        crs.updateRow();
      }

      System.out.println("Now accept the changes to the database");

      crs.setUrl("jdbc:db2:*local");
      crs.setTableName("cujosql.test_table");

      crs.acceptChanges();
      crs.close();

      System.out.println("And the database table looks like this:");
      conn = DriverManager.getConnection("jdbc:db2:localhost");
      stmt = conn.createStatement();
      rs = stmt.executeQuery("select col1 from cujosql.test_table");
      while (rs.next()) {
        System.out.println("Value from table is " + rs.getShort(1));
      }

      conn.close();

    } 
    catch (SQLException ex) {
      System.out.println("SQLException: " + ex.getMessage());
    }
  }
}
Related concepts
Use DB2CachedRowSet
Other DB2CachedRowSet features
Related reference
Create and populate a DB2CachedRowSet
Access DB2CachedRowSet data and cursor manipulation