Update Record using ResultSet in JDBC

We know that ResultSet objects are used to get the data that is retrieved using a Select statement.
ResultSet can also be used to insert or update records in the database.

Steps to remember when you update Record using ResultSet in JDBC

1. ResultSet should be Updatable You can do this while creating Statement object

2. Get a ResultSet object after executeQuery()

3. Iterate the ResultSet and use ResultSet.updateXXX() wherever you need to update the record.

4. Then use ResultSet.updateRow() to update the changes.

Lets see an example on how to insert record using Resultset in Java in database.

Example

We have a table employee_details that has 3 records

ID Name Designation Salary
1 Steve Sr Developer 5000
2 Mark Sr Developer 4500
3 Robin Jr Developer 3500

Now we will write code to get all the records and then update the salary for each of them to add 500.

Output

When we fire a direct query to the database to check the records that were updated we see the below results for updated salaries.

ID Name Designation Salary
1 Steve Sr Developer 5500
2 Mark Sr Developer 5000
3 Robin Jr Developer 4000