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 Oracle server:
/**
* OracleRowSetInsert.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class OracleRowSetInsert {
public static void main(String [] args) {
try {
// Load the JDBC driver class. Needed for JDBC 3.0 drivers
Class.forName("oracle.jdbc.OracleDriver");
// 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:oracle:thin:Herong/TopSecret"
+"@//localhost:1521/XE");
// 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 OracleRowSetInsert.java
OracleRowSetInsert.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\ojdbc14.jar OracleRowSetInsert
Exception: Invalid operation for read only resultset: moveToInsertRow
Notice that my program failed because the Oracle JDBC driver does not support the updatable RowSet function.
I have tried to call the setConcurrency() method. But it did not help:
// Set JdbcRowSet to be updatable
jrs.setConcurrency(java.sql.ResultSet.CONCUR_UPDATABLE);