Working With RowSet

21
All rights reserved. Reproduction and/or distribution in whole or in part in electronic, paper or other forms without written permission is prohibited. Java ReferencePoint Suite SkillSoft Corporation. (c) 2002. Copying Prohibited. Reprinted for Balaji Nallathambi, Verizon [email protected] Reprinted with permission as a subscription benefit of Books24x7, http://www.books24x7.com/

description

rowset

Transcript of Working With RowSet

Page 1: Working With RowSet

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

is prohibited.

Java ReferencePoint SuiteSkillSoft Corporation. (c) 2002. Copying Prohibited.

Reprinted for Balaji Nallathambi, [email protected]

Reprinted with permission as a subscription benefit of Books24x7,http://www.books24x7.com/

Page 2: Working With RowSet

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

i

Page 3: Working With RowSet

Point 6: Working With RowSetRyan MooreApplications 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−basedapplications 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 toaccess information.

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

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

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 4: Working With RowSet

Understanding Database Connectivity TechniquesSome of the commonly used databases are IBM DB/2, Microsoft SQL Server, Oracle, Sybase, andSQLBase. APIs that facilitated clients to interact with these databases were provided by thesevendors. Each database needed an individual API. As a result, the same application code was notapplicable to all databases. JDBC partly solves this problem by providing a common interface thatallows applications to communicate with all databases.

Existing Database Connectivity Techniques

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

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

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

Net−protocol: Is a pure Java driver and uses a database gateway to communicate with thedatabase 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 anative 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. Figure2−6−1shows how a driver works and the various layers that drivers need to traverse:

Figure 2−6−1: Working of JDBC DriversTechniques Used in JDBC

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

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

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 5: Working With RowSet

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:

A request for data is placed and a connection is opened to the database server.1.

The ResultSet object obtains the requested values and makes the data accessible.2.

The connection is kept open until data exists in the ResultSet object.3.

Java ReferencePoint Suite 3

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 6: Working With RowSet

Introducing RowSetsIn the existing techniques of data transfer, the application keeps the connection open until theResultSet object is in use. This feature can be a drawback when large numbers of end usersconnect 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 retrievedfrom 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 amanner similar to iteration through a ResultSet object. Table 2−6−1 lists comparisons between theRowSet and the ResultSet:

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

ResultSet RowSetIs a table of data representing a databaseresult set

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

Is usually generated by executing astatement that queries the database

Is executed using a bean development tool

Can be used in a while loop to iteratethrough the result set

Follows the JavaBeans model for properties and eventnotifications

Types of RowSets

The two types of RowSets are:

Disconnected RowSet: Stores data in memory and makes a connection to a data source toretrieve data or communicate updates back to the data source. A disconnected RowSetdoes not keep the connection open throughout the data transaction. An example of adisconnected 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. TheRowSets implemented by these classes are:

CachedRowSet: Is a disconnected RowSet that caches data in memory and provides all thefeatures of the JDBC 2.0 ResultSet. CachedRowSet transfers a set of rows across anetwork and makes a result set scrollable and updatable. CachedRowSets are thin andserializable. This makes them the perfect tool to supply thin Java clients, such as a PersonalDigital Assistant (PDA) or Network Computers (NC), with tabular data. The code for creatinga CachedRowSet is:

CachedRowSet crset = new CachedRowSet();

JDBCRowSet: Is non−serializable and uses an internal connection that opens a connectionon 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

Page 7: Working With RowSet

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

JDBCRowSet jrs = new JDBCRowSet();

WebRowSet: Is a connected RowSet that provides a distributed implementation of theRowSet interface. A WebRowSet is similar to JDBCRowSet but uses the HTTP protocol tocommunicate internally to a Java Servlet that provides access to the database. AWebRowSet caters to thin clients that need access to only a set of rows. The code used toconstruct 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 WebRowSetConnectionstate

Disconnected RowSet Connected RowSet Connected RowSet

Caching Caches data in memory Uses an internal connection thatopens on execute() and closeson close()

Uses the HTTPprotocol tocommunicateinternally with aJava Servlet

Serialization Serializable and can bemoved across Java VirtualMachines (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 JavaBeanscomponents

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 arelational database. As a result, the RowSet needs to have certain properties that allow it to connectto the database. The properties of a RowSet need to be set to determine its functionality.

Java ReferencePoint Suite 5

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 8: Working With RowSet

There are two kinds of properties, static and dynamic. Static properties are set at development timeand 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 DescriptionType Sets the RowSet typeConcurrence Sets the concurrency for a RowSetCommand Sets a RowSet's command property to the given String object and clears

the parameters, if any, which were set for the previous commandData Source Sets the data source property name for the RowSet objectUsername Sets the username property for a RowSet to the given user namePassword Sets the password used to create a database connection for this RowSet

to the given String objectTransaction isolation Sets the transaction isolation property for a RowSet to the given constantEscape processing Sets the escape substitution before sending SQL statements to the

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

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

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

execute to the given numberType map 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 areretrieved during run time. Before setting the properties, you need to create the RowSet. Therespective code for creating a CachedRowSet, a JDBCRowSet, and a WebRowSet are:

CachedRowSet crs = new CachedRowSetJDBCRowSet jrs = new JDBCRowSetWebRowSet wrs = new WebRowSet

The method for setting the properties is the same for all RowSets. In this list, a CachedRowSet isused 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 therows 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 setof updatable. By default, the concurrence property is set at read−only, as illustrated in thesecond line of code:

crsSet.CONCUR_UPDATABLE orcrsSet.CONCUR_READ_ONLY

Command attribute: Sets the command attribute. In the given line of code, the RowSet�scommand string is set with the query SELECT * FROM PRICES. The command property

Java ReferencePoint Suite 6

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 9: Working With RowSet

works in combination with the execute method. When you apply the execute method, theRowSet retrieves data from the PRICES table:

crsSet.setcommand (SELECT * FROM PRICES)

Data source attribute: Facilitates making a connection. You need to specify the data sourcename, the user name, and the password. The code that sets the username and passwordfor the data source object and sets the data source attribute is:

crsSet.setDataSourceName ("jdbc/pricesDB)crsSet.setUsername("fred")crsSet.setPassword("fredrock")

Java ReferencePoint Suite 7

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 10: Working With RowSet

Implementing the CachedRowSetThe CachedRowSet is similar to a ResultSet except that it is disconnected. It reduces connectiontime and communicates easily with thin clients. The CachedRowSet caches the requested data inmemory and ends the connection.

The FetchEmployee Program

This section contains the FetchEmployee.java program that fetches the records of employees fromthe specified table and stores them in CachedRowSet according to the properties set for theCachedRowSet. The CachedRowSet object is then assigned to a session variable and displayedusing 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 extendsthe 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,IOException

Managing Database Operations

To manage database operations in the FetchEmployee.java program:

Create objects of the Connection, Statement, and ResultSet classes for managing databaseinteraction.

1.

Register the driver for JDBC. In this program, the name of the driver issun.Jdbc.Odbc.JdbcOdbcDriver.

2.

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

3.

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

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

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

Create a Session object and bind the object of CachedRowSet to the Session object byassigning it a name, mycrs.

7.

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

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 11: Working With RowSet

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

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

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 theFetchEmployee.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 objectof the CachedRowSet class by typecasting it. The values in the CachedRowSet class are displayedat the client.

Importing Packages and Deriving from the HttpServlet Class

To use the ShowEmp.java program, first declare the import statements for including the necessarypackages 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, whichextends the HttpServlet class. The ShowEmp class performs the tasks implemented in the servletand overrides the service method for implementing the servlet:

public class ShowEmp extends HttpServlet{public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{

Java ReferencePoint Suite 9

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 12: Working With RowSet

Declaring Objects

After declaring the HttpServlet class:

Declare the String objects to store the values fetched from the CachedRowSet.1.

Create a Session and PrintWriter object for responding to the client.2.

Create an object of the CachedRowSet to assign to the object retrieved from the session.3.

Typecast the object retrieved from the session object to the CachedRowSet form.4.

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 tothe 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>State</th><th>Country</th>");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>");

Java ReferencePoint Suite 10

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 13: Working With RowSet

out.println("</Body>");out.println("</Html>");}catch(Exception e){ System.out.println(e);}}}

Java ReferencePoint Suite 11

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 14: Working With RowSet

Implementing the WebRowSetThe WebRowSet is a connected RowSet. The program is created based on the same scenario usedfor the CachedRowSet. The objective is to acquire employee records and store them in the RowSetobject.

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 retrievedata from the employee table. To retrieve this data:

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

1.

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

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

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:

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

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

Write the details in the file.3.

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 15: Working With RowSet

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:

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

Creating a Connection object and obtain the connection using a user−defined methodgetConnection()

2.

Setting the properties of the connection object3.

Creating a Connection object4.

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. Whenwriting the code:

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

Navigate to the beginning of the record.2.

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

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

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;

Java ReferencePoint Suite 13

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 16: Working With RowSet

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 theMyWebRowSet.java program:

Java ReferencePoint Suite 14

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 17: Working With RowSet

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/dtds/RowSet.dtd'><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>

Java ReferencePoint Suite 15

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 18: Working With RowSet

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

Java ReferencePoint Suite 16

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 19: Working With RowSet

Implementing the JDBCRowSetThe JDBCRowSet program demonstrates the implementation of the JDBCRowSet class. Thisprogram 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 asfollows:

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

Initialize the JDBCRowSet.2.

Set the properties of the RowSet.3.

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

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

Close the JdbcRowSet.6.

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

Page 20: Working With RowSet

jrs.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); }}

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

Java ReferencePoint Suite 18

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 21: Working With RowSet

Related TopicsFor related information on this topic, you can refer to:

An Overview of java.text API•

Using Databases in Java•

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited