JAVA JDBC – Update Row in ResultSet to Database Table

In this chapter you will learn:

1. How to Update a Row in ResultSet in JDBC?

You can update a row in table using RowSet updateString() and updateRow() method. There are 3 steps while updating a row in rowset.

1. Select row which you want to update. You can select a row using absolute(int rownumber) method.

rset.absolute(9);

2. Execute updateString(string column_name, string value) method.

rset.updateString("PRODUCT", "HDMI CABLE");

It will update 9th row of PRODUCT column with string value ‘HDMI CABLE’ in RowSet. Remember, this update reflects only rowset and it will not reflect in database table until you use updateRow() method.

3. Execute updateRow() command to make changes in database table.

Update Row in MySQL Database using ResultSet Object

package DataSetExample;

import java.sql.*;

public class ResultSet_Update
{
	   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
	   static final String dburl = "jdbc:mysql://localhost/STOREDB";	   
	   static final String dbuser = "root";
	   static final String dbpass = "root";
	   
public static void main(String[] args)
{
	Connection con = null;
	Statement stmt = null;
	
	try 
	{
	    //Step 1 : Connecting to server and database
	    con = DriverManager.getConnection(dburl, dbuser, dbpass);	    
	    //Step 2 : Initialize Statement
	    stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
	    //Step 3 : SQL Query
	    String query="SELECT * FROM ITEM";
	    
	    //Step 4 : Run Query In ResultSet
	    ResultSet rset = stmt.executeQuery(query);
	    	    
	    //Update String
	    
	    //absulute() method puts cursor or pointed at the given row
	    rset.absolute(9);
	    rset.updateString("PRODUCT", "HDMI CABLE");
	    rset.updateRow();
	    System.out.println("Row Updated");
	    
	    //System.out.println(rset.getMetaData());
	    
	} 
	
	catch (SQLException e) 
	{
	    System.err.println("Cannot connect ! ");
	    e.printStackTrace();
	}
	
	finally {
	    System.out.println("Closing the connection.");
	    if (con != null) try { con.close(); } catch (SQLException ignore) {}
	}
	
}
}

Output

Before Update
Before Update
After Update
After Update

Summary

In this chapter you learn how to update a database table row using JDBC RowSet object. In the next chapter you will learn how to insert a row in database table using JDBC RowSet insertRow() method.


Leave a Reply

Your email address will not be published. Required fields are marked *