The ResultSet interface can be used to modify database records directly when it is created as an updatable ResultSet. Instead of executing a separate UPDATE SQL statement, methods such as updateInt(), updateString(), and updateDouble() can be used to change column values. The updateRow() method saves the modified values of the current row to the database. An updatable ResultSet is created using ResultSet.CONCUR_UPDATABLE.
Program: Updating Employee Salary Using ResultSet
This program retrieves an employee record and updates its salary using the ResultSet interface. The updateDouble() method changes the salary, and updateRow() permanently saves the change to the database.
import java.sql.*;
public class ResultSetUpdateExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/jdbc_demo";
String username = "root";
String password = "password";
String sql =
"SELECT employee_id, employee_name, " +
"department, salary FROM employee";
try {
Connection con =
DriverManager.getConnection(
url, username, password);
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
ResultSet rs = stmt.executeQuery(sql);
boolean found = false;
while (rs.next()) {
if (rs.getInt("employee_id") == 101) {
found = true;
System.out.println("Before Update");
System.out.println("----------------------");
System.out.println(
"Employee ID: " +
rs.getInt("employee_id"));
System.out.println(
"Employee Name: " +
rs.getString("employee_name"));
System.out.println(
"Salary: " +
rs.getDouble("salary"));
// Update salary
rs.updateDouble("salary", 55000.00);
// Save the change
rs.updateRow();
System.out.println("\nAfter Update");
System.out.println("----------------------");
System.out.println(
"Employee ID: " +
rs.getInt("employee_id"));
System.out.println(
"Employee Name: " +
rs.getString("employee_name"));
System.out.println(
"Salary: " +
rs.getDouble("salary"));
break;
}
}
if (!found) {
System.out.println("Employee not found.");
}
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\mysql-connector.jar" ResultSetUpdateExample.java
PS D:\test> java -classpath ".;D:\test\mysql-connector.jar" ResultSetUpdateExample
Before Update
----------------------
Employee ID: 101
Employee Name: Ravi
Salary: 50000.0
After Update
----------------------
Employee ID: 101
Employee Name: Ravi
Salary: 55000.0Code language: CSS (css)
