Java Reference
In-Depth Information
Note
Some database JDBC drivers do not support updatable
ResultSets
. See the
documentation of your JDBC driver for more information. This code was run using
Oracle's
ojdbc6.jar
JDBC driver on Oracle database 11.2 release.
The format for creating a
Statement
that will produce an
updatable Res-
ultSet
is to pass the
ResultSet
type as the first argument and the
ResultSet
concurrency as the second argument. The scroll type must be
TYPE_SCROLL_SENSITIVE
to ensure that the
ResultSet
will be sensitive to any
updates that are made. The following code demonstrates this technique by creating a
Statement
object that will produce a scrollable and updatable
ResultSet
object:
Statement stmt
= conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
The format for creating a
PreparedStatement
that will produce an updatable
ResultSet
is to pass the SQL string as the first argument, the
ResultSet
type as
the second argument, and the
ResultSet
concurrency as the third argument. The
solution to this recipe demonstrates this technique using the following line of code:
pstmt = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_SENSITIVE,
Both of the lines of code discussed in this section will produce scrollable and up-
datable
ResultSet
objects. Once you have obtained an updatable
ResultSet
, you
can use it just like an ordinary
ResultSet
for fetching values that are retrieved from
the database. In addition, you can call one of the
ResultSet
object's
up-
dateXXX()
methods to update any value within the
ResultSet
. In the solution to
this recipe, the
updateString()
method is called, passing the position of the value
from the query as the first argument and the updated text as the second argument. In
this case, the fourth element column listed in the SQL query will be updated.
rs.updateString(4, desc + " -- More to come");
Finally, to persist the values that you have changed, call the
ResultSet up-
dateRow()
method, as seen in the solution to this recipe: