Java JDBC CachedRowSet create
import javax.sql.rowset.CachedRowSet; import javax.sql.rowset.RowSetFactory; import javax.sql.rowset.RowSetProvider; import javax.sql.rowset.spi.SyncProviderException; import java.sql.Connection; import java.sql.SQLException; public class Main { public static Connection conn = null; public static CachedRowSet crs = null; public static void main(Connection conn) { try {//from w w w .j ava 2 s . c o m // Perform Scrollable Query queryWithRowSet(); // Update the CachedRowSet updateData(); // Synchronize changes syncWithDatabase(); } catch (Exception ex) { System.out.println(ex); } finally { if (conn != null) { try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } /** * Call this method to synchronize the data that has been used in the * CachedRowSet with the database */ public static void syncWithDatabase() { try { crs.acceptChanges(conn); } catch (SyncProviderException ex) { ex.printStackTrace(); } finally { if (crs != null) { try { crs.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } public static void queryWithRowSet() { RowSetFactory factory; try { factory = RowSetProvider.newFactory(); crs = factory.createCachedRowSet(); // Alternative // crs.setUsername(createConn.getUsername()); // crs.setPassword(createConn.getPassword()); // crs.setUrl(createConn.getJdbcUrl()); crs.setCommand("select id, recipe_num, name, description from recipes"); int[] keys = { 1 }; crs.setKeyColumns(keys); crs.execute(conn); while (crs.next()) { System.out.println(crs.getString(2) + ": " + crs.getString(3) + " - " + crs.getString(4)); } } catch (SQLException ex) { ex.printStackTrace(); } } public static boolean updateData() { boolean returnValue = false; try { crs.beforeFirst(); while (crs.next()) { if (crs.getString("RECIPE_NUM").equals("1")) { System.out.println("updating recipe 1"); crs.updateString("description", "Subject to change"); crs.updateRow(); } } returnValue = true; crs.beforeFirst(); while (crs.next()) { System.out.println(crs.getString(2) + ": " + crs.getString(3) + " - " + crs.getString(4)); } } catch (SQLException ex) { returnValue = false; ex.printStackTrace(); } return returnValue; } }