Sunteți pe pagina 1din 21

All rights reserved. Reproduction and/or distribution in whole or in part in electronic, paper or other forms without written permission is prohibited.

or other forms without written permission is prohibited. Java ReferencePoint Suite SkillSoft Corporation. (c) 2002.

Java ReferencePoint Suite

SkillSoft Corporation. (c) 2002. Copying Prohibited.

Reprinted for Balaji Nallathambi, Verizon Balaji@verizon.com

Reprinted with permission as a subscription benefit of Books24x7,

R ep rin ted wi t h pe rmi ss i o n a s a

i

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

Point 6: Working With RowSet

Ryan Moore Applications need to communicate with databases to access information such as employee records, payroll systems, travel−scheduling systems, and so on.

Numerous Application Programming Interfaces (APIs) have been developed to enable Java−based applications to communicate with databases. Of the available APIs, the Java Database Connectivity (JDBC) API is commonly used for connecting to databases. This API uses the RowSet interface to access information.

To understand how to work with the RowSet interface, you need to first understand the basics of JDBC (for more information on JDBC, see JDBC Data Access API).

This ReferencePoint explains the methods of connecting to a database and describes the techniques involved in JDBC, the disadvantages of these techniques, and the role of a RowSet in JDBC. The ReferencePoint also explains the types of RowSets, their uses, and the implementation of the CachedRowSet, JDBCRowSet, and WebRowSet classes, which form a part of the RowSet interface.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Understanding Database Connectivity Techniques

Some of the commonly used databases are IBM DB/2, Microsoft SQL Server, Oracle, Sybase, and SQLBase. APIs that facilitated clients to interact with these databases were provided by these vendors. Each database needed an individual API. As a result, the same application code was not applicable to all databases. JDBC partly solves this problem by providing a common interface that allows applications to communicate with all databases.

Existing Database Connectivity Techniques

JDBC is an object−oriented standard API that allows application code to make requests, retrieve data, and access specific details from databases. JDBC connects to a database using one of the following four types of JDBC drivers:

JDBC−ODBC bridge: Uses a native library with a common interface Open Database Connectivity (ODBC) and is not database−specific.

Native−API: Is partly a Java driver and accesses a database−specific driver using a native library. This driver is faster than the JDBC−ODBC bridge driver because it has to traverse fewer layers.

Net−protocol: Is a pure Java driver and uses a database gateway to communicate with the database server.

Native−protocol: Is a pure Java driver and communicates directly with the database. Native−protocol is a fast and popular JDBC driver.

The first two drivers, JDBC−ODBC bridge and Native−API, require the client computer to have a native library. The other two drivers do not use a native library and are data−specific. Therefore, these drivers are much faster that the JDBC−ODBC bridge and Native−API drivers. Figure 2−6−1shows how a driver works and the various layers that drivers need to traverse:

works and the various layers that drivers need to traverse: Figure 2−6−1: Working of JDBC Drivers

Figure 2−6−1: Working of JDBC Drivers

Techniques Used in JDBC

The core JDBC API, java.sql.*, includes the standard (Java Development kit). This API is not a single interface, but a group of interfaces that facilitate database connectivity. A few important JDBC API interfaces are:

java.sql.DriverManager: Manages a set of JDBC drivers

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

3

java.sql.Connection: Opens a connection with a specific database

java.sql.Statement: Executes SQL statements

java.sql.ResultSet: Retrieves a set of results from the database based on the request.

To connect to a database using JDBC interfaces:

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.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

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 2−6−1 lists comparisons between the RowSet and the ResultSet:

Table 2−6−1: Comparison of a ResultSet and RowSet

ResultSet

RowSet

Is a table of data representing a database result set

Contains a set of rows from a result set or another source of tabular data, such as a file or spreadsheet

Is usually generated by executing a statement that queries the database

Is executed using a bean development tool

Can be used in a while loop to iterate through the result set

Follows the JavaBeans model for properties and event 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();

JDBCRowSet: Is non−serializable and uses an internal connection that opens a connection on a call to the execute() method and closes the connection by the close() method. The

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

5

JDBCRowSet acts as a layer around the ResultSet, making it appear as a JavaBean component. Requests to JDBC RowSets are filtered by the mapping call in a JDBC connection, statement, or result set. The JDBC interface is used in the same way as other RowSet implementations. The code used to create a JDBCRowSet is:

JDBCRowSet jrs = new JDBCRowSet();

WebRowSet: Is a connected RowSet that provides a distributed implementation of the RowSet interface. A WebRowSet is similar to JDBCRowSet but uses the HTTP protocol to communicate internally to a Java Servlet that provides access to the database. A WebRowSet caters to thin clients that need access to only a set of rows. The code used to construct a WebRowSet is:

WebRowSet wrs = new WebRowSet();

Table 2−6−2 lists the key factors and contains a comparison between the CachedRowSet, JDBCRowSet, and the WebRowSet:

Table 2−6−2: A Comparison of RowSets

Parameter

CachedRowSet

JDBCRowSet

WebRowSet

Connection

Disconnected RowSet

Connected RowSet

Connected RowSet

state

Caching

Caches data in memory

Uses an internal connection that opens on execute() and closes on close()

Uses the HTTP protocol to communicate internally with a Java Servlet

Serialization

Serializable and can be moved across Java Virtual Machines (JVMs)

Non−serializable

Non−serializable

Uses and Properties of RowSets

RowSets can be used for:

Transmitting data over a network

Making a result set scrollable, updatable, or both

Permitting the driver, its connection, and the current result set to be used as JavaBeans components

Retrieving filtered data by querying for values within a specified range

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.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

6

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 2−6−3 lists the important properties of RowSets and their descriptions:

Table 2−6−3: Important Properties of a RowSet

Property

Description

Type

Sets the RowSet type

Concurrence

Sets the concurrency for a RowSet

Command

Sets a RowSet's command property to the given String object and clears the parameters, if any, which were set for the previous command

Data Source

Sets the data source property name for the RowSet object

Username

 

Password

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

Transaction isolation

 

Escape processing

Sets the transaction isolation property for a RowSet to the given constant Sets the escape substitution before sending SQL statements to the database

Maximum field size

Sets the maximum number of bytes that can be used for a column value in

Maximum rows

this RowSet to the given number Sets the maximum number of rows that this RowSet object may contain to

Query time out

the given number Sets the maximum number of seconds the driver will wait for a query to

Type map

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 2−6−3:

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 read−only, 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 RowSet s command string is set with the query SELECT * FROM PRICES. The command property

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

7

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")

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Implementing the CachedRowSet

The CachedRowSet is similar to a ResultSet except that it is disconnected. It reduces connection time and communicates easily with thin clients. The CachedRowSet caches the requested data in memory and ends the connection.

The FetchEmployee Program

This section contains the FetchEmployee.java program that fetches the records of employees from the specified table and stores them in CachedRowSet according to the properties set for the CachedRowSet. The CachedRowSet object is then assigned to a session variable and displayed using another servlet.

Importing Packages and Deriving from the HttpServlet Class

Declare the import statements for including the necessary packages for using the APIs of servlet, SQL, and input output operations:

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import 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:

public class FetchEmployee extends HttpServlet

{

public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOE

Managing Database Operations

To manage database operations in the FetchEmployee.java program:

1. Create objects of the Connection, Statement, and ResultSet classes for managing database interaction.

2. Register the driver for JDBC. In this program, the name of the driver is sun.Jdbc.Odbc.JdbcOdbcDriver.

3. Initialize the connection object using the getConnection() method of DriverManager and the statement object using the createStatement() method.

4. Create a string object and assign the SQL query to it.

5. Execute the SQL query using the statement object and assign it to the ResultSet object.

6. Create an object of CachedRowSet and populate the values from the ResultSet object.

7. Create a Session object and bind the object of CachedRowSet to the Session object by assigning it a name, mycrs.

8. Close the connections and assign the ResultSet object to null.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

9

9. Redirect to another servlet, ShowEmp, for displaying the results.

Listing 2−6−1 shows the code to implement database management in the FetchEmployee.java program:

Listing 2−6−1: 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 2−6−1, you can manage database operations from the FetchEmployee.java program.

You can view the complete code of this program here

Understanding the ShowEmp Program

The ShowEmp.java program retrieves the value from a session variable and assigns it to an object of the CachedRowSet class by typecasting it. The values in the CachedRowSet class are displayed at the client.

Importing Packages and Deriving from the HttpServlet Class

To use the ShowEmp.java program, first declare the import statements for including the necessary packages for using the APIs of the servlet, SQL, RowSet, and input/output operations:

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import 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:

public class ShowEmp extends HttpServlet

{

public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOE

{

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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.

Listing 2−6−2 shows the code to perform these steps:

Listing 2−6−2: Declaring Objects for the ShowEmp.java Program

String id = new String(); String name=new String(); String add=new String(); String ph=new String(); String city=new String(); String state=new String();

String country=new String(); try

{

HttpSession s = req.getSession(true); PrintWriter out = res.getWriter(); CachedRowSet crs = new CachedRowSet(); crs = (CachedRowSet)s.getAttribute("mycrs");

Displaying Information to the Client

After you typecast the object retrieved from the session object, create a table and print the values to the client. To print values, use the while loop and iterate through the rows retrieved in the RowSet. Listing 2−6−3 shows the code for this process:

Listing 2−6−3: Displaying Information to the End User

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

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

11

out.println("</Body>");

out.println("</Html>");

}

catch(Exception e)

{ System.out.println(e);

}

}

}

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Implementing the WebRowSet

The WebRowSet is a connected RowSet. The program is created based on the same scenario used for the CachedRowSet. The objective is to acquire employee records and store them in the RowSet object.

Importing Packages and Defining the main() Method

Declare the import statements for including the necessary packages for using the APIs of servlet, SQL, and input/output operations:

import java.sql.*; import javax.sql.*; import sun.jdbc.rowset.*; import 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 {

Writing the Code for the main() Method

In the main() method, after you create an object of the WebRowSet class, write the code to retrieve data from the employee table. To retrieve this data:

1. Set the properties, such as Data Source Name (DSN), username, and password, of the WebRowSet.

2. Provide the SQL statement as a parameter to the command property of the WebRowSet.

3. Run the query using the execute command and populate the results.

The code to retrieve data from the employee table is:

WebRowSet wrs; wrs = new WebRowSet(); wrs.setUrl("jdbc:odbc:mydsn"); wrs.setUsername(""); wrs.setPassword(""); wrs.setCommand("select name, id from employee"); wrs.execute();

Writing the Output to a File and Navigating Records

To write the output to a file and navigate records:

1. Create an object of the FileWriter class to write the contents to a file named Employee.xml.

2. Display the values using the method scrollData().

3. Write the details in the file.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

13

The code for implementing these tasks is:

java.io.FileWriter FW = new java.io.FileWriter("Employee.xml"); scrollData(wrs); wrs.writeXml(FW); } catch (Throwable ex) { System.out.println(ex.getMessage());

}

}

Defining the Methods for Startup and Navigating Records

Define the methods for startup and navigating records by:

1. Creating a method, startup(), for performing startup operations before using the WebRowSet

2. Creating a Connection object and obtain the connection using a user−defined method getConnection()

3. Setting the properties of the connection object

4. Creating a Connection object

The code for performing these tasks is:

private void startup() throws SQLException { Connection con = getConnection(); con.setAutoCommit(false); con.setAutoCommit(false); Statement smt = con.createStatement();

Browsing Data Retrieved from the Database

In the scrollData() function, write the code to browse records retrieved from the database. When writing the code:

1. Create variables for storing the values fetched from database.

2. Navigate to the beginning of the record.

3. Update the record with new value if the id value is equal to three.

4. Check for the position of the cursor and display the messages accordingly.

Listing 2−6−4 shows the code to browse information retrieved from the database:

Listing 2−6−4: 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

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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");

}

}

}

Listing 2−6−4 completes the MyWebRowSet.java program.

You can view the complete code of this program here. Listing 2−6−5 shows the XML output of the MyWebRowSet.java program:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

15

Listing 2−6−5: XML Output

<?xml version="1.0" encoding="UTF−8"?> <!DOCTYPE RowSet PUBLIC '−//Sun Microsystems, Inc.//DTD RowSet//EN' 'http://java.sun.com/j2ee/d <RowSet> <properties> <command>select name,id from employee</command>

<concurrency>1007</concurrency>

<datasource><null/></datasource> <escape−processing>true</escape−processing>

<fetch−direction>0</fetch−direction>

<fetch−size>0</fetch−size>

<isolation−level>1</isolation−level>

<key−columns>

<column>1</column>

<column>2</column>

</key−columns> <map></map>

<max−field−size>0</max−field−size>

<max−rows>0</max−rows>

<query−timeout>0</query−timeout>

<read−only>true</read−only>

<rowset−type>1004</rowset−type>

<show−deleted>false</show−deleted> <table−name><null/></table−name> <url>jdbc:odbc:mydsn</url> </properties> <metadata>

<column−count>2</column−count>

<column−definition>

<column−index>1</column−index>

<auto−increment>false</auto−increment> <case−sensitive>false</case−sensitive> <currency>false</currency>

<nullable>1</nullable>

<signed>false</signed> <searchable>true</searchable>

<column−display−size>10</column−display−size>

<column−label>name</column−label> <column−name>name</column−name> <schema−name></schema−name>

<column−precision>10</column−precision>

<column−scale>0</column−scale>

<table−name>employee</table−name> <catalog−name></catalog−name>

<column−type>1</column−type>

<column−type−name>CHAR</column−type−name> </column−definition> <column−definition>

<column−index>2</column−index>

<auto−increment>false</auto−increment> <case−sensitive>false</case−sensitive> <currency>false</currency>

<nullable>1</nullable>

<signed>true</signed> <searchable>true</searchable>

<column−display−size>11</column−display−size>

<column−label>id</column−label> <column−name>id</column−name> <schema−name></schema−name>

<column−precision>10</column−precision>

<column−scale>0</column−scale>

<table−name>employee</table−name> <catalog−name></catalog−name>

<column−type>4</column−type>

<column−type−name>INTEGER</column−type−name>

</column−definition>

</metadata>

<data>

<row>

<col>John

</col>

<col>1</col>

</row>

<del>

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

16

<col>David

<upd>Antony</upd>

<col>2</col>

<upd>110</upd>

</col>

</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>

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Implementing the JDBCRowSet

The JDBCRowSet program demonstrates the implementation of the JDBCRowSet class. This program implements the JDBCRowSet for displaying the records in the console.

Instantiating the JDBCRowSet Class

You instantiate the JDBCRowSet class to use its methods for retrieving data from the data source. Before you instantiate this class, you need to import the necessary packages and create the main() method for the application:

import java.sql.*; import javax.sql.*;

import sun.jdbc.rowset.*; public class MyJdbcRowSet

{

Connection con = null; Statement stmt = null; JdbcRowSet jrs = null; public static void main(String Args[]) {

try

{

MyJdbcRowSet rs = new MyJdbcRowSet();

Performing Database Operations

You can define the Proceed() method for connecting to the data source and retrieving records as follows:

1. Create an object of the EchoListener class for trapping the events that occur within rows.

2. Initialize the JDBCRowSet.

3. Set the properties of the RowSet.

4. Set the SQL command to the Command property of the JDBCRowSet class.

5. Browse the data and print it on the console by using the scrollData() method.

6. Close the JdbcRowSet.

Listing 2−6−6 shows the code for performing these steps:

Listing 2−6−6: Defining a Method to Interact with the Database

public void proceed()

{

try { EchoListener echo = new EchoListener(); jrs = new JdbcRowSet(); jrs.addRowSetListener(echo); jrs.setUrl("jdbc:odbc:mydsn"); jrs.setUsername(""); jrs.setPassword(""); jrs.setCommand("select name,id from employee"); jrs.execute(); scrollData(jrs);

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

18

}

jrs.close();

}

catch (SQLException ex)

{

}

System.err.println("SQLException: " + ex.getMessage());

You can view the complete code of the MyJDBCRowSet program here.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Related Topics

For related information on this topic, you can refer to:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited