JDBC RESULTSET – Insert Row in MySQL Database Table

In this chapter you will learn

1. How to insert row in Database Table using JDBC RowSet

This chapter will teach you, how can you use ResultSet to insert row in database table. Always remember in order to update or insert row in database table you need to set ResultSet TYPE_SCROLL_INSENSITIVE and CONCUR_UPDATABLE.

      Statement stmt = con.createStatement(
                                      ResultSet.TYPE_SCROLL_INSENSITIVE,
                                      ResultSet.CONCUR_UPDATABLE);

If you don’t set these two parameter ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE, then you will get following error message on screen.

com.mysql.jdbc.NotUpdatable: Result Set not updatable.This result set must come from a statement that was created with a result set type of ResultSet.CONCUR_UPDATABLE, the query must select only one table, can not use functions and must select all primary keys from that table. See the JDBC 2.1 API Specification, section 5.6 for more details.This result set must come from a statement that was created with a result set type of ResultSet.CONCUR_UPDATABLE, the query must select only one table, can not use functions and must select all primary keys from that table. See the JDBC 2.1 API Specification, section 5.6 for more details.

Programming Example of Updatable RowSet in JDBC

package DataSetExample;

import java.sql.*;

public class JDBC_ResultSet
{
	   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);
	    	    
	    rset.moveToInsertRow();
	    rset.updateString("PRODUCT", "Charger");
	    rset.updateString("PRICE", "1800");
	    rset.insertRow();
	    rset.moveToCurrentRow();
	    System.out.println("Row Inserted");
	} 
	
	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

Row Inserted
Closing the connection.
_

Summary

In this chapter you learn how to insert row in MySQL Database Table using RowSet Object in JDBC.


Leave a Reply

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