Java Reference
In-Depth Information
Solution
If you have JDBC 2 and a conforming driver, you can request an updatable
ResultSet
when
you create the statement object. When you're on the row you want to change, use the
up-
date()
methods and end with
updateRow()
.
Discussion
You need to create the statement with the attribute
ResultSet.CONCUR_UPDATABLE
as shown
in
Example 18-7
.
Do an SQL SELECT with this statement. When you are on the row (only
one row matches this particular query because it is selecting on the primary key), use the ap-
propriate update method for the type of data in the column you want to change, passing in
the column name or number and the new value. You can change more than one column in the
current row this way. When you're done, call
updateRow()
on the
ResultSet
. Assuming
that you didn't change the autocommit state, the data is committed to the database.
Example 18-7. ResultSetUpdate.java (partial listing)
try
try
{
con
=
DriverManager
.
getConnection
(
url
,
user
,
pass
);
stmt
=
con
.
createStatement
(
ResultSet
.
TYPE_SCROLL_SENSITIVE
,
ResultSet
.
CONCUR_UPDATABLE
);
rs
=
stmt
.
executeQuery
(
"SELECT * FROM Users where nick=\"ian\""
);
// Get the resultset ready, update the passwd field, commit
rs
.
first
( );
rs
.
updateString
(
"password"
,
"unguessable"
);
rs
.
updateRow
( );
rs
.
close
( );
stmt
.
close
( );
con
.
close
( );
}
catch
catch
(
SQLException ex
) {
System
.
err
.
println
(
"SQLException: "
+
ex
.
getMessage
( ));
}