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.
1 | rset.absolute(9); |
2. Execute updateString(string column_name, string value)
method.
1 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 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
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.