Beruflich Dokumente
Kultur Dokumente
Table of Contents
Point 6: Working With RowSet........................................................................................................1
Understanding Database Connectivity Techniques......................................................................2
Existing Database Connectivity Techniques...........................................................................2
Techniques Used in JDBC......................................................................................................2
Introducing RowSets........................................................................................................................4
Types of RowSets...................................................................................................................4
Uses and Properties of RowSets............................................................................................5
Implementing the CachedRowSet...................................................................................................8
The FetchEmployee Program.................................................................................................8
Understanding the ShowEmp Program..................................................................................9
Implementing the WebRowSet......................................................................................................12
Importing Packages and Defining the main() Method...........................................................12
Writing the Code for the main() Method................................................................................12
Writing the Output to a File and Navigating Records............................................................12
Defining the Methods for Startup and Navigating Records...................................................13
Browsing Data Retrieved from the Database........................................................................13
Implementing the JDBCRowSet....................................................................................................17
Instantiating the JDBCRowSet Class....................................................................................17
Performing Database Operations.........................................................................................17
Related Topics................................................................................................................................19
The first two drivers, JDBCODBC bridge and NativeAPI, require the client computer to have a
native library. The other two drivers do not use a native library and are dataspecific. Therefore,
these drivers are much faster that the JDBCODBC bridge and NativeAPI drivers. Figure
261shows how a driver works and the various layers that drivers need to traverse:
1. A request for data is placed and a connection is opened to the database server.
2. The ResultSet object obtains the requested values and makes the data accessible.
3. The connection is kept open until data exists in the ResultSet object.
Introducing RowSets
In the existing techniques of data transfer, the application keeps the connection open until the
ResultSet object is in use. This feature can be a drawback when large numbers of end users
connect to the server at the same time, slowing server response.
A solution to these problems is the RowSet available with the JDBC 2.0 API extension package.
The RowSet interface opens a connection, retrieves data, and closes the connection.
The RowSet object, which is instantiated from the RowSet interface, contains a set of rows retrieved
from a ResultSet object, a database, or another tabular data store.
The RowSet object is an extension of a ResultSet object. You can iterate through a RowSet in a
manner similar to iteration through a ResultSet object. Table 261 lists comparisons between the
RowSet and the ResultSet:
Table 261: Comparison of a ResultSet and RowSet
ResultSet
RowSet
Is a table of data representing a database Contains a set of rows from a result set or another
result set
source of tabular data, such as a file or spreadsheet
Is usually generated by executing a
Is executed using a bean development tool
statement that queries the database
Can be used in a while loop to iterate
Follows the JavaBeans model for properties and event
through the result set
notifications
Types of RowSets
The two types of RowSets are:
Disconnected RowSet: Stores data in memory and makes a connection to a data source to
retrieve data or communicate updates back to the data source. A disconnected RowSet
does not keep the connection open throughout the data transaction. An example of a
disconnected RowSet is the CachedRowSet class.
Connected RowSet: Opens a connection and keeps it open as long as the RowSet is in use.
Examples of connected RowSets are the JDBCRowSet and WebRowSet classes.
The JDBC API includes three classes: CachedRowSet, JDBCRowSet, and WebRowSet. The
RowSets implemented by these classes are:
CachedRowSet: Is a disconnected RowSet that caches data in memory and provides all the
features of the JDBC 2.0 ResultSet. CachedRowSet transfers a set of rows across a
network and makes a result set scrollable and updatable. CachedRowSets are thin and
serializable. This makes them the perfect tool to supply thin Java clients, such as a Personal
Digital Assistant (PDA) or Network Computers (NC), with tabular data. The code for creating
a CachedRowSet is:
CachedRowSet crset = new CachedRowSet();
Table 262 lists the key factors and contains a comparison between the CachedRowSet,
JDBCRowSet, and the WebRowSet:
Table 262: A Comparison of RowSets
Parameter
Connection
state
Caching
CachedRowSet
Disconnected RowSet
JDBCRowSet
Connected RowSet
WebRowSet
Connected RowSet
Serialization
The main objective of a RowSet is to store values from a table. Rows are requested from a
relational database. As a result, the RowSet needs to have certain properties that allow it to connect
to the database. The properties of a RowSet need to be set to determine its functionality.
There are two kinds of properties, static and dynamic. Static properties are set at development time
and dynamic properties are set at run time.
Table 263 lists the important properties of RowSets and their descriptions:
Table 263: Important Properties of a RowSet
Property
Type
Concurrence
Command
Data Source
Username
Password
Transaction isolation
Escape processing
Maximum field size
Maximum rows
Query time out
Type map
Description
Sets the RowSet type
Sets the concurrency for a RowSet
Sets a RowSet's command property to the given String object and clears
the parameters, if any, which were set for the previous command
Sets the data source property name for the RowSet object
Sets the username property for a RowSet to the given user name
Sets the password used to create a database connection for this RowSet
to the given String object
Sets the transaction isolation property for a RowSet to the given constant
Sets the escape substitution before sending SQL statements to the
database
Sets the maximum number of bytes that can be used for a column value in
this RowSet to the given number
Sets the maximum number of rows that this RowSet object may contain to
the given number
Sets the maximum number of seconds the driver will wait for a query to
execute to the given number
Installs the given java.util.Map object as the type map associated with the
Connection object for this RowSet
The properties are specified using the set method during development time and their values are
retrieved during run time. Before setting the properties, you need to create the RowSet. The
respective code for creating a CachedRowSet, a JDBCRowSet, and a WebRowSet are:
CachedRowSet crs = new CachedRowSet
JDBCRowSet jrs = new JDBCRowSet
WebRowSet wrs = new WebRowSet
The method for setting the properties is the same for all RowSets. In this list, a CachedRowSet is
used to set the properties listed in Table 263:
Type attribute: Sets the type to scrollable, allowing you to make updates by scrolling to the
rows that need to be updated. The second line is the default setting of the type property,
which is set to insensitive or nonscrollable:
crsSet.TYPE_SCROLL_SENSITIVE, or crsSet.TYPE_SCROLL_INSENSITIVE
Concurrence attribute: Enables you to update the rows when the concurrence attribute is set
of updatable. By default, the concurrence property is set at readonly, as illustrated in the
second line of code:
crsSet.CONCUR_UPDATABLE or
crsSet.CONCUR_READ_ONLY
Command attribute: Sets the command attribute. In the given line of code, the RowSets
command string is set with the query SELECT * FROM PRICES. The command property
Reprinted for v697039, Verizon
works in combination with the execute method. When you apply the execute method, the
RowSet retrieves data from the PRICES table:
crsSet.setcommand (SELECT * FROM PRICES)
Data source attribute: Facilitates making a connection. You need to specify the data source
name, the user name, and the password. The code that sets the username and password
for the data source object and sets the data source attribute is:
crsSet.setDataSourceName ("jdbc/pricesDB)
crsSet.setUsername("fred")
crsSet.setPassword("fredrock")
javax.servlet.*;
javax.servlet.http.*;
java.io.*;
java.util.*;
java.sql.*;
sun.jdbc.rowset.*;
After importing the packages to run the application, create a class, FetchEmployee, which extends
the HttpServlet class for performing the servlet tasks. After creating the FetchEmployee class,
override the service method for writing implementation of the servlet:
Listing 261 shows the code to implement database management in the FetchEmployee.java
program:
Listing 261: Database Management in the FetchEmployee.java Program
Connection con;
Statement smt;
ResultSet rs;
String fsal="100";
String tsal = "800";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:mydsn","","");
smt = con.createStatement();
String sql = "select * from employee where sal between "+fsal+" and "+tsal;
rs = smt.executeQuery(sql);
CachedRowSet crs = new CachedRowSet();
crs.populate(rs);
HttpSession s = req.getSession(true);
s.setAttribute("mycrs",crs);
con.close()
rs = null;
res.sendRedirect("http://localhost:8080/servlet/ShowEmp");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
After implementing the code in Listing 261, you can manage database operations from the
FetchEmployee.java program.
You can view the complete code of this program here
javax.servlet.*;
javax.servlet.http.*;
java.io.*;
java.util.*;
java.sql.*;
sun.jdbc.rowset.*;
After you import the necessary packages into your application, create a class, ShowEmp, which
extends the HttpServlet class. The ShowEmp class performs the tasks implemented in the servlet
and overrides the service method for implementing the servlet:
10
Declaring Objects
After declaring the HttpServlet class:
1. Declare the String objects to store the values fetched from the CachedRowSet.
2. Create a Session and PrintWriter object for responding to the client.
3. Create an object of the CachedRowSet to assign to the object retrieved from the session.
4. Typecast the object retrieved from the session object to the CachedRowSet form.
id = new String();
name=new String();
add=new String();
ph=new String();
city=new String();
state=new String();
country=new String();
HttpSession s = req.getSession(true);
PrintWriter out = res.getWriter();
CachedRowSet crs = new CachedRowSet();
crs = (CachedRowSet)s.getAttribute("mycrs");
out.println("<Html>");
out.println("<Title> Employee Details </Title>");
out.println("<Body>");
out.println("<Table border=1>");
out.println("<Tr><th>Employee Id</th><th> Name</th><th>Add</th><th>Phone</th><th>City</th><th>S
while(crs.next())
{
out.println("<tr>");
name = crs.getString("name");
out.println("<td>"+name+"<td>");
add = crs.getString("add");
out.println("<td>"+add+"<td>");
ph = crs.getString("Ph");
out.println("<td>"+ph+"<td>");
city = crs.getString("city");
out.println("<td>"+city+"<td>");
state = crs.getString("state");
out.println("<td>"+state+"<td>");
country = crs.getString("country");
out.println("<td>"+country+"<td>");
out.println("</tr>");
}
out.println("</Table>");
Reprinted for v697039, Verizon
11
out.println("</Body>");
out.println("</Html>");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
java.sql.*;
javax.sql.*;
sun.jdbc.rowset.*;
java.io.*;
After importing the packages, create a class, MyWebRowSet, and a method, main(). In the main()
method, create an object of the MyWebRowSet class:
public class MyWebRowSet {
public static void main(String args[])
{
MyWebRowSet rs = new MyWebRowSet();
try {
13
Listing 264 shows the code to browse information retrieved from the database:
Listing 264: Browsing Information Retrieved from a Database
private void scrollData(WebRowSet wrs) throws SQLException {
System.out.println("Displaying Records...");
String name;
int Id;
Reprinted for v697039, Verizon
14
wrs.beforeFirst();
while (wrs.next()) {
name = wrs.getString(1);
if (wrs.wasNull() == false) {
System.out.println("name is " + name);
} else {
System.out.println("name is null");
}
Id = wrs.getInt("id");
if (wrs.wasNull() == false) {
System.out.println("Id is " + Id);
if (Id == 3) {
System.out.println("Updating!");
wrs.updateInt("id", 110);
wrs.updateString("name", "Sam");
wrs.updateRow();
wrs.deleteRow();
wrs.moveToInsertRow();
wrs.updateInt("id", 120);
wrs.updateString("name", "John");
wrs.insertRow();
wrs.moveToCurrentRow();
wrs.next();
wrs.updateString("name", "David");
wrs.updateRow();
wrs.previous();
}
} else {
System.out.println("Id is null");
}
}
if (wrs.isAfterLast() == true) {
System.out.println("We have reached the end");
System.out.println("This is row: " + wrs.getRow());
}
while (wrs.previous()) {
name = wrs.getString("name");
if (wrs.wasNull() == false) {
System.out.println("name is " + name);
} else {
System.out.println("name is null");
}
Id = wrs.getInt(2);
if (wrs.wasNull() == false) {
System.out.println("Id is " + Id);
} else {
System.out.println("Id is null");
}
}
if (wrs.isBeforeFirst() == true) {
System.out.println("Cursor at the Start");
}
wrs.first();
if (wrs.isFirst() == true)
System.out.println("First Record");
System.out.println("Row Number: " + wrs.getRow());
if (wrs.isBeforeFirst() == false)
System.out.println("Not Before First");
wrs.last();
if (wrs.isLast() == true)
System.out.println("Reached Last Record");
System.out.println("Now the Record No is " + wrs.getRow());
if (wrs.isAfterLast() == false)
System.out.println("No not after last");
}
}
15
16
<col>David
</col>
<upd>Antony</upd>
<col>2</col>
<upd>110</upd>
</del>
<ins>
<col>Lara</col>
<upd>Romario</upd>
<col>120</col>
</ins>
<row>
<col>Susan
</col>
<col>5</col>
</row>
<row>
<col>Rose</col>
<col>7</col>
</row>
</data>
</RowSet>
18
jrs.close();
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex.getMessage());
}
}
You can view the complete code of the MyJDBCRowSet program here.
Related Topics
For related information on this topic, you can refer to:
An Overview of java.text API
Using Databases in Java