Updating a row in the resultset

You can always execute an UPDATE statement with the new changes. JDBC2.0 provides another way. It allows you to make changes to a row from ResultSet and reflect the changes in the database.

before:

+---------+--------+---------------------+--------+
| orderid | custid | timestamp           | status |
+---------+--------+---------------------+--------+
|       1 |      1 | 2001-10-13 17:33:11 |      0 |
|       2 |      1 | 1972-12-12 00:00:00 |      1 |
|       3 |      1 | 1999-02-01 00:00:00 |      2 |
|       4 |      2 | 2001-05-01 00:00:00 |      0 |
+---------+--------+---------------------+--------+

Main.java:

import java.util.*;
import java.text.*;
import java.sql.*;
  
public class Main {
   public static void main(String []args) throws Exception {
      try {
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.1/esus", 
                                                       "joris",
                                                       "mypass");
 
         Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                                               ResultSet.CONCUR_UPDATABLE);
 
         ResultSet rs = stmt.executeQuery("SELECT * FROM orders WHERE orderid = 1"); 
 
         if (rs.next()) {
            // change the status column
            rs.updateInt("status", 1);
            // store changes in database
            rs.updateRow();
         }
 
         stmt.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

after:

+---------+--------+---------------------+--------+
| orderid | custid | timestamp           | status |
+---------+--------+---------------------+--------+
|       1 |      1 | 2001-10-13 17:33:11 |      1 |
|       2 |      1 | 1972-12-12 00:00:00 |      1 |
|       3 |      1 | 1999-02-01 00:00:00 |      2 |
|       4 |      2 | 2001-05-01 00:00:00 |      0 |
+---------+--------+---------------------+--------+