Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Changing Data Using a ResultSet

Problem

You want to change the data using a ResultSet.

Solution

If you have JDBC 2 and a conforming driver, you can request an updatable ResultSet when you create the statement object. Then, when you’re on the row you want to change, use the update( ) methods, and end with updateRow( ).

Discussion

You need to create the statement with the attribute ResultSet.CONCUR_UPDATABLE as shown in Example 20-9. Do an SQL SELECT with this statement. When you are on the row (there is only one row that matches this particular query because it is selecting on the primary key), use the appropriate update method for the type of data in the column you want to change, passing in the column name or number and the new value. You can change more than one column in the current row this way. When you’re done, call updateRow( ) on the ResultSet. Assuming that you didn’t change the autocommit state, the data will be committed to the database.

Example 20-9. ResultSetUpdate.java (partial listing)

try {
   con = DriverManager.getConnection(url, user, pass);
   stmt = con.createStatement(
       ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
   rs = stmt.executeQuery("SELECT * FROM Users where nick=\"ian\"");

   // Get the resultset ready, update the passwd field, commit
   rs.first(  );
   rs.updateString("password", "unguessable");
   rs.updateRow(  );

   rs.close(  );
   stmt.close(  );
   con.close(  );
} catch(SQLException ex) {
   System.err.println("SQLException: " + ex.getMessage(  ));
}
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata