JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

Inserting Rows with JdbcRowSet Objects

This section describes how to insert data rows with a JdbcRowSet object.

Based on the JDBC documentation, a JdbcRowSet object is extended from a ResultSet object and defined to be updatable by default. This means that you can use JdbcRowSet objects to update, delete or insert rows back to target tables in the database server. I wrote a sample program to use a JdbcRowSet object to insert 2 data rows back to the Profile table in MySQL server:

/**
 * MySqlRowSetInsert.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.sql.*;
public class MySqlRowSetInsert {
  public static void main(String [] args) {
    try {

// Load the JDBC driver class. Needed for JDBC 3.0 drivers
      Class.forName("com.mysql.jdbc.Driver") ;

// Get a new JdbcRowSet object with Run's implementation
      javax.sql.rowset.JdbcRowSet jrs 
        = new com.sun.rowset.JdbcRowSetImpl();

// Set the connection URL for the DriverManager
      jrs.setUrl("jdbc:mysql://localhost/HerongDB"
        +"?user=Herong&password=TopSecret");

// Set a SQL statement with parameters
      jrs.setCommand("SELECT * FROM Profile WHERE 1=2");

// Connect and run the statement
      jrs.execute();

// Move to the insert row
      jrs.moveToInsertRow();

// Set column values and insert
      jrs.updateString("FirstName", "Herong");
      jrs.updateString("LastName", "Yang");
      jrs.insertRow();
 
// Repeat for another row
      jrs.updateString("FirstName", "Bush");
      jrs.updateString("LastName", "Gate");
      jrs.insertRow();

      System.out.println("2 rows inserted.");
      
// Close resource
      jrs.close();
    } catch (Exception e) {
      System.err.println("Exception: "+e.getMessage());
    }
  }
}

The program executed correctly:

C:\>javac -cp .;\local\lib\rowset.jar MySqlRowSetInsert.java

MySqlRowSetInsert.java:15: 
warning: com.sun.rowset.JdbcRowSetImpl is Sun proprietary API 
and may be removed in a future release
        = new com.sun.rowset.JdbcRowSetImpl();
                            ^
1 warning

C:\>java -cp .;\local\lib\rowset.jar;
  \local\lib\mysql-connector-java-5.0.7-bin.jar MySqlRowSetInsert

2 rows inserted.

Sections in This Chapter

Overview of RowSet Objects

Installation of JdbcRowSet Reference Implementation

Connecting JdbcRowSet to Database Servers

Connecting JdbcRowSet with a Connection URL

Connecting JdbcRowSet with a Predefined Connection Object

Connecting JdbcRowSet with a Predefined ResultSet Object

Connecting JdbcRowSet with JNDI Directory Service

JdbcRowSet Query Statement with Parameters

Inserting Rows with JdbcRowSet Objects

Dr. Herong Yang, updated in 2007
Inserting Rows with JdbcRowSet Objects