Lecture Videos
  1  import java.sql.*;
  2  import javax.sql.RowSet;
  3  import com.sun.rowset.JdbcRowSetImpl;
  4  
  5  public class ScrollUpdateRowSet {
  6    public static void main(String[] args)
  7        throws SQLException, ClassNotFoundException {
  8      // Load the JDBC driver
  9      Class.forName("com.mysql.jdbc.Driver");
 10      System.out.println("Driver loaded");
 11  
 12      // Create a row set
 13      RowSet rowSet = new JdbcRowSetImpl();
 14  
 15      // Set RowSet properties
 16      rowSet.setUrl("jdbc:mysql://localhost/javabook");
 17      rowSet.setUsername("scott");
 18      rowSet.setPassword("tiger");
 19      rowSet.setCommand("select state, capital from StateCapital");
 20      rowSet.execute();
 21  
 22      System.out.println("Before update ");
 23      displayRowSet(rowSet);
 24  
 25      // Update the second row
 26      rowSet.absolute(2); // Move cursor to the 2nd row
 27      rowSet.updateString("state", "New S"); // Update the column
 28      rowSet.updateString("capital", "New C"); // Update the column
 29      rowSet.updateRow(); // Update the row in the data source
 30  
 31      // Insert after the second row
 32      rowSet.last();
 33      rowSet.moveToInsertRow(); // Move cursor to the insert row
 34      rowSet.updateString("state", "Florida");
 35      rowSet.updateString("capital", "Tallahassee");
 36      rowSet.insertRow(); // Insert the row
 37      rowSet.moveToCurrentRow(); // Move the cursor to the current row
 38  
 39      // Delete fourth row
 40      rowSet.absolute(4); // Move cursor to the fifth row
 41      rowSet.deleteRow(); // Delete the second row
 42  
 43      System.out.println("After update ");
 44      displayRowSet(rowSet);
 45  
 46      // Close the connection
 47      rowSet.close();
 48    }
 49  
 50    private static void displayRowSet(RowSet rowSet)
 51        throws SQLException {
 52      ResultSetMetaData rsMetaData = rowSet.getMetaData();
 53      rowSet.beforeFirst();
 54      while (rowSet.next()) {
 55        for (int i = 1; i <= rsMetaData.getColumnCount(); i++)
 56          System.out.printf("%-12s\t", rowSet.getObject(i));
 57        System.out.println();
 58      }
 59    }
 60  }