Java Reference
In-Depth Information
CachedRowSet crs = new CachedRowSetImpl();
Once instantiated, you need to set up a connection to the database. There are also a
couple of ways to do this. Properties could be set for the connection that will be used,
and the solution to this recipe demonstrates this technique within comments. The fol-
lowing excerpt from the solution sets the connection properties using the
CachedRowSet
object's
setUsername(), setPassword()
, and
setUrl()
methods. Each of them accepts a string value, and in the example that string is obtained
from the
CreateConnection
class:
// Alternatively populate the CachedRowSet connection
settings
// crs.setUsername(createConn.getUsername());
// crs.setPassword(createConn.getPassword());
// crs.setUrl(createConn.getJdbcUrl());
Another way to set up the connection is to wait until the query is executed and pass
a
Connection
object to the
executeQuery()
method. This is the technique that
is used in the solution to this recipe. But before you can execute the query, it must be
set using the
setCommand()
method, which accepts a string value. In this case, the
string is the SQL query that you need to execute:
crs.setCommand("select id, recipe_number, recipe_name,
description from recipes");
Next, if a
CachedRowSet
will be used for updates, the primary key values should
be noted using the
setKeys()
method. This method accepts an
int
array that in-
cludes the positional indices of the key columns. These keys are used to identify unique
columns. In this case, the first column listed in the query,
ID
, is the primary key:
int[] keys = {1};
crs.setKeyColumns(keys);
Finally, execute the query and populate the
CachedRowSet
using the
ex-
ecute()
method. As mentioned previously, the
execute()
method optionally ac-
cepts a
Connection
object, which allows the
CachedRowSet
to obtain a database
connection.