How to Update Table Records in Java


In this example we will show how to update the table row using result set object.

Source Code

package com.beginner.examples;

import com.mysql.jdbc.Driver;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
  
    public class UpdateExample {
        public static void main(String[] args) throws SQLException, ClassNotFoundException {

        Class.forName("com.mysql.jdbc.Driver");
        
        //database connection
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql", "root", "");

        // sql statement
        String sql = "SELECT host from user " +
                " WHERE user = 'root' ";

        try
        {
        	// execute sql statement
        	ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE).executeQuery(sql);
            while (rs.next()) 
            {
            	if(rs.getString(1) == "127.0.0.1"){
            		// update record
                    rs.updateNString(1, "root");
                    rs.updateRow();
                    System.out.println("Update!");
                }
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Output:

Update!

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments