Java Reference
In-Depth Information
2. Set a new value for each column in the row by using the appropriate update method.
3. Call the method insertRow() to insert the new row into the result set and, simultaneously, into the
database.
Listing 4-9 demonstrates the use of the UpdatableResultSet to insert a new row into a
database.
Listing 4-9: Using UpdatableResultSet to insert a new row
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection ("jdbc:odbc:Contacts");
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(query);
rs.moveToInsertRow();
rs.updateInt("Contact_ID", 150);
rs.updateString("First_Name", "Nigel");
rs.updateString("Last_Name", "Thornebury");
rs.insertRow();
If you insert a row without supplying a value for every column in the row, the default
value for the column will be used if there is one. Otherwise, if the column accepts
SQL NULL values, a NULL will be inserted. Failing either of those, a SQLException
will be thrown.
You will also get a SQLException if a required table column is missing in the
ResultSet you use to insert the row, so the query used to get the ResultSet object
should generally select all columns, though you will probably want to use a WHERE
clause to limit the number of rows returned by your SELECT statement.
If you move the cursor from the insert row before calling the method
insertRow(), you will lose all of the values you have added to the insert
row.
Caution
To move the cursor from the insert row back to the result set, you can use any of the
methods that put the cursor on a specific row: first, last, beforeFirst, afterLast, and
absolute. You can also use the methods previous and relative because the result set
maintains a record of the current row while accessing the insert row.
In addition, you can use a special method: moveToCurrentRow(), which can be called
only when the cursor is on the insert row. This method moves the cursor from the
insert row back to the row that was previously the current row.
Search WWH ::




Custom Search