Java how to use updatable result sets with jdbc

www.i‮‬giftidea.com

An Updatable ResultSet is a type of ResultSet object in Java that allows you to update the underlying database when you modify the contents of the ResultSet. To use Updatable ResultSets with JDBC, you can follow these steps:

  1. Establish a connection to the database using the DriverManager class. For example:
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";

Connection connection = DriverManager.getConnection(url, username, password);
  1. Create a Statement object and execute a SQL query that returns an Updatable ResultSet. For example:
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");

Note that the ResultSet object is created with the constants ResultSet.TYPE_SCROLL_SENSITIVE and ResultSet.CONCUR_UPDATABLE, which allow the ResultSet to be scrolled and updated.

  1. Use the methods of the ResultSet object to update the data in the ResultSet. For example:
while (resultSet.next()) {
    int id = resultSet.getInt("id");
    String name = resultSet.getString("name");
    double salary = resultSet.getDouble("salary");
    
    if (name.equals("John")) {
        resultSet.updateString("name", "Hyman");
        resultSet.updateDouble("salary", salary * 1.1);
        resultSet.updateRow();
    }
}

In this example, the name and salary fields of any row with a name equal to "John" are updated. The updateRow() method is called to commit the changes to the underlying database.

  1. Close the ResultSet, Statement, and Connection objects when you're finished:
resultSet.close();
statement.close();
connection.close();

That's it! You can use Updatable ResultSets to update the data in your database directly from your Java program.