Académique Documents
Professionnel Documents
Culture Documents
Student Guide
Copyright 2000 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, California 94303, U.S.A. All rights reserved.
This product or document is protected by copyright and distributed under licenses restricting its use, copying,
distribution, and decompilation. No part of this product or document may be reproduced in any form by any means
without prior written authorization of Sun and its licensors, if any.
Third-party software, including font technology, is copyrighted and licensed from Sun suppliers.
Sun, Sun Microsystems, the Sun Logo, Solaris, JDK, PersonalJava, Java, JavaBeans, 100% Pure Java, JDBC Compliant,
JavaSoft, Java Naming and Directory Interface, JavaBlend, JavaScript, and JDBC are trademarks or registered trademarks
of Sun Microsystems, Inc. in the U.S. and other countries.
All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc.
in the U.S. and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun
Microsystems, Inc.
UNIX is a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd.
The OPEN LOOK and Sun Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees.
Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user
interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface,
which license also covers Suns licensees who implement OPEN LOOK GUIs and otherwise comply with Suns written
license agreements.
U.S. Government approval required when exporting the product.
RESTRICTED RIGHTS: Use, duplication, or disclosure by the U.S. Govt is subject to restrictions of FAR 52.227-14(g)
(2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227-7015 (b)(6/95) and DFAR 227.7202-3(a).
DOCUMENTATION IS PROVIDED "AS IS" AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS,
AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH
DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.
Please
Recycle
Contents
About This Course ......................................................................................ix
Course Goal .........................................................................................ix
Course Overview ................................................................................. x
Course Map......................................................................................... xii
Module-by-Module Overview ....................................................... xiii
Course Objectives.............................................................................. xvi
Skills Gained by Module................................................................ xvii
Guidelines for Module Pacing ..................................................... xviii
Topics Not Covered.......................................................................... xix
How Prepared Are You?................................................................... xx
Introductions ..................................................................................... xxi
How to Use Course Materials ........................................................ xxii
Course Icons and Typographical Conventions ......................... xxiv
Icons ......................................................................................... xxiv
Typographical Conventions ...................................................xxv
Syntax Conventions ............................................................... xxvi
JDBC Overview ........................................................................................1-1
Objectives ...........................................................................................1-1
Relevance............................................................................................ 1-2
References .......................................................................................... 1-3
What Is the JDBC API? ..................................................................... 1-4
Drivers ................................................................................................ 1-7
Overview ....................................................................................1-7
Type 1 JDBC/ODBC Bridge Plus ODBC Driver .............1-10
Type 2 Native API................................................................1-12
Type 3 JDBC-Net ..................................................................1-14
Type 4 Native Protocol........................................................1-16
Finding Drivers .......................................................................1-18
JDBC Developer Interface.............................................................. 1-19
Packages ...................................................................................1-19
Classes and Interfaces.............................................................1-20
iii
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
v
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
vi
vii
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
viii
ix
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Course Overview
The JDBC API is a set of specifications that tell database vendors how
to enable Java applications to perform operations on their databases,
and allow you to write Java applications that connect to any database
that provides drivers.
Database Application Programming With Java Technology provides you
with the information and skills to connect a Java application to a
relational database management system (RDBMS) and retrieve and
manipulate data. Features of both the first and second releases of JDBC
are covered; the second release includes a number of features such as
support for connection pooling and more flexible navigation within a
result set.
You will also learn how to choose the correct application architecture
for use with JDBCtwo-tier, three-tier, or n-tierand how to map that
applications objects to tables in a database.
Information on SQLJ, another method for connecting a Java
application to a relational database, is included in an appendix.
Course Overview
Note Before taking this course, you should be somewhat familiar
with structured query language (SQL) and databases; a short review of
the basics is provided in Appendix A, Database Basics.
xi
Course Map
The following course map enables you to see what you have
accomplished and where you are going in reference to the course
goals.
xii
Module-by-Module Overview
This course contains the following modules:
xiii
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Module-by-Module Overview
xiv
Module-by-Module Overview
xv
Course Objectives
Upon completion of this course, you should be able to:
xvi
2 3 4 5
6 7 8
xvii
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
xviii
Day 1
A.M.
JDBC Overview
A.M.
Using JDBC
P.M.
Day 2
A.M.
P.M.
Day 3
A.M.
P.M.
Day 4
A.M.
P.M.
xix
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
xx
Introductions
Now that you have been introduced to the course, introduce yourself
to each other and the instructor, addressing the items shown on the
above overhead.
xxi
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
xxii
xxiii
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Icons
Additional resources Indicates additional reference materials are
available.
Exercise objective Indicates the objective for the lab exercises that
follow. The exercises are appropriate for the material being discussed.
xxiv
xxv
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
type varIdentifier
int myFirstVariable;
The first line shown, typically with elements in italics, is the syntax;
the second line is the example.
Any elements shown in italics are variables, which must have values
substituted for them.
class className
Any elements shown in square brackets, such as the classModifier
element in the following class declaration syntax, are optional:
[classModifier] class name {block}
xxvi
JDBC Overview
Objectives
Upon completion of this module, you should be able to:
1-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1
Relevance
Discussion What main tasks should JDBC complete to be useful in
connecting an application to a database?
1-2
1
References
Additional resources The following resources can provide
additional detail on the topics presented in this module, as well as the
entire course.
JDBC Overview
1-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1-4
JDBC Overview
1-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1
What Is the JDBC API?
The JDBC driver vendor provides implementations, in the form of
drivers, for the interfaces that are in the API. When the developer
subsequently uses JDBC methods in the developer interface, the
vendor-supplied classes in the drivers provide code for database
operations.
1-6
Drivers
Overview
A JDBC driver is a collection of classesthat implement the JDBC
interfaces required to connect a Java application to a database. Each
database driver must provide a class that has implemented the
java.sql.Driver interface. The database driver class then is used by
the generic java.sql.DriverManager class when it needs a driver to
connect to a particular database using a URL string.
The JDBC driver test suite is provided for driver vendors. Only drivers
that pass the JDBC driver test suite can be designated JDBC
Compliant. You can download the driver test suite from the
following site:
http://java.sun.com/marketing/enterprise/jdbc.html
JDBC Overview
1-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1
Drivers
Overview
The JDBC API is patterned after the open database connectivity model
(ODBC), which makes providing a JDBC implementation on top of
ODBC very small and efficient (Figure 1-1). ODBC is a standardized
API for accessing databases; it provides similar functionality as the
JDBC API for traditional languages, such as C and C++.
Figure 1-1 illustrates how a single Java application (or applet) can
access multiple database systems through one or more drivers.
Java application
JDBC API
JDBC driver manager
URL
JDBC-NET
driver
URL
JDBC-ODBC
Bridge driver
URL
Driver A
URL
Driver B
ODBC and
DB drivers
Figure 1-1
1-8
JDBC Drivers
1
Drivers
Overview
JDBC drivers generally fit into one of four categories shown in
Table 1-1.
Table 1-1
Driver Categories
Category
Driver
Category
Description
Pure Java
Technology
Net Protocol
JDBC-ODBC
Bridge
No
Direct
Native API
based
No
Direct
JDBC-Net
Communicates with an
intermediary server seated
between the client and the
database, using a network
protocol that is specific to
the intermediary
Yes
Connector
Native
Protocol
Yes
Direct
JDBC Overview
1-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Drivers
Type 1 JDBC/ODBC Bridge Plus ODBC Driver
The JDBC-ODBC bridge allows open database connectivity (ODBC)
drivers to be used as JDBC drivers. It was implemented to get the
JDBC API working quickly, and provides access to some of the less
popular database management systems (DBMSs) if JDBC drivers are
not implemented for them.
The bridge gives JDBC access to the database using an existing ODBC
driver. The ODBC driver uses native code that must be installed on
each database client. Therefore, this driver is most appropriate for
corporate networks where client installations are not a major problem,
or for an application server in a three-tier architecture.
1-10
1
Drivers
Type 1 JDBC/ODBC Bridge Plus ODBC Driver
This approach allows companies with a heavy investment in ODBC to
leverage that investment with the newer Java programming language
tools.
The disadvantage to this approach is that the application code calls the
JDBC driver manager, which invokes the JDBC driver. The driver calls
the ODBC driver manager, which invokes the ODBC driver, who
finally contacts the database. Failure can occur at several points in this
system.
The JDBC-ODBC bridge is bundled with the J2SDK, in the package
named sun.jdbc.odbc. A variety of vendors, including Intersolv,
Visigenic, SCO, and DataRamp have ODBC drivers that work with the
JDBC-ODBC bridge.
Figure 1-2 illustrates a system using this driver.
Application
Database
JDBC API
ODBC bridge
ODBC driver
Client
Figure 1-2
JDBC Overview
Server
JDBC-ODBC Bridge
1-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Drivers
Type 2 Native API
This kind of driver is built on top of a native database client library
(usually C or C++). The driver translates the JDBC calls into calls to
the API of the database client library. The library is distributed by the
provider of the DBMS. This driver, as well as the ODBC bridge,
requires native code installed on each database client.
The native API is an improvement over the JDBC/ODBC bridge, but it
does not accomplish the goal of the JDBC API, which is to write once
and run anywhere. If a particular DBMS vendor has not created a
client API for its database, then it becomes difficult to switch from one
DBMS to another.
This type of driver is not always uniformly distributed, so you might
not be able to run your application on all platforms capable of running
Java technology.
1-12
1
Drivers
Type 2 Native API
Figure 1-3 illustrates a system using this driver.
Application
JDBC API
Native code
libraries
Database
Client
Figure 1-3
JDBC Overview
Server
Native API
1-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Drivers
Type 3 JDBC-Net
This kind of driver communicates with an intermediary server seated
between the client and the database, using a network protocol that is
specific to the intermediary. These calls are translated by the
intermediary to DBMS-specific calls and forwarded to the database.
You do not need to install native code on the database client machines,
because you can implement the driver using only Java technology. If
the intermediary can talk to different DBMSs, you need only one JDBC
driver.
This type of driver has the most flexibility.
1-14
1
Drivers
Type 3 JDBC-Net
Figure 1-4 illustrates a system using this driver.
Application
JDBC API
JDBC-Net
Client
Figure 1-4
JDBC Overview
DBMS-specific
translator
Intermediary server
Database
Server
JDBC-Net
1-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Drivers
Type 4 Native Protocol
This kind of driver translates JDBC calls directly into the network
protocol used by the DBMS. This allows direct calls from the client to
the database. These protocols are proprietary, so the database provider
is the primary source for the driver. Several vendors have these in
progress.
This type of driver might give the best performance, but falls short for
the same reasons as the native API drivers: there is no flexibility to
allow for switching to different types of DBMSs.
1-16
1
Drivers
Type 4 Native Protocol
Figure 1-5 illustrates a system using this driver.
Application
JDBC API
Database
Native protocol
Client
Figure 1-5
JDBC Overview
Server
Native Protocol
1-17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1
Drivers
Finding Drivers
To view the latest information about drivers, check the following JDBC
Web page:
http://java.sun.com/products/jdbc/drivers.html
The first vendors with category 3 drivers available were SCO, Open
Horizon, Visigenic, and WebLogic.
1-18
java.sql Contains the classes and interfaces used for the base
functionality of JDBC
This package has been part of the Java programming language
since the JDK 1.1 was released. It is included in the Java 2
Platform, Standard Edition.
JDBC Overview
1-19
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1-20
DriverManager
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
1
JDBC Developer Interface
Classes and Interfaces
DriverManager Class
The DriverManager class manages database drivers and provides
support for creating new database connections. It connects Java
applications to the correct JDBC driver.
You can use DriverManager to load multiple drivers in memory at the
same time. Each driver can point to a separate database, or all drivers
can point to the same database.
Different drivers must have a different subprotocol identifier for the
DriverManager to distinguish among them. Subprotocols are covered
later in this module, in Identifying a Database Using a URL.
Driver Interface
The Driver interface represents a point of contact between a Java
application and a driver. A Driver can establish a connection to a
database. A developer typically supplies a URL-like string as input,
and the Driver returns a Connection.
Connection Interface
The Connection interface represents a session with a specific
database. The Connection allows developers to create statement
objects to represent database queries. In addition, you can use a
Connection to obtain information about the database and about the
JDBC driver capabilities.
JDBC Overview
1-21
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1
JDBC Developer Interface
Classes and Interfaces
Statement, PreparedStatement, and CallableStatement
Interfaces
Statement functions as a container for executing a SQL statement on a
given connection. There are two important subtypes of Statement:
PreparedStatement and CallableStatement. PreparedStatement
holds the precompiled SQL statement so that it can be executed
multiple times. CallableStatement executes SQL stored procedures.
ResultSet Interface
A ResultSet represents a set of return data provided when SELECT
SQL queries are executed; it is the result of executing a statement.
Within a row, you can access its column values in any order. You can
use the ResultSetMetaData interface to get information about the
ResultSet. A ResultSet maintains a cursor pointing to its current
row of data. Initially the cursor is positioned before the first row; the
next method moves the cursor to the next row.
The classes and interfaces in the JDBC Core API are shown in
Figure 1-6.
1-22
1
JDBC Developer Interface
java.lang.Object
Array*
java.lang.Throwable
Blob*
java.lang.Exception
Clob*
SQLException
Struct*
BatchUpdateException
SQLData*
SQLWarning
DataTruncation
SQLInput*
Connection
SQLOutput*
DatabaseMetaData
Driver
DriverManager
java.util.Date
Date
DriverPropertyInfo
Ref*
Time
ResultSet
TimeStamp
ResultSetMetaData
Legend
Statement
Class
Abstract
Class
PreparedStatement
CallableStatement
Interface
Extends
* New with JDBC 2.0
Types
Figure 1-6
JDBC Overview
1-23
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1-24
1
Identifying a Database Using a URL
Overview
The JDBC URL mechanism is intended to provide a framework so that
different drivers can use different naming systems that are appropriate
for their needs. Each driver need only understand a single URL
naming syntax, and can reject any other URLs that it encounters. The
conventions are flexible, implementing the following features.
JDBC URLs also allow a level of indirection. This means that the
JDBC URL can refer to a logical host or database name that is
dynamically translated to the actual name by a network naming
system.
This allows system administrators to avoid specifying particular
hosts as part of the JDBC name. There are several different
network name services (such as the network information service,
NIS), and there is no restriction on which ones you can use.
JDBC Overview
1-25
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1-26
JDBC Overview
1-27
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1-28
1
Identifying a Database Using a URL
subprotocol
Using a Network Naming Service as the Subprotocol
To specify a network naming service (so that the database name in the
JDBC URL does not have to be its actual name), use the subprotocol.
Naming service URL syntax
jdbc:namingService:dataSrcName
Example
jdbc:dcenaming:accounts-payable
In this example, the URL specifies that the local DCE naming service
should resolve the database name accounts-payable into a more
specific name that can be used to connect to the real database.
Note To use a network naming system, JNDI and the JDBC 2.0
standard extensions must be installed. These are covered in Module 6,
JDBC 2.0 Standard Extensions.
odbc Subprotocol
The odbc subprotocol is reserved for URLs that specify ODBC-style
data source names. Name-value pairs also can be included.
Syntax
jdbc:odbc:dataSrcName[;attributeName=attributeValue]
Example
Valid URLs include the following:
jdbc:odbc:fred
jdbc:odbc:wombat
jdbc:odbc:wombat;CacheSize=20;ExtensionCase=LOWER
jdbc:odbc:qeora;UID=kgh;PWD=fooey
JDBC Overview
1-29
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1-30
JDBC Overview
1-31
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
1-32
1
Think Beyond
From what you now know of the JDBC API, list the steps that would
be necessary to connect to and retrieve data from a database.
JDBC Overview
1-33
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Using JDBC
Objectives
Upon completion of this module, you should be able to:
2-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Relevance
Discussion Suppose you are tasked with writing an application that
retrieves, updates, modifies, and deletes information from a database.
Consider the following questions:
1. What do you need to know about the database?
2. What is the impact on the end-user (client) program if a different
database is used?
3. What considerations must be made to make the system flexible
and responsive to changes in the business? For example, suppose
that you deny service to certain customers.
2-2
Using JDBC
2-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Creating a Basic JDBC Application
2-4
2
Creating a Basic JDBC Application
The steps are illustrated in the following portion of example code,
which connects to a database named accounts on a server machine
named java1.com, using the JDBC-ODBC bridge.
// Step 1
1 Class.forName("oracle.jdbc.driver.OracleDriver");
// Step 2
2 Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@java1.com:1521:accounts", "marcl", "mpuppet");
// Step 3
3 Statement stmt = con.createStatement();
// Step 4
4 String SQL_stmt = "SELECT a, b, c FROM table1";
5 ResultSet rs = stmt.executeQuery(SQL_stmt);
// Step 5
6 while (rs.next()) {
7
System.out.println("a=" + rs.getInt("a"));
8
System.out.println("b=" + rs.getString("b"));
9
System.out.println("c=" + rs.getFloat("c"));
10 }
// Step 6
11 rs.close();
12 stmt.close();
13 con.close();
The following sections provide details about each step.
Using JDBC
2-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2-6
2
Step 1 Registering a Driver
Approaches to Registering a Driver
There are several ways to register a driver within a Java application:
Instantiate a driver
Note You need to gain access to the JDBC interfaces before you
begin. To do so, be sure to import the java.sql package, or only the
classes in that package that you need.
Using JDBC
2-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2-8
Using JDBC
2-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Notes
2-10
Using JDBC
2-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Step 1 Registering a Driver
Using the jdbc.drivers Property
Defining the jdbc.drivers Property
Note This approach must be done on the command line, or run by a
script, before launching the Java application.
Syntax
jdbc.drivers = driverName[:driverName]
Example
jdbc.drivers = oracle.jdbc.driver.OracleDriver:acme.cool.Driver
2-12
Using JDBC
2-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Step 1 Registering a Driver
Choosing the Best Registration Approach
Discussion For each approach, what are the advantages and
disadvantages, and why?
2-14
Properties list
Memory
Using JDBC
2-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Step 2 Establishing a Connection to the Database
Connection Process
4. If the driver does not match, null is returned and the next driver
is checked.
5. If the Java application cannot connect to the database, a
SQLException is thrown. This would happen if no suitable driver
can be found, or because the last driver found was suitable but
failed during the attempt to connect.
Exception handling in JDBC is covered in Module 4, JDBC
Advanced Topics.
2-16
2
Step 2 Establishing a Connection to the Database
Connection Process
Figure 2-1 illustrates how a DriverManager resolves a URL string
passed in the getConnection method. When the driver returns a null,
the driver manager continues to call the next registered driver until
either the list is exhausted or a Connection object is returned.
getConnection(urlString)
DriverManager
Application
connect(urlString)
Connection
null
null
jdbc:A
driver
jdbc:B
driver
jdbc:odbc
driver
Successful
connection
accounts
Figure 2-1
Using JDBC
2-17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
DriverManager.getConnection method
Driver.connect method
DriverManager.getConnection
There are three getConnection methods; you can use any of them to
establish a connection:
getConnection (urlString)
getConnection (urlString, PropertiesObject)
getConnection (urlString, user, password)
Syntax
Connection conRefVar = DriverManager.getConnection(arguments);
2-18
2
Step 2 Establishing a Connection to the Database
DriverManager.getConnection
Example
The following example establishes a connection con to the database
named accounts on the specified host.
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@java1.com:1521:accounts");
Using JDBC
2-19
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2-20
2
Step 2 Establishing a Connection to the Database
Driver.connect
Syntax
Connection conRefVar = Driver.connect(urlString, PropertiesInfo);
Example
There is an assumed import of the java.sql package in the following
example, as well as the presence of a supporting class and method.
1 Driver drv = new oracle.jdbc.driver.OracleDriver();
2 Connection con = null;
3 try{
4
// Pass the connection request directly to THIS driver.
5
// If the connection attempt fails, the application
6
// will NOT try to connect to any other JDBC drivers.
7
con = drv.connect("jdbc:oracle:thin:@java1.com:1521:accounts",
null);
8 }
9 catch (SQLException exc){
10 // If unable to obtain a connection, take some kind
11 // of recovery action here. Options might include
12 // connecting to an alternate DB, prompting the user
13 // for action, or exiting the application.
14 }
Using JDBC
2-21
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2-22
Statement stmt;
try {
stmt = con.createStatement();
} catch (SQLException e) {
System.out.println (e.getMessage());
}
ResultSet rs = stmt.executeQuery
("SELECT * FROM customer WHERE ID = 11");
Using JDBC
2-23
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Step 3 Creating a Statement
Statement
Note For more information about SQL commands, refer to Appendix
A, Database Basics.
2-24
Using JDBC
2-25
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Step 3 Creating a Statement
PreparedStatement
Examples
1 public boolean prepStatement(float sales, String name){
2
PreparedStatement prepStmnt = con.prepareStatement
("SELECT * FROM coffees WHERE cof_name = ?");
3
prepStmnt.setString(1, "Espresso");
4
ResultSet rs = prepStmnt.executeQuery();
5 }
1 PreparedStatement ps = c.prepareStatement(
"UPDATE customer SET order_num = ? WHERE cid = ?");
2 ps.setInt(1, 543);
3 ps.setString(2, "0147");
4 int result = ps.executeUpdate();
Note For prepared statements, placeholders have a beginning index
of 1, not 0.
Refer to the PreparedStatement interface in the Java 2 Platform API
Specification for a list of the setXXX methods. These methods, used
for setting SQL IN parameter values, must specify types that are
compatible with the defined SQL type of the input parameter. For
example, if the IN parameter has SQL type Integer, then use setInt.
2-26
Using JDBC
2-27
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Step 3 Creating a Statement
CallableStatement
Example
You could use a CallableStatement if you wanted to store a
precompiled SQL statement to query a database containing the coffee
inventory or suppliers.
1 String coffeeName= "Espresso";
2 CallableStatement querySales = con.prepareCall
("{call return_sales[?, ?]}");
3 try {
4
querySales.setString(1, coffeeName);
5
querySales.registerOutParameter(2, Type.REAL);
6
querySales.execute();
7
float sales = querySales.getFloat(2);
8 } catch (SQLException e){
9
System.out.println("Query failed");
10
e.printStackTrace();
11 }
1 CallableStatement cs = c.prepareCall
("{call get_order_number [?, ?]}");
2 cs.setString(1, "0147");
3 cs.registerOutParameter(2, Type.INTEGER);
4 cs.execute();
5 int returnVal = cs.getInt(2);
Before executing a stored procedure call, you must explicitly call
registerOutParameter to register the java.sql.Type of any SQL
OUT parameters.
2-28
2
Step 3 Creating a Statement
Comparing Statement Interfaces
Table 2-1 compares the three types of statement interfaces.
Table 2-1
PreparedStatement
CallableStatement
Where is code
created?
Client
Client
Server
Where is code
stored?
Client
Server
Server
Technologies for
writing code
Java programming
language, SQL
operations
Java programming
language, SQL
operations
The procedural
language for the
database on the
target platform, such
as PLSQL (the
procedural language
for SQL)
Configurability
High
Low
Portability
High
Low
Efficiency for
transferring
data
Low
High
Using JDBC
2-29
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2-30
Using JDBC
2-31
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Step 4 Executing the SQL
Statement
Syntax
1 Connection conRefVar = DriverManager.getConnection(urlString);
2 Statement stmtRefVar = conRefVar.createStatement();
3 ResultSet resultsetRefVar = stmtRefVar.executeQuery (sqlString);
Example
1 Connection con = DriverManager.getConnection(
"jdbc:odbc:accounts");
2 Statement stmt = con.createStatement();
3 ResultSet rs = stmt.executeQuery("SELECT * from employees");
2-32
Using JDBC
2-33
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Step 5 Processing the Results
Refer to the Java 2 Specification API for the getXXX methods to access
columns within the ResultSet. These include getBoolean(int
columnIndex), getByte(int columnIndex), and getInt(int
columnIndex).
To retrieve data from the ResultSet object, you must be familiar with
the columns returned and their data types. A table mapping Java types
to SQL data types is provided in Table 3-1 of Module 3, OOAD and
Database Design.
Syntax
1 while (resultsetRefVar.next()) {
2
System.out.println ("column: " +
resultsetRefVar.getXXXMethod(column));
3 }
2-34
"
"
"
"
+
+
+
+
rs.getString(1));
rs.getInt(2));
rs.getFloat(3));
rs.getInt(4));
Using JDBC
2-35
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Step 6 Closing Down JDBC Objects
The following example shows how to close down a ResultSet,
Statement, and Connection object, and catching any resulting
exceptions.
1
2
3
4
5
6
7
8
try {
rs.close();
stmt.close();
con.close();
}
catch (SQLException ex) {
ex.printStackTrace();
}
Note Be sure that you do the closing down inside a finally block of
exception handling to ensure that the objects are closed when you exit.
2-36
2
Exercise: Using JDBC
Exercise objective Practice the concepts and tasks you have learned
in this module.
Tasks
Go to the SL330 directory on your computer and change to the lab files
directory. Open the directory for this module, then the directory for
this exercise, and read the readme file. Follow the instructions in that
file to complete this exercise.
If additional instructions or materials are required, your instructor will
provide them.
Using JDBC
2-37
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Exercise: Using JDBC
Exercise Summary
Discussion Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
2-38
Experiences
Interpretations
Conclusions
Applications
2
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Using JDBC
2-39
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Think Beyond
The Java programming language is object oriented; a relational
database is not. What do you need to do to connect the Java
technology object model logically to the database?
2-40
Objectives
Upon completion of this module, you should be able to:
3-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Relevance
Discussion What would be the best way to correlate objects with
tables in your database?
3-2
3
References
Additional resources The following resources can provide
additional detail on the topics presented in this module:
3-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Module Overview
When you develop an object-oriented application that accesses a
database, it is important to also consider how you will store data from
objects in the database, and how you will use and retrieve the data.
You need to take into account many issues, including the following:
This module describes how to deal with these issues, through object
IDs (OIDs) and object-relational mapping.
Note The principles discussed apply to any object-oriented
application, not only to those created using the Java programming
language.
3-4
Object ID Overview
A requirement in classic relational DBMS is that every row entry in a
table must be uniquely identifiablethat is, there should be a way to
uniquely identify every record.
In databases, this is represented at the table level by a primary key, a
value unique for every database record in the table. However,
sometimes you need to retrieve and combine data from multiple
tables, and the primary key might not be unique in this case.
This section describes object IDs (OIDs), which are unique record
identifiers that have no business meaning, and explains how they can
be used more effectively than other indexes, such as primary keys, to
uniquely identify objects (records) in one or more databases.
3-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3-6
3
Object IDs and Primary Keys
3-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Object IDs and Primary Keys
Another example could be a national identification number (social
security number in the United States). Many applications use this
number as a primary key; if the country changes its system of
identifying residents, or if a country with a different system of
identification numbers needs to use the application, the
application and tables would need to change.
3-8
If you make the OID unique only within a class, then you can have
12345 as the OID for a customer, an employee, an order, and any
other classes in the class diagram.
This is not a problem until an employee needs to become a
customer or a customer wants to be an employee. At this point,
you would need to assign the employee object a new OID.
3-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Object IDs and Primary Keys
If you make OIDs unique to each class, you separately create OIDs
for every table that stores object data in the system. This has the
following implications.
3-10
The solutions for this are to reassign a matching OID for both
tables. This is costly because you must find one that is free in
both tables, use a database join table, which is less efficient, or
place a foreign key in one or both tables. This is wasteful if
there are only a few employees who are also customers.
If the OID is unique within the class hierarchy, then this problem is
alleviated. You do not need to reassign OIDs when changes occur
within the class hierarchy, such as a customer becoming an
employee.
If the OIDs are unique across all classes, you never have to change
them based on the object model. This provides the best results for
unique object identification, but can result in slower performance.
Single-row table
High/low
Single-row Table
In this method, use a single-row table that stores the next available
unique OID. Each time the OID is used and assigned to a new object,
the value in the table is incremented.
However, there are concurrency issues because each time you create an
object, you must lock the table and update the OID to ensure the OID
is not duplicated. This can significantly decrease performance because
the same table must be accessed every time a new object is created.
3-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3-12
The first part, or high value, comes from a single-row table that is
retrieved at the beginning of the session. However, the high-low
approach is different from the single-row table approach because
you do not have to retrieve the value from the table for each
object; you do it only once per user session. Each user retrieves a
different value, but during that session each user has the same
high value. All OIDs are based on the high value but differentiated
by an incremented low value.
3
Creating Object IDs
High/Low
For example, assume a single-row table has the value 5000 and is
incremented by 1 at the beginning of each session. The application
begins the low values at 1 for each user and increments the low values
by 1 each time the user creates an object.
Note This process is illustrated in Figure 3-1 on page 3-14.
1. When user A starts the application, he or she retrieves the high
value from the table (5000). User A uses this high value
throughout the session.
2. The high value is incremented to 5001.
3. User B logs in and retrieves the next high value from the table,
5001.
4. The high value is incremented to 5002.
5. When user A creates his or her first new object, such as a new
customer record, the OID is 5000 with 1 appended to produce the
OID 50001.
The second object created by user A is 50002, and so on.
6. When user B creates new objects, they are assigned OIDs of 50011,
50012, and so on.
3-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Creating Object IDs
High/Low
Figure 3-1 illustrates each step in the example.
1
User A
User A
High Value
5000
High Value
5000 5001
5000
3
User B
User B
High Value
5001
High Value
5001 5002
5001
User A
5000
FirstName
LastName
SSN
Joe
Mays
674-58-4013
FirstName
LastName
SSN
Stelter
101-12-0086
50012
Grom
503-50-9901
OID
CustID
50001 C239PPL
User B
5001
OID
6
CustID
C249FGW Mike
Figure 3-1
3-14
High/Low Example
Object-Relational Mapping
Once you have determined how to uniquely identify each object, you
need to design the tables in your database, and decide how they will
relate to the classes in your application.
In an object-oriented application, data is stored as sets of related
values (attributes in OOAD terminology) within an object. (You can
store the attributes of an object in the relational database, but not the
operations.)
Relational databases store data as sets of related values (rows) within
one or more tables. This means that an important task in determining
a data storage strategy for an application is to map the object model to
the relational model. To do so, map the attributes of the classes to the
appropriate relational tables.
3-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Object-Relational Mapping
Inheritance complicates mapping classes to tables, because any
subclass has more attributes than are in the class definition. An
important part of mapping is deciding how to store the inherited
attributes in the database: in the same table as the subclass table, or in
another table.
Note Objects, not classes, are stored in tables. The point at which you
actually save the objects in the database is implementation-dependent.
3-16
Object-Relational Mapping
To connect your object model with the database, complete these steps
before you begin defining your database.
3-17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3-18
3
Mapping Classes to Tables
One Table for Every Class
This approach, shown in Figure 3-2, has one table per class. Each class,
regardless of type, has a table. Inherited attributes are not stored in the
table, so no data is duplicated across tables.
Classes
abstractPerson
personOID
firstName
lastName
address
Employee
Customer
customerOID
salutation
employeeOID
SSN
Tables
Person
personOID firstName
salutation
Figure 3-2
address
Employee
Customer
customerOID
lastName
personOID
employeeOID
SSN
personOID
3-19
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Mapping Classes to Tables
One Table for Every Class
Note personOID is not in the Customer and Employee classes in the
object model in Figure 3-2, but was added to the Customer and
Employee tables so that it can be used to look up information in those
tables. It is stored and maintained in all three tables.
3-20
3-21
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Mapping Classes to Tables
One Table for Every Class
Disadvantages
3-22
It takes longer to read and write to the tables, because you might
have to read from multiple tables to create one object.
3
Mapping Classes to Tables
One Table for Each Concrete Class
This approach has one table per concrete class (a class that is not
abstract). Each table would contain all attributes for the class plus the
attributes of the inherited class. Figure 3-3 shows mapping the Person,
Employee, and Customer classes using this approach.
Classes
abstractPerson
firstName
lastName
address
Employee
Customer
customerOID
salutation
employeeID
SSN
Tables
Customer
firstName
lastName
address
customerOID
salutation
employeeOID
SSN
Employee
firstName
lastName
Figure 3-3
address
3-23
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Mapping Classes to Tables
One Table for Each Concrete Class
Note In Figure 3-3, each subclass has its own OID, because there is a
table for each. personOID was removed from the abstractPerson class
in the object model because there is no table in that class for this
approach to table design.
3-24
Disadvantages
To modify a class, you must modify its table and the tables for any
subclasses.
3-25
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Mapping Classes to Tables
One Table for an Entire Class Hierarchy
This approach has one table for all attributes of all classes in the
hierarchy. Figure 3-4 shows mapping the Person, Employee, and
Customer classes.
Classes
abstractPerson
firstName
lastName
address
personOID
Employee
Customer
salutation
SSN
Table
Person
firstName
lastName
address
Figure 3-4
3-26
personOID
salutation
SSN
Polymorphism is supported.
3-27
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3-28
Database tables can become extremely large. All fields are not
needed for all records; for example, the salutation field is required
only for customers, not employees.
When you add a new column, if it cannot have a null value, you
must update all records with a value for that column.
Many operations need to access the same table, which can reduce
performance.
3
Mapping Classes to Tables
Mapping Two Classes to One Table
In some situations, you might need to map two classes to one
relational table. Figure 3-5 shows an example.
Classes
Address
PostalCode
addressOID
line1
line2
city
state
addressOID
postcodeOID
postalCode
Table
addressOID
Figure 3-5
line1
3-29
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3-30
3
Mapping Class Attributes to Table Columns
Once you have mapped classes to tables, you need to map the class
attributes to columns in the tables. To do so, first review Table 3-1,
which shows the standard Java technology data types (Java types)
and the corresponding common SQL types.
Table 3-1
SQL Type
Java Type
CHAR
String
VARCHAR
String
LONGVARCHAR
String
NUMERIC
java.math.BigDecimal
DECIMAL
java.math.BigDecimal
BIT
boolean
TINYINT
byte
SMALLINT
short
INTEGER
int
BIGINT
long
REAL
float
FLOAT
double
DOUBLE
double
BINARY
byte[]
VARBINARY
byte[]
LONGVARBINARY
byte[]
DATE
java.sql.Date
TIME
java.sql.Time
TIMESTAMP
java.sql.Timestamp
3-31
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Mapping Class Attributes to Table Columns
You need to understand how to manage data translation between the
application and database so that there is no chance for data truncation
or incorrect conversion. For every attribute to be stored on the
database, decide what its corresponding SQL data type will be.
Several of the Java types have two or more corresponding types in
SQL, so you must decide how you will store data with these Java types
in the database.
3-32
3-33
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Mapping Class Relationships to Tables
One-to-One Relationships
In a one-to-one relationship, the mapping is straightforward.
Sometimes it is only one-way; one table references another. Figure 3-6
illustrates the one-to-one relationship.
Classes
Car
carOID
engOID
year
model
doors
1 1
Engine
engOID
carOID
model
cylinders
serNum
Tables
Car
carOID
engOID
year
model
doors
cylinders
serNum
Engine
engOID
Figure 3-6
3-34
carOID
model
One-to-One Relationship
3-35
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Mapping Class Relationships to Tables
One-to-Many Relationships
In a one-to-many relationship, for every one record in the first table
there are one or more records in the second table. The OID of the class
in the first table is added to the class of the second table.
Figure 3-7 shows tables for Order and OrderLine classes, which have a
one-to-many relationship from Order to OrderLine (each order can
have one or more line items; each line item can have only one order).
Classes
Order
OrderLine
1 *
orderOID
OLOID
orderOID
isPrePaid
quantity
number
price
dateReceived
orderlines[ ]
Tables
Order
orderOID
isPrePaid number
dateReceived
OrderLine
OLOID
Figure 3-7
3-36
orderOID quantity
price
3-37
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Mapping Class Relationships to Tables
Many-to-Many Relationships
Figure 3-8 shows the object model and tables with a many-to-many
relationship.
Classes
Address
* *
addrOID
line1
line2
city
state
postalCode
Customer
custOID
name
address [ ]
Tables
Address
addrOID
line1
line2
Customer
custOID
name
Figure 3-8
3-38
state
city
postalCode
custOID
3-39
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Mapping Class Relationships to Tables
Many-to-Many Relationships
Table 3-1 shows possible OID values in each of the three tables, with
the many-to-many relationships in boldface.
Table 3-2
3-40
Address table
Join table
Customer table
addrOID
addrOID
custOID
custOID
38
38
23
23
38
314
314
114
10
614
584
22
43
39
48
93
47
322
22
22
15
15
10
15
3
Exercise: OOAD and Database Design
Exercise objective Practice the concepts you have learned in this
module.
Tasks
Go to the SL330 directory on your computer and change to the lab files
directory. Open the directory for this module, then the directory for
this exercise, and read the readme file. Follow the instructions in that
file to complete this exercise.
If additional instructions or materials are required, your instructor will
provide them.
3-41
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Exercise: OOAD and Database Design
Exercise Summary
Discussion Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
3-42
Experiences
Interpretations
Conclusions
Applications
3
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
3-43
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Think Beyond
What additional features would you like to have available for use in a
database application?
3-44
Objectives
Upon completion of this module, you should be able to:
Create transactions
4-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
4
Relevance
Discussion Multi-user access to a database can require you to make
decisions, such as whether to allow changes that have not yet been
committed. What similar situations might you encounter when
manipulating data in a database?
4-2
Exceptions
Overview
When a Java application communicates with the database, the
following elements are present:
The application
The database
When any part of this process goes wrong, the server must tell the
application. This is usually done using a SQLException, which
indicates any kind of error during a JDBC operation, or SQLWarning,
which indicates nonfatal problems. To address exceptions, use a
try/catch or throw construct.
4-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Exceptions
SQLException
SQLException is different from other exceptions because it can have a
list of exception objects.
In the SQLException class, the method getNextException returns
the SQLException object that is next in line. In addition,
getErrorCode returns an integer error code specified by the database
vendor, and getMessage returns a String error.
Possible failure points include:
4-4
4
Exceptions
SQLException
Many errors can occur on the server, such as attempting to select
columns that do not exist. An error is returned for each incorrect
column name.
4-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Exceptions
SQLWarning
SQLWarning is a subclass of SQLException that is returned for nonfatal SQL states. SQLWarnings are not thrown; they are chained
together, and you can refer to them at any time. To retrieve them, call
the getWarnings method. You can call this method on several
different objects: anything that could generate a warning, such as a
Connection, all statement objects, and a ResultSet.
SQLWarning has the same methods as SQLException, except that you
should use getNextWarning, instead of getNextException.
4-6
Metadata
Metadata is information about data, such as the column definitions in
the table. Data is a persons phone number; metadata is how many
characters the number can contain, whether the data is alphanumeric,
and so on.
Knowing the metadata for the information your application stores can
be very useful. The data is always available, which means you do not
need to generate it, only retrieve it.
Two types of metadata are available through the JDBC API:
Database metadata
4-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Metadata
Database Metadata
Use the Connection.getMetaData method to retrieve database
metadata.
This method returns a DatabaseMetaData reference that allows you to
use a number of methods to get information about the database. For
example, the isReadOnly method returns a boolean indicating
whether the database is editable.
4-8
Metadata
Result Set Metadata
Use the ResultSetMetaData class to view information about a result
set. If you want to use the metadata for result set, call the
ResultSet.getMetaData method for your result set; it retrieves a
ResultSetMetaData reference.
Once the reference is retrieved, you can use a variety of methods to
retrieve the information, such as getColumnCount to return an integer
that specifies the number of columns in the result set. You could then
iterate through the columns and retrieve the column names.
4-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Transactions
Overview
In database manipulation, a transaction is a logical group of work
consisting of one or more instructions. For example, the instructions
might be to enter a customer record, create a new order record, add a
line item to an order, and so on.
For a transaction to execute successfully, all of its instructions must be
successfully executed for the database. If there is an error any time
during transaction execution, the previous operations must be
reversed. This is referred to as backing out or performing a rollback on
a transaction. Use transactions to partition work to minimize the
chances of data corruption.
4-10
4
Transactions
JDBC Transaction Methods
To perform transactions in JDBC, perform the following steps:
To drop the changes since the last commit, call the rollback
method. Calling the rollback method on the connection drops all
changes that have been made since the previous commit/rollback
and releases any database locks currently held by this
Connection. This method should be used only when auto-commit
has been disabled.
4-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
4
Transactions
Basic Syntax
Syntax
In the following syntax, transactionEndMethod is either commit or
rollback.
1 Connection conRefVar = DriverManager.getConnection(urlString);
2 conRefVar.setAutoCommit(false);
3 Statement stmtRefVar = con.createStatement();
4 stmtRefVar.executeUpdate(sqlString);
5 conRefVar.transactionEndMethod;
Example
The following code shows a series of inserts and updates combined
into a transaction.
1 try {
2
con.setAutoCommit(false);
3
Statement stmt = con.createStatement();
4
stmt.executeUpdate("INSERT INTO customer(1011,'XYZ Corporation')");
5
stmt.executeUpdate("INSERT INTO order(21,1011,12.43f)");
6
con.commit();
7 } catch (SQLException ex) {
8
try {
9
con.rollback();
10
} catch (SQLException ex2){}
11 }
4-12
Transactions
Concurrency Control
Creating a transaction in the JDBC API is handled through the
Connection interface. For each connection, you can identify the
transaction isolation level, which determines what types of manipulation
are allowed. For example, it lets you control whether a row is reread if
it is altered after the first read.
The transaction isolation levels control the following:
Phantom reads When one transaction reads all rows that satisfy
a WHERE condition, a second transaction inserts a row that
satisfies that WHERE condition; the first transaction rereads for
the same condition, getting the additional row in the second read.
4-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Transactions
Concurrency Control
To see the current isolation level, use the getTransactionIsolation
method.
To set the transaction isolation level, call the
Connection.setTransactionIsolation method.
The following static variables set the isolation level.
4-14
4
Transactions
Concurrency Control
4-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
4
Transactions
Concurrency Control
Syntax
conRefVar.setTransactionIsolation(Connection.isolationLevel);
Note This method cannot be called while in the middle of a
transaction.
Example
1 Connection con;
2 con.setTransactionIsolation
(Connection.TRANSACTION_READ_UNCOMMITTED);
3 InitialContext initCtx =
Class.forName("oracle.jdbc.driver.OracleDriver");
4 con = DriverManager.getConnection
("jdbc:oracle:thin:@java1.com:1521:accounts", "marcl","mpuppet");
4-16
4
Exercise: JDBC Advanced Topics
Exercise objective Practice the concepts you have learned in this
module.
Tasks
Go to the SL330 directory on your computer and change to the lab files
directory. Open the directory for this module, then the directory for
this exercise, and read the readme file. Follow the instructions in that
file to complete this exercise.
If additional instructions or materials are required, your instructor will
provide them.
4-17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
4
Exercise: JDBC Advanced Topics
Exercise Summary
Discussion Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
4-18
Experiences
Interpretations
Conclusions
Applications
4
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Create transactions
4-19
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
4
Think Beyond
What additional features would be useful in a database application?
4-20
Objectives
Upon completion of this module, you should be able to:
This module describes how to use the main features added in the latest
release of the JDBC API.
5-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Relevance
Discussion Should a result set show or hide changes that have been
made to a database since it was retrieved? What advantages and
disadvantages are there for each approach?
5-2
5-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Scrollability
Updatability
Scrollability
5-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Forward-only
Scroll-insensitive
Scroll-sensitive
5-6
5
Result Set Enhancements
Scrollability
Scroll Settings
Scroll-sensitive and scroll-insensitive result sets differ in two ways
from the JDBC 1.0 functionality.
5-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Result Set Enhancements
Scrollability
Scroll Settings
You can use the items listed in Table 5-1 to control scroll sensitivity
and other aspects of the result set. (These are also listed in the Java 2
Platform API Specification.)
Table 5-1
5-8
Field Summary
Field
Type
Description
CONCUR_READ_ONLY
static int
CONCUR_UPDATABLE
static int
FETCH_FORWARD
static int
FETCH_REVERSE
static int
FETCH_UNKNOWN
static int
TYPE_FORWARD_ONLY
static int
TYPE_SCROLL_INSENSITIVE
static int
TYPE_SCROLL_SENSITIVE
static int
5
Result Set Enhancements
Scrollability
Scroll Settings
Syntax
Statement stmtRefVar = conRefVar.createStatement
(int resultSetType, int resultSetConcurrency);
ResultSet resultsetRefVar = stmtRefVar.executeQuery
(sqlString);
Examples
This example uses none of the new features, and works in JDBC 1.0 or
2.0, using only 1.0 functionality.
1 Connection con = DriverManager.getConnection(
"jdbc:odbc:accounts");
2 Statement stmt = con.createStatement();
3 ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
The previous example has been modified to use 2.0 features. It
establishes the connection, then uses 2.0 features to create a scrollable
result set that is updatable and scroll-sensitive.
1 Connection con = DriverManager.getConnection(
"jdbc:odbc:accounts");
2 Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
3 ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
5-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Result Set Enhancements
Scrollability
Scroll Settings
This example shows an example of an updatable, scroll-sensitive
cursor that retrieves 25 rows at a time: To specify the number of rows
to be retrieved at a time, use the Statement.setFetchSize method.
1 Connection con = DriverManager.getConnection(
"jdbc:odbc:accounts");
2 Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
3 stmt.setFetchSize(25);
4 ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
5-10
5-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Result Set Enhancements
Scrollability
Positioning
You can use the methods in Table 5-2 to move and position within the
result set; these methods and others not listed here are included in the
API Specification.
Table 5-2
5-12
Methods
Method
Type
Description
absolute(int row)
boolean
afterLast()
void
beforeFirst()
void
first()
boolean
last()
boolean
next()
boolean
previous()
boolean
relative(int)
boolean
5
Result Set Enhancements
Scrollability
Positioning
The JDBC 2.0 API also provides methods for you to determine where
you are within the ResultSet, shown in Table 5-3:
Table 5-3
Method
Type
Description
isAfterLast()
boolean
isBeforeFirst()
void
isFirst()
void
isLast()
boolean
5-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5-14
5
Result Set Enhancements
Updatability
To update the specific columns of a row, use the updateXXX methods,
which associate to the column type.
Updating a Row
The concurrency type must be CONCUR_UPDATABLE.
Syntax
Write an updateXXX statement for each column to update.
resultsetRefVar.updateXXX(column, value);
resultsetRefVar.updateRow();
column can be either the column number or name.
Example
The following code updates the first row of the result set.
1 rs.updateString(1, "100020");
2 rs.updateFloat("salary",60000.0f);
3 rs.updateRow();
You can specify the column number or column name when calling
updateXXX. The update performed on the result set is not applied to
the underlying database until you call updateRow. If you move the
cursor from the current row before calling updateRow, then the update
is discarded. In addition, you can call cancelRowUpdate to explicitly
cancel the updates, but you must call it before you make a call to
updateRow.
5-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Result Set Enhancements
Updatability
Deleting a Row
Syntax
resultsetRefVar.deleteRow();
Example
The following example shows how to delete a row. The sixth row in
the result set is deleted from the database.
1 rs.absolute(6);
2 rs.deleteRow();
resultsetRefVar.movetoInsertRow();
resultsetRefVar.updateXXX(column, value);
resultsetRefVar.insertRow();
5-16
5
Result Set Enhancements
Updatability
Inserting a New Row
Example
The following example shows how to insert a new row into the
ResultSet and database.
1 rs.moveToInsertRow(); rs.updateString(1, "100050");
2 rs.updateFloat(2, 80000.0f);
3 rs.insertRow();
5-17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5-18
The query selects all of the non-nullable columns in the table, and
all columns that do not have a default value.
Statement
PreparedStatement
CallableStatement
5-19
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5-20
5
Statement Enhancements for Batch Updates
Statement
Example
1
2
3
4
5
6
7
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Mays')");
stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");
stmt.addBatch("INSERT INTO emp_dept VALUES (1000, 260)");
int[] updateCounts = stmt.executeBatch();
con.commit();
In this example, auto-commit mode is disabled to prevent the JDBC
API from committing the transaction when the
Statement.executeBatch method is called. Disabling autocommit
allows the application to decide whether to commit the transaction in
the event that an error occurs and some of the commands in a batch
fail to execute. For this reason, you should usually turn off autocommit mode when you do batch updates.
5-21
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5-22
5
Statement Enhancements for Batch Updates
Statement
The Statement.executeBatch method submits a batch of commands
to the underlying DBMS for execution. Commands are executed in the
order in which they were added to the batch. The executeBatch
method returns an array of update counts for the commands that were
executed. The array contains one entry for each command in the batch,
and the elements in the array are ordered according to the order in
which the commands were executed (which, again, is the same as the
order in which the commands were originally added to the batch).
Calling executeBatch closes the calling Statement objects current
result set if one is open. The statementss internal list of batch
commands for the rest of the statements is reset to empty once
executeBatch returns.
The executeBatch method throws a BatchUpdateException if any
of the commands in the batch fail to execute properly. You can call the
BatchUpdateException.getUpdateCounts method to return an
integer array of update counts (int data types) for the commands in
the batch that were executed successfully.
The executeBatch method stops when the first command returns an
error, and commands are executed in the order that they are added to
the batch. Thefore, if the array returned by
BatchUpdateException.getUpdateCounts contains n elements, this
means that the first n commands in the batch executed successfully
when executeBatch was called.
5-23
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5-24
5
Statement Enhancements for Batch Updates
PreparedStatement
Syntax
PreparedStatement pstmtRefVar = conRefVar.prepareStatement
(sqlString);
pstmtRefVar.setXXXMethod(column, value);
// add other lines as necessary
pstmtRefVar.addBatch();
// submit the batch for execution
intArrayRefVar = pstmtRefVar.executeBatch();
Example
1 con.setAutoCommit(false);
2 PreparedStatement stmt = con.prepareStatement
("INSERT INTO employees VALUES (?, ?)");
3 stmt.setInt(1, 2000);
4 stmt.setString(2, "Joe Mays");
5 stmt.addBatch();
6 stmt.setInt(1, 3000);
7 stmt.setString(2, "Kara Stelter");
8 stmt.addBatch();
9 // submit the batch for execution
10 int[] updateCounts = stmt.executeBatch();
11 con.commit();
Finally, PreparedStatement.executeBatch is called to submit the
updates to the DBMS, then commit. Error handling in the case of
PreparedStatement objects is analogous to error handling for
Statement objects.
5-25
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5-26
5-27
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5-28
5
Advanced Data Types
Using SQL3 Data Types
Retrieve, store, and update SQL3 data types the same way you do
other data types. Use either ResultSet, getXXX, or
CallableStatement.getXXX methods to retrieve them,
PreparedStatement.setXXX methods to store them, and updateXXX
methods to update them. Approximately 90 percent of the operations
performed on SQL3 types involve using the getXXX, setXXX, and
updateXXX methods.
Table 5-4 shows which methods to use.
Table 5-4
SQL3 Type
getXXX
ResultSet
setXXX
CallableStatement
PreparedStatement
updateXXX
ResultSet
BLOB
getBlob
setBlob
updateBlob
CLOB
getClob
setClob
updateClob
ARRAY
getArray
setArray
updateArray
Structured type
getObject
setObject
updateObject
getRef
setRef
updateRef
Arrays
For example, the following code fragment retrieves a SQL ARRAY
value. For this example, the column SCORES in the table STUDENTS
contains values of type ARRAY. The variable stmt is a Statement
object.
1 ResultSet rs = stmt.executeQuery(
"SELECT scores FROM students WHERE id = 2238");
2 rs.next();
3 Array scores = rs.getArray("scores");
The variable scores is a logical pointer to the SQL ARRAY object stored
in the table students in the row for student 2238.
5-29
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Advanced Data Types
Using SQL3 Data Types
Arrays
The following example shows how to get an array of primitives.
1 import java.sql.*;
2
3 public class DBArray{
4
public static void main(String [] args){
5
try{
6
Class.forName("DriverClass");
7
Connection cnct = DriverManager.getConnection("ConnectInfo");
8
Statement stmt = cnct.createStatement();
9
// Create and execute the query
10
String dbQuery =
"SELECT scores FROM students WHERE id = 2238";
11
ResultSet rs = stmt.executeQuery(dbQuery);
12
// If you get a record back
13
if (rs.next()){
14
// Get array and store underlying Object reference.
15
// The object will be a type of array, but you must
16
// check for which type it is by using the instanceof
17
// keyword (unless you know the storage type in advance)
18
Array scores = rs.getArray("scores");
19
Object arrayVar = scores.getArray();
20
// If the object reference is an array of float,
21
// cast it and retrieve all of the values, printing
22
// the result.
23
if (arrayVar instanceof float []){
24
float [] scoreValues = (float [])arrayVar;
25
for (int i = 0; i < scoreValues.length; i++){
26
System.out.println(scoreValues[i]);
27
}
28
}
29
}
30
}
31
catch (Exception exc){}
32 }
33 }
5-30
5
Advanced Data Types
Using SQL3 Data Types
Clob
1 import java.sql.*;
2 import java.io.*;
3
4 public class ReadDBClob{
5
6
public static void main(String [] args){
7
8
try{
9
Class.forName("str");
10
Connection cnct = DriverManager.getConnection("str");
11
Statement stmt = cnct.createStatement();
12
// Create and execute the query
13
String dbQuery = "SELECT notes FROM support_rec WHERE
id = 2238";
14
ResultSet rs = stmt.executeQuery(dbQuery);
15
// If you get a record back
16
if (rs.next()){
17
// Get the CLOB and use it to construct a BufferedReader
18
// (so that you can get the CLOBs content. Clob
19
// is just a reference in Java; to use the underlying CLOB
20
// in the DB, you have to get an InputStream or Reader)
21
Clob sptNotes = rs.getClob("notes");
22
BufferedReader dbNote = new
BufferedReader(sptNotes.getCharacterStream());
23
String clobLine = dbNote.readLine();
24
// Echo the content to standard output
25
while (clobLine != null){
26
System.out.println(clobLine);
27
clobLine = dbNote.readLine();
28
}
29
}
30
}
31
catch (Exception exc){}
32 }
33 }
5-31
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5-32
5
Advanced Data Types
Blob, Clob, and Array Objects
For example, if you want to use a SQL ARRAY object in an application
as if it were an array in the Java programming language, you need to
materialize the ARRAY object on the client and then convert it to an
array in the Java programming language. Then you can use array
methods in the Java programming language to operate on the
elements of the array. The interfaces Blob, Clob, and Array all have
methods for materializing the objects they represent.
5-33
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5-34
5-35
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Advanced Data Types
Structured Types
Unlike Blob, Clob, and Array objects, a Struct object contains values
for each of the attributes in the SQL structured type and is not just a
logical pointer to the object in the database. For example, suppose that
a PLANE_POINT object is stored in column POINTS of table PRICES.
1 ResultSet rs = stmt.executeQuery(
"SELECT points FROM prices WHERE price > 3000.00");
2 while (rs.next()) {
3
Struct point = (Struct)rs.getObject("points");
4
// do something with point
5 }
If the PLANE_POINT object retrieved has an X value of 3 and a Y value
of -5, the Struct object point contains the values 3 and -5.
You might have noticed that Struct is the only type not to have a
getXXX and setXXX method with its name as XXX. You must use
getObject and setObject with Struct instances. This means that
when you retrieve a value using the method getObject, you get an
Object in the Java programming language that you must explicitly
cast to a Struct, as was done in the previous code example.
You can retrieve the internal values by calling the getAttributes
method.
5-36
5-37
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Advanced Data Types
Distinct Types
A SQL distinct type is mapped to the type in the Java programming
language to which its underlying type would be mapped. For
example, NUMERIC maps to java.math.BigDecimal, so the type MONEY
maps to java.math.BigDecimal. To retrieve a MONEY object, use
ResultSet.getBigDecimal or CallableStatement.getBigDecimal;
to store a MONEY object, use PreparedStatement.setBigDecimal.
5-38
5-39
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Exercise: JDBC 2.0 Core Features
Exercise objective Practice the concepts and tasks you have learned
in this module.
Tasks
Go to the SL330 directory on your computer and change to the lab files
directory. Open the directory for this module, then the directory for
this exercise, and read the readme file. Follow the instructions in that
file to complete this exercise.
If additional instructions or materials are required, your instructor will
provide them.
5-40
5
Exercise: JDBC 2.0 Core Features
Exercise Summary
Discussion Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
5-41
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
5-42
5
Think Beyond
An application must specify a JDBC URL when connecting to a
database using the driver manager. Would this be restricting at times?
What system could make it easier to change the URL?
5-43
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Objectives
Upon completion of this module, you should be able to:
Explain how to use row sets to encapsulate rows for use with the
JavaBeans component model
6-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
6
Relevance
Discussion So far, you have learned that you need to establish a
connection each time you want to connect to the database. What
advantages would there be in a system that provided an existing
supply of connections?
6-2
6
References
Additional resources The following resources can provide
additional detail on the topics presented in this module:
6-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Connection pooling
Distributed transactions
Row sets
6-4
JNDI
Overview
The Java Naming and Directory Interface (JNDI) is a standard
extension to the Java platform, providing Java technology-enabled
applications with a uniform way for applications to find and access
remote services over the network. This allows you to connect
seamlessly to multiple enterprise naming and directory interfaces. The
JDBC 2.0 API provides support for JNDI.
The remote services you access using JNDI can be any enterprise
service, including a messaging service or application-specific service.
6-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
JNDI
JNDI Advantages
As described in Module 1, JDBC Overview, an application can
connect to a database using the JDBC driver manager. In this
approach, the JDBC driver that is used to create a database connection
must first be registered with the JDBC driver manager.
For example, when the driver class includes an appropriate static
initializer, the following statement loads and registers the JDBC driver
implemented by the JDBCDriverClassName class.
Class.forName("JDBCDriverClassName");
However, the JDBC driver class name usually identifies a particular
JDBC driver vendor, which can make the code that loads the driver
specific to a particular vendors product and, therefore, non-portable.
In addition, an application must specify a JDBC URL when connecting
to a database using the driver manager:
Connection con = DriverManager.getConnection
("jdbc:vendorX_subprotocol:machineY:portZ");
6-6
6
JNDI
JNDI Advantages
This code demonstrates that a JDBC URL might be specific not only to
a particular vendors JDBC product, but also to a particular machine
name and port number on that machine. This can make the application
difficult to maintain because the computing environment changes.
Using JNDI with JDBC solves these problems by allowing an
application to specify a logical name that JNDI associates with a
particular data source. This makes deploying and maintaining JDBC
applications easier. The driver is specified using two separate
programs:
One program associates the driver with a data source name you
choose.
This makes changing the driver easier, because you need to change it
in only one place.
6-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
JNDI
JDBC DataSource
A JDBC DataSource object is a Java programming language instance
of the javax.sql.DataSource interface. A data source object is a
factory for JDBC connections.
1
2
3
4
5
6
6-8
6
JNDI
JDBC DataSource
A class that implements the DataSource interface provides a set of
properties that must be given values so that a connection to a
particular data source can be made. These properties, which follow the
design pattern specified for JavaBeans model components, are usually
set when a data source object is used. Examples of data source
properties include the location of the database server, the name of the
database, the network protocol to use to communicate with the server,
and so on.
The JDBC 2.0 API specifies the following standard names for data
source properties:
Table 6-1
Property Name
Type
Description
databaseName
String
dataSourceName
String
description
String
networkProtocol
String
password
String
A database password
portNumber
int
roleName
String
serverName
String
user
String
6-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
JNDI
JDBC DataSource
A data source must support the description property. Support for the
other properties listed is not required because they might not be
needed by all data sources. However, if a data source needs to use one
of the properties listed in Table 6-1, it must use the standard property
name.
The standard properties are included in the JDBC specification to
encourage uniformity among data sources from different vendors. For
example, this standardization allows you to write a utility that lists
available data sources and their descriptions along with other
information if it is available.
6-10
6
JNDI
JDBC DataSource
For each property, you must be able to write to it and read it using
accessor and mutator methods.
For example, if sds denotes a data source object that supports the
serverName property, the following methods must be provided.
sds.setServerName("my_database_server");
String prop = sds.getServerName();
See the JavaBeans API specification for a full description of properties
and their accessor methods.
The accessor and mutator methods for a property are defined on the
implementation class and not in the DataSource interface. This creates
some separation between the management API for DataSource objects
and the API used by applications. Applications should not need to
access or change properties, but management tools can access them
using introspection.
A data source can contain a property that is not included on the list of
standard properties in Table 6-1. In this case, use a vendor-specific
name for the property.
The JDBC 2.0 API specifies a simple policy for assigning JNDI names
to data sources. All JDBC data sources should be registered in the jdbc
naming subcontext of a JNDI namespace, or in one of its child
subcontexts. The JDBC subcontext is the child of the root naming
context.
You can use JNDI to complete the first and second steps of the JDBC
process: registering the driver and connecting to the database.
6-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
JNDI
Registering a DataSource Object
To register the driver, you associate it with the DataSource object.
You can create, deploy, and manage a DataSource object within JNDI
separately from the Java applications that use it. This section describes
the use of DataSource objects.
Syntax
6-12
6
JNDI
Registering a DataSource Object
Example
This example registers a data source object with a JNDI naming
service.
1
2
3
4
5
6-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
JNDI
Establishing a Connection Using JNDI
Once you have registered a data source with JNDI, a JDBC application
can use it.
Syntax
Context contextRefVar = new InitialContext();
DataSource dataSrcRefVar = (DataSource)contextRefVar.lookup
(logicalDataSrc);
Connection conRefVar = dataSrcRefVar.getConnection
("userID", "password");
Example
1 Context ctx = new InitialContext();
2 DataSource ds = (DataSource)ctx.lookup("jdbc/AccountMain");
3 Connection con = ds.getConnection("marcl", "mpuppet");
6-14
6
JNDI
Establishing a Connection Using JNDI
The first line in the example creates a Java object that references the
initial JNDI naming context. Next, the initial naming context does a
lookup operation using the logical name of the data source. The
Context.lookup method returns a reference to a Java object, which is
narrowed to a javax.sql.DataSource object. In the last line, the
DataSource.getConnection method is called to produce a database
connection.
Note The DataSource feature provides an alternative to the JDBC
DriverManager, essentially duplicating all of the driver manager's
useful functionality. Although the same application can use both
mechanisms, it is a good idea to regard the DriverManager as a legacy
feature of the JDBC API. Applications should use the JNDI
DataSource API whenever possible. A JDBC implementation that is
accessed using the DataSource API should not automatically register
itself with the DriverManager.
6-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Connection Pooling
Note For an example of using connection pooling, refer to Appendix
B of the JDBC 2.0 Standard Extension API, included in the lab files for
this course.
Overview
A connection pool is a cache of database connections that is
maintained in memory, so that the connections can be reused.
Connection pooling can increase performance, especially when the
JDBC API is used in a middle-tier server environment, such as a Web
server capable of running Java applications.
The application does not register drivers; middle-tier code does the
registration. Connection pooling can simplify client code because
clients no longer have to deal with registering a driver.
You can use connection pooling to complete step 2 of the JDBC
process, establishing a connection.
6-16
6
Connection Pooling
Overview
Connection pooling has no impact on the code that you write. You
simply take advantage of a connection pool that has been
implemented in the driver, rather than writing code yourself.
Figure 6-1 provides an example of the basic components that might
compose a distributed, three-tier application that uses the JDBC 2.0
APIs connection-pooling feature.
Network
Application code
Client
(browser)
DataSource
Middle-tier server code
ConnectionPoolDataSource
JDBC driver
Tier 1
Tier 2
Figure 6-1
Network
DBMS
Tier 3
6-17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Connection Pooling
Overview
To support connection pooling, a JDBC driver vendor must provide an
implementation of the javax.sql.ConnectionPoolDataSource
interface. This interface and the closely related
javax.sql.PooledConnection interface (not shown in Figure 6-1)
provide methodsor hooksthat enable a third party, such as a
middle-tier server vendor to implement connection pooling as a layer
on top of the JDBC API.
The JDBC 2.0 API provides hooks to support connection pooling
instead of mandating a particular connection pooling implementation,
because there are many possible connection pooling algorithms that
JDBC users might use. Of course, JDBC driver vendors can also
provide connection pooling implementations.
6-18
6
Connection Pooling
Connecting
A party, such as a middle-tier server vendor, who wants to implement
connection pooling should provide a data source class (a class that
implements the javax.sql.DataSource interface) to interact with
their particular connection pooling implementation. Application code
that you write can retrieve instances of this data source class from
JNDI and use it to obtain a database connection in the usual manner.
If you use connection pooling, the client does not have to register the
driver.
The following syntax and example show how to establish a
connection.
Syntax
Connection conRefVar = dataSrcRefVar.getConnection
(logicalDataSrc, "userID", "password");
// Do all the work as a single transaction (optional).
conRefVar.setAutoCommit(false);
// Work is done using standard JDBC code as defined in the
// rest of the JDBC API.
conRefVar.commit();
// Close the connection. This returns the underlying physical
// database connection to the pool.
conRefVar.close();
Example
1 Connection con = ds.getConnection("jdbc/webDatabase", "marcl",
"mpuppet");
2 con.setAutoCommit(false);
// The actual work (queries and updates) would go here.
3 con.commit();
4 con.close();
6-19
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Distributed Transactions
Overview
A distributed transaction is two or more tasks, on different entities (a
database, or other entity), that need to be committed as one
transaction. For example, moving money from an account in one bank
to an account in another is a distributed transaction.
Support for distributed transactions allows a JDBC driver to support
the standard two-phase commit protocol used by the Java Transaction
API (JTA). JDBC driver support for distributed transactions allows you
to write Enterprise JavaBeans that are transactional across multiple
DBMS servers.
6-20
6
Distributed Transactions
Architecture
Figure 6-2 shows a simplified example of the basic components in a
distributed, three-tier application that uses the distributed transaction
features in the JDBC 2.0 API.
Network
Client
(browser)
Application code
DataSource
Transaction manager
Tier 1
Tier 2
Figure 6-2
Network
DBMS
Tier 3
6-21
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Distributed Transactions
Architecture
On the client, a browser invokes a piece of application code that
executes in a middle-tier server environment. The middle-tier server
could be a Web server supporting Java technology, an Enterprise
JavaBeans server, or some other type of application server that
supports the Java programming language. The middle-tier application
code uses the JDBC API to access a pair of databases in the context of
a global (distributed) transaction.
Using distributed transactions does not significantly affect the code
that you write. The application code uses the DataSource interface in
the standard way to obtain a Connection object. The DataSource
implementation, which the middle-tier server vendor provides,
interacts with the transaction manager to set up the transactional
environment for the Connection returned to the application, and
typically maintains a pool of database connections to achieve
maximum performance. The DataSource implementation uses the
features provided by the JDBC 2.0 driver vendor to implement
connection pooling and to enable distributed transactions.
6-22
Distributed Transactions
Implementation
To support distributed transactions, a JDBC driver vendor must
provide implementations of the javax.sql.XADataSource and
javax.sql.XAConnection interfaces. These interfaces are similar to
the ConnectionPoolDataSource and PooledConnection interfaces.
They provide the same hooks to enable connection pooling, and add
the ability to do distributed transactions.
A middle-tier server vendor who wants to support distributed
transactions should provide a data source classan implementation of
the javax.sql.DataSource interfacethat interacts with the middletier servers transaction infrastructure.
The transaction infrastructure includes a transaction manager, such as
an implementation of the Java Transaction Service API, and a JDBC
driver that supports the JDBC 2.0 API. You can retrieve instances of
this data source class from JNDI using application code executing in
the middle tier that obtains a database connection in the usual manner.
6-23
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Distributed Transactions
Implementation
Note Distributed transactions do not impact application code
significantly. However, there are coding differences of which you
should be aware. There are differences because the JDBC API assumes
that distributed transaction boundaries are controlled by either the
middle-tier server or another API, such as the user transaction portion
of the Java Transaction API.
Distributed transactions are intended to be used by component-based
transactional applications that operate in a modern application server
environment, such as an Enterprise JavaBeans server, in which
declarative transactions are used.
6-24
6
Distributed Transactions
Implementation
Transaction boundaries are controlled by the middle-tier server, so the
application code must not call the Connection.commit or
Connection.rollback methods. These methods throw a
SQLException if they are called.
In addition, the Connection object that is returned by a DataSource
when distributed transactions are being done has autocommit mode
turned off by default. If you attempt to enable autocommit mode by
calling Connection.setAutoCommit with a value of true, a
SQLException is thrown.
6-25
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Row Sets
Overview
A RowSet object encapsulates a set of rows that have been retrieved
from some tabular data source, such as results of a database query,
This makes it easy to send tabular data over a network. A RowSet
object must implement the javax.sql.RowSet interface, which adds
support to the JDBC API for the JavaBeans component model. The
RowSet interface inherits from the ResultSet interface.
The RowSet object provides a way to represent the rows so that they
can be used with the JavaBeans component model; a RowSet object is a
JavaBean that can be combined with other components in an
application. You can create row sets at design time and use them in
conjunction with other JavaBeans components in a visual JavaBeans
builder tool to construct an application
You also can use RowSet objects to provide scrollable result sets or
updatable result sets when the underlying JDBC driver does not
support them.
6-26
6
Row Sets
Overview
You can serialize a row set implementation.
A row set might maintain an open database connection. When a row
set is disconnected from its data source, updates performed on the row
set are propagated to the underlying database using an optimistic
concurrency control algorithm.
Unlike statements and result sets, row sets are not tied to a specific
connection. A row set is affiliated with a connection only for the
duration of its use with a particular query.
6-27
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Row Sets
Types of Row Set Implementations
Row sets can have many different implementations to fill different
needs. There are two categories: row sets that are connected and those
that are disconnected.
6-28
6
Row Sets
Types of Row Set Implementations
Disconnected Row Sets
Because it is not continually connected to its data source, a
disconnected row set stores its data in memory. It needs to maintain
metadata about the columns it contains and information about its
internal state. It also needs a way to make connections, for executing
commands, and for reading and writing data to and from the data
source.
6-29
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Row Sets
Row Sets at Design Time
Properties
The RowSet interface provides a set of JavaBeans properties that allow
you to configure a RowSet instance to connect to a data source and
retrieve a set of rows, as shown in the following example.
1
2
3
4
6-30
6
Row Sets
Row Sets at Design Time
Properties
The DataSource object is used internally to create a connection to the
underlying data source. The transaction isolation property specifies
that only data that was produced by committed transactions can be
read by the row set. Lastly, the command property specifies a
command that is executed to retrieve a set of rows. In this case the
NAME, BREED, and AGE columns for all rows in the CANINE table
are retrieved.
6-31
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Row Sets
Row Sets at Design Time
Events
RowSet components support JavaBeans events, which allows other
JavaBeans components in an application to be notified when an
important event on a row set occurs. A component that wishes to
register for RowSet events must implement the RowSetListener
interface. Event listeners are registered with a row set by calling the
addRowSetListener method, as shown in the following example. Any
number of listeners can be registered with an individual RowSet
object.
RowSetListener listener ...;
rset.addRowSetListener(listener);
6-32
6
Row Sets
Row Sets at Design Time
Events
Row sets can generate three different types of events.
Cursor movement events indicate that the row sets cursor has
moved.
Row set change events indicate that the entire contents of a row set
changed. For example, this can happen when RowSet.execute is
called.
6-33
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
6
Row Sets
Row Sets at Design Time
Events
When an event occurs, an appropriate listener method is called to
notify a listener. If a listener is not interested in a particular event type,
it can implement an event-handling method with an empty method
body. An event listener is passed a RowSetEvent object, which
identifies the source of the event when an event occurs.
6-34
Row Sets
Row Sets at Runtime
Parameters
You can use the row set to execute queries, and pass values.
In the RowSet interface example shown previously, a simple SQL
command that takes no input parameters was used. However, a row
set can also use a command that accepts input parameters. A group of
setXXX methods provide a way to pass input parameters to a row set.
The following example shows a command that takes a String input
parameter. The RowSet.setString method is used to pass the input
parameter value to the RowSet. Typically, the command property is
specified at design time, while parameters are not set until runtime
when their values are known.
rset.setCommand("SELECT NAME, BREED, AGE FROM CANINE WHERE NAME = ?");
rset.setString(1, "spot");
6-35
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Row Sets
Row Sets at Runtime
Traversing a Row Set
The javax.sql.RowSet interface extends the java.sql.ResultSet
interface, so in many ways a row set behaves just like a result set. In
fact, most components that make use of a RowSet component will
likely treat it as a ResultSet object. A RowSet is simply a ResultSet
that can function as a JavaBeans component.
The following example shows how to iterate forward through a row
set; it is the same process that would be used for a result set.
1
2
3
4
5
6-36
Row Sets
Row Sets at Runtime
Command Execution
You can fill a row set with data by calling the RowSet.execute
method. This method uses the appropriate property values that have
been set to connect to a data source, and retrieve data. The exact
properties that you must set can vary between RowSet
implementations. Check the documentation for the particular row set
being used to find out what properties are required.
The RowSet interface contains the properties that are needed to
connect to a JDBC data source.
The current contents of the row set, if any, are lost when an execute
method is called.
6-37
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
6-38
6
Overview of Row Set Implementation
6-39
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
6
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
6-40
Explain how to use row sets to encapsulate rows for use with the
JavaBeans component model
6
Think Beyond
What elements might be necessary in an implementation of the
CachedRowSet class?
6-41
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Objectives
Upon completion of this module, you should be able to:
7-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7
Relevance
Discussion How would you modify your application to retrieve data
from a different source of data, such as a spreadsheet?
7-2
7-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7
CachedRowSet Class Overview
Using a CachedRowSet enables the following capabilities.
Java client
Tier 1
RMI/CORBA
CachedRowSet
Tier 2
JDBC
DBMS
Figure 7-1
7-4
Tier 3
CachedRowSet Architecture
7
CachedRowSet Class Overview
7-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Creating a CachedRowSet
A CachedRowSet is a JavaBean, so CachedRowSet instances are often
created by a visual Beans development tool when an application is
assembled. Applications can also create instances at runtime using any
public constructor that the CachedRowSet class provides.
7-6
Retrieving Data
A CachedRowSet object can contain data retrieved using a JDBC driver
or data from some other source, such as a file. CachedRowSet objects
usually contain data that was fetched from a SQL database using
JDBC. One way to get data into a CachedRowSet is to call the
CachedRowSet.populate method (defined on the CachedRowSet
class), as shown in the following example.
1 ResultSet rs = stmt.executeQuery
("SELECT NAME, SALARY FROM EMPLOYEE");
2 CachedRowSet crset = new CachedRowSet();
3 crset.populate(rs);
7-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7
Retrieving Data
The example uses a variable stmt of type Statement. The populate
method takes a parameter that is a ResultSet containing some data.
The populate method reads the contents of the ResultSet, and
caches the contents in the CachedRowSet object.
You can use the term disconnected to describe a CachedRowSet.
Disconnected means that a CachedRowSet object caches its data
outside of a data source. Once the populate method returns, the
CachedRowSet object does not maintain a connection to the
underlying data source that produced the initial ResultSet. The
populate method does not require that any properties be set ahead of
time to enable data source connectivity.
7-8
Retrieving Data
Another way to get data into a CachedRowSet object is to call the
execute method. There are two forms of execute: one method takes a
Connection object as a parameter and the other that does not.
If a Connection is passed to execute, then there is no need to set
properties ahead of time to enable data source connectivity. However,
execute always requires that a command be specified using the
command property. The CachedRowSet only makes use of the JDBC
connection briefly while data is being read from the database and used
to populate it with rows. To use the execute method, you should call
it once you have set the appropriate properties.
1
2
3
4
7-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7
Retrieving Data
In this case, because a Connection is not passed to the execute
method, the CachedRowSet must create a Connection internally and
use it to retrieve a set of rows. (This approach is based on the
assumption that a JDBC data source is being accessed.)
7-10
Accessing Data
The contents of a CachedRowSet are accessed using methods inherited
from the ResultSet interface. A CachedRowSet is always scrollable,
and its type is ResultSet.
7-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Modifying Data
A CachedRowSet object keeps track of both its original value and its
current value. The original value is set by methods
CachedRowSet.execute and populate. For example, when execute
is called, the original value is typically assigned the set of rows
returned by executing the row sets command. After calling execute
(or populate) the original value and the current value are the same.
The CachedRowSet.updateXXX methods (which are inherited from
ResultSet) can be called to update the current value of a
CachedRowSet. Calling an updateXXX method does not affect the
original value, or the values stored in the underlying data source. Only
the current value of the CachedRowSet, which is cached in memory, is
changed.
7-12
7
Modifying Data
The following example illustrates these concepts.
When CachedRowSet.execute is called in the first line of the
example, the original and current values of the CachedRowSet, which
are maintained in main memory, are initialized. The cursor is then
positioned at the first and second rows, in turn, and the updateString
and updateFloat methods are called to modify the current value of
the first two rows in the row set, which contain an employee name and
salary.
Call the updateRow method to signal the completion of each row
update. Once updateRow is called, cancelRowUpdates can no longer
be called to undo updates to the current value of the row.
UpdateRow does not affect the original value of the row or the
underlying values in the data source. Deleting and inserting rows is
done exactly as for ResultSets, so this is not shown in the example.
1 // initialize the original and current values
2 crset.execute();
3 // update the current value of the first row
4 crset.first();
5 crset.updateString(1, "Joe Mays");
6 crset.updateFloat(2, 50000f);
7 crset.updateRow();
8 // update the current value of the sixth row
9 crset.relative(5);
10 crset.updateString(1, "Kara Stelter");
11 crset.updateFloat(2, 38000f);
12 crset.updateRow();
13 // update the original value and the database
14 crset.acceptChanges();
After making some changes, you can call acceptChanges to propagate
any updates, inserts, and deletes back to the underlying data source.
The acceptChanges method invokes a writer component internally to
actually update the data source. Typically, a writer compares the
original value of each updated row with the values stored in the
database to be sure that the underlying data has not been changed by
someone else. If nothing has been changed, the row sets updates are
written to the database. The original value is set to the current value
before acceptChanges returns.
7-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7
Modifying Data
Alternatively, an application can call the method restoreOriginal if
it discards the updates that it has made on a CachedRowSet. Calling
restoreOriginal simply replaces the current value of the row set
with the original valuethere is no interaction with the underlying
data source.
7-14
Miscellaneous Methods
The CachedRowSet.clone and CachedRowSet.createCopy methods
both create an exact copy of a row set that is independent from the
original.
In contrast the CachedRowSet.createShared method creates a row
set that shares its state with the original row set; that is, both the new
and the original row set share the same physical, in-memory copy of
their original and current values. Updates made by calling an
updateXXX method on one shared row set are reflected in the other.
The createShared method, in effect, allows an application to create
multiple cursors over a single set of rows.
CachedRowSets also provide methods for easy conversion to a Java
technology collection. The crs.toCollection method allows a
java.util.Connection object to be created from a CachedRowSet.
7-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7-16
7-17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7
Reading and Writing Data
Overview
Similarly, when the CachedRowSet.acceptChanges method is called,
the CachedRowSet invokes an object that implements the
RowSetWriter interface internally to handle the task of writing
changed rows back to the data source. The RowSetWriter.writeData
method is invoked by the row set to write any data that has been
changed. This method might detect a conflict with the underlying data
and signal this by returning a value of true to the caller.
To register readers and writers with a CachedRowSet object, call the
methods CachedRowSet.setReader and CachedRowSet.setWriter.
A CachedRowSet style implementation should also provide
corresponding accessor methods.
The RowSetReader, RowSetWriter, and RowSetInternal interfaces
are used by the row set implementation classes.
7-18
7
Reading and Writing Data
Overview
Figure 7-2 outlines how readers and writers interact with a data source
and the CachedRowSet.
CachedRowSet
data in
data out
RowSetReader
RowSetWriter
Data source*
7-19
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7-20
7
Reading and Writing Data
RowSetReader
The example is designed to be used with the CachedRowSet row set
implementation. You use the CachedRowSet.populate method to
read the rows from a ResultSet object into the row set. The example
assumes the caller is of type CachedRowSet. A SQLException is
thrown if anything goes wrong.
An alternative reader implementation could read data directly from a
regular file. In this way, you can use a row set to provide access to
non-SQL data. A reader of this type can use the RowSet.insertRow
method to insert new rows into the row set. InsertRow updates the
original value of the row set when invoked by a reader. The
RowSetMeta interface can also be used by such a reader to
communicate the format of the data being read to the row set
implementation.
7-21
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7-22
7
Exercise: Row Set Implementations
Exercise objective Practice the concepts and tasks you have learned
in this module.
Tasks
Go to the SL330 directory on your computer and change to the lab files
directory. Open the directory for this module, then the directory for
this exercise, and read the readme file. Follow the instructions in that
file to complete this exercise.
If additional instructions or materials are required, your instructor will
provide them.
7-23
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7
Exercise: Row Set Implementations
Exercise Summary
Discussion Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
7-24
Experiences
Interpretations
Conclusions
Applications
7
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
7-25
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7
Think Beyond
What considerations should you take into account when designing the
architecture of your Java application?
7-26
Objectives
Upon completion of this module, you should be able to:
8-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
8
Relevance
Discussion N-tier architectures allow better flexibility and
maintenance of a software subsystem. The most common is the threetier architecture. How do the components of a three-tier system
interact with each other?
What is the deciding factor for these divisions?
8-2
8
References
Additional resources The following reference can provide additional
details on the topics discussed in this module:
8-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
8-4
8
Tiered Application Architecture Overview
In addition, as shown in Figure 8-1, you can use tiers as a way to
coordinate the efforts of multiple clients.
Client
Middle
tier
Client
DBMS
Client
Figure 8-1
8-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
8-6
Data This component stores and allows access to the data, and is
typically in the third tier, the server.
Two-Tier Architecture
In the two-tier architecture, the application front end is in the first tier.
The database is in the second tier, the server tier. The Java application
or applet functioning as the presentation communicates directly with
the database. A users actions are translated in JDBC-based SQL
commands and are delivered to the database. The results of those
statements are sent back to the user.
You can store the database on another machine to which the user is
connected using a network. The network can be an intranet or the
Internet. This architecture enables the data to reside locally or
remotely.
If other users need a different presentation to the same data, you need
to develop only a new interface on the front end.
8-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
8
Two-Tier Architecture
Figure 8-2 shows a two-tier application design.
Client machine
Presentation
component
Business logic
component*
Applet or
application
JDBC driver
DBMS
protocol
Database
server machine
Data
component
DBMS
Note In the examples shown in this course, tiers are often shown on
separate machines; however, you can store tiers on the same machine.
You can support caching results of database queries by introducing the
caching functionality into the front-end presentation on the client
machine, or into the database on the server machine.
The first tier is responsible for making connections to any additional
database servers.
8-8
Three-Tier Architecture
In a three-tier architecture, the first tier (client) sends commands to a
middle tier, which then sends SQL statements to the database on the
third tier (server). The database processes the SQL statements and
sends the results back to the middle tier, which then sends them to the
user.
This middle tier enables you to develop the following functionality
separately: secure socket classes, cache data, or business rules. Java
applications in the middle tier usually interact with the database with
JDBC, and with the client using one of the following mechanisms.
8-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Three-Tier Architecture
Having the business rules enforcement component in a separate tier,
between the client and database, has the following advantages:
8-10
8
Three-Tier Architecture
A well-implemented three-tier architecture makes changing any aspect
of the application easier, because the different components are
separated logically. For example, information systems departments,
using a three-tier model, can maintain control over access and updates
to corporate data by controlling the middle tier. In many cases, the
three-tier architecture also can provide performance advantages.
8-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
8
Three-Tier Architecture
You can implement all data validation, including business rules, in the
middle tier. The middle tier also can take over responsibility for
making connections to additional database servers.
Figure 8-3 shows a three-tier application design.
Client machine
Presentation
component
Java applet or
HTML browser
RMI/CORBA,
HTTP
Server machine
Business logic
component
Application server
(Java technology)
JDBC driver
DBMS
protocol
Database
server machine
Figure 8-3
Data
component
DBMS
For greater security, do not include SQL and the business logic on the
client.
8-12
N-Tier Architecture
N-tier architectures extend the two-tier and three-tier architectures by
further breaking out functional modules into tiers.
You can create an n-tier architecture by partitioning the application
vertically or horizontally.
8-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
8
N-Tier Architecture
For example, a three-tier application that needs to support a
greatly increased number of end users could manage the increased
work load by adding a local or regional cache tier to provide a
store of objects, and reduce the number of transactions that users
had to perform directly on the database. This is shown in
Figure 8-4.
First tier
Client
Caching control
Second tier
Application server
Third tier
DBMS
Figure 8-4
8-14
8
N-Tier Architecture
First tier
Client
Second tier
Application server
Print server
Third tier
DBMS
Figure 8-5
8-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Choosing an Architecture
The JDBC API does not enforce a particular application architecture.
You can use a two-tier, three-tier, or n-tier architecture, depending on
the application and other considerations. Use this section to learn how
to determine how to choose the architecture that works best for your
requirements.
Two-Tier Architecture
Two-tier architecture is simple, straightforward, and typically suitable
for small applications. It is easier to implement if development
resources are significantly limited.
A limitation of the two-tier model is that the GUI and application logic
are tightly coupled, so the client program is responsible for all error
checking and all data is exposed on the network, which is not secure.
In addition, if database table schema changes on the server, you must
restructure the client code.
8-16
8
Choosing an Architecture
Two-Tier Architecture
Installing drivers requires more work.
For two-tier solutions, this means that you must install drivers on
every client machine, which is a potentially time-consuming task
for systems with many clients.
You can store business logic on either tier; however, when storing the
business logic on the server in the form of stored procedures, you lose
the platform- and DBMS-independence of JDBC.
8-17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Choosing an Architecture
Three-Tier and N-Tier Architecture
Three-tier and n-tier architectures resolve many of the issues that a
two-tier architecture addresses without the associated limitations.
The client might be much thinner than on the two-tier model and
consists essentially of the presentation, as well as control logic and
code that communicates with the middle tier. This might allow you to
use less powerful client machines. It also makes it easier to support
client machines of multiple platforms, because there is less code on
each.
You can customize the middle tier to your applications requirements.
Enforcing the business rules in the middle tier, between the client and
database, enables you to create the rules once and keep them in a
single, easily maintained location.
8-18
8
Choosing an Architecture
Three-Tier and N-Tier Architecture
The three-tier and n-tier architecture models are more scalable. If
support for additional clients is required, such architectures are
typically flexible enough to accommodate added middle-tier or
database systems to handle the increased load.
The disadvantage of using a three-tier or n-tier architecture is that it
increases the number of possible failure points. A two-tier architecture
has only three possible failure points: client, network, and server. A
three-tier architecture has five: client, network, application server,
network, and database server.
Overall application complexity is increased, though each tier is
simplified.
Despite these disadvantages, the three-tier or n-tier model is the
preferred architecture for database applications. The added level of
abstraction eases development and maintenance of the whole
application. Furthermore, it is easier to integrate several databases or
even legacy systems in an application.
8-19
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
8
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
8-20
8
Think Beyond
Based on this course, can you begin implementing JDBC in your
work? What other information would be useful to help you get
started?
8-21
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Database Basics
Objectives
Upon completion of this appendix, you should be able to:
A-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
A
References
Additional resources The following reference can provide additional
details on the topics discussed in this appendix:
A-2
Melton, Jim, Alan Simpson. 1993. Understanding the New SQL. San
Francisco: Morgan Kauffman Publishers.
A
Database Overview
A database is a shared collection of logically related data and a
description of the data that has been developed to meet the
information requirements of an organization.
A database management system, or DBMS, is normally used to
maintain a database. A DBMS is a software system specially designed
to provide certain standard databases services.
The data must have a format that the DBMS and computer system
understands.
Database Basics
A-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
A
Database Overview
An RDBMS is a database management system that conforms to a set of
rules, including the following.
A-4
A
Relational Database Structure
In relational databases, data is represented in tables. A table is made
up of columns and rows.
Each database column (also called a field) provides information about
a particular element to be stored in the database. This information
includes its name, data type and any special characteristics it
possesses.
A database row (also called a record) contains the values for a specific
set of data stored in the database.
Table A-1 shows an example table named Customers with six columns
and three rows.
Customer
Name
Address
City
State
PostalCode
C4201
Kara Stelter
410 E Colfax
Denver
CO
80021
C7023
Sonja Wang
115 Ludlow
Fargo
ND
58047
C9900
Mike Slade
Montclair
NJ
10029
Database Basics
A-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
A
Data Independence
A relational database allows data to be managed independently from
the way in which it is stored.
The physical model of data storage for a relational database can be
determined by the RDBMS. From the users perspective, it is not
important to know how data is stored for the system. The user works
with a logical model of the data (tables, rows, and columns) that
represents the users window on the stored data.
A-6
A
Transactions
In database manipulation, a transaction is a logical group of work
consisting of one or more instructions. For example, the instructions
might be to enter a customer record, create a new order record, add a
line item to an order, and so on. For a transaction to execute
successfully, all of its instructions must be successfully executed for the
database. If there is an error any time during transaction execution, the
previous operations must be reversed. This is referred to as backing
out or performing a rollback on a transaction. Use transactions to
partition work to minimize the chances of data corruption.
A transaction starts with a begin work command, and contains all
database data manipulation information; the transaction either is
completed successfully with a commit work command or fails with a
rollback. The begin work command tells the database to start logging
all database data manipulation actions. The commit work command
tells the database that the transaction has completed successfully and
to stop logging. The rollback command tells the database to stop
logging and to reverse any data manipulation that had occurred.
The business rules of your application have a major impact on how
you should partition tasks into transactions. If your application
requires that users enter a certain set of valid information before they
enter associated information, the first set should be a transaction.
Partitioning transactions is an art, not a science. There are advantages
and disadvantages to most of the ways you partition tasks into
transactions; it depends on the types of risks and advantages and
disadvantages you prefer.
Using an order entry system as a example, assume a new customer has
just accessed your Web site and wants to enter a new order. How
would you partition the entry of the information to limit the
customers chances of lost data entry from an error?
Ask the following questions in this situation, to determine how to
partition the information:
Database Basics
A-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
A
Transactions
Discussion One way to partition this example would be to have all
work done by the customer as one transaction. What problems might
this cause?
Another way to partition this example is to have the customer
information as one transaction, the order as another transaction, and
the payment as another. What problems might this cause?
A-8
A
Transactions
Figure A-1 shows a Customer table, followed by a begin work
command and various inserts, updates, and deletes, followed by a
commit work and the effect on the Customer table.
Customer table, before:
CustID
Name
Addr
City
State PostalCode
C303
Joe Mays
408 E Sperling
Fargo
ND
58012
C272
Eliza Durham
PO Box 907
Juneau
AK
99821
C7640
CO
80022
C7842
Bran Andrews
NJ
10022
Netcong
BEGIN WORK
INSERT into CUSTOMER ("C8007", "Michael Wang","PO Box 42","Willmar", "MN", "56273"
INSERT into CUSTOMER ("C8014", "Agata Omole","99 W Slade","Kalispell", "MT", "59901"
UPDATE CUSTOMER set Addr = "PO Box 709" where CustID = "C272"
DELETE from CUSTOMER where CustID = "C8007"
COMMIT WORK
Name
Addr
City
State PostalCode
C303
Joe Mays
408 E Sperling
Fargo
ND
58012
C272
Eliza Durham
PO Box 709
Juneau
AK
99821
C7640
Denver
CO
80022
C7842
C8014
Bran Andrews
Agata Omole
Netcong
NJ
10022
99 W Slade
Kalispell
MT
59901
Figure A-1
Database Basics
A-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
A
Transactions
Figure A-2 shows how, if one part of a transaction fails, the entire
transaction is reversed, or rolled back. The same beginning Customer
table is used.
Customer table, before:
CustID
Name
Addr
City
State PostalCode
C303
Joe Mays
408 E Sperling
Fargo
ND
58012
C272
Eliza Durham
PO Box 907
Juneau
AK
99821
C7640
CO
80022
C7842
Bran Andrews
NJ
10022
Netcong
BEGIN WORK
INSERT into CUSTOMER ("C8007", "Michael Wang","PO Box 42","Willmar", "MN", "56273"
INSERT into CUSTOMER ("C8014", "Agata Omole","99 W Slade","Kalispell", "MT", "59901"
UPDATE CUSTOMER set Addr = "PO Box 709" where CustID = "C272"
DELETE from CUSTOMER where CustID = "C8007"
DELETE FAILS
ROLLBACK
Customer table, after (no change):
CustID
Name
Addr
City
State PostalCode
C303
Joe Mays
408 E Sperling
Fargo
ND
58012
C272
Eliza Durham
PO Box 907
Juneau
AK
99821
C7640
Denver
CO
80022
C7842
Bran Andrews
Netcong
NJ
10022
Figure A-2
A-10
A
Locking
Locking the database is necessary to allow only one person access to a
particular column or row at a time. The idea of allowing multiple
users access to the same row in a database is called concurrency.
Relational databases use two basic row locking strategies, pessimistic
and optimistic, to deal with concurrency.
Pessimistic locking locks a row for the entire time the row is in
memory. This concurrency approach ensures that the row cannot be
updated by someone else at the same time you are updating. In
essence, there is no concurrency, because you are given exclusive
control of updating the row.
Pessimistic locking is best for batch processing, when multiple tables
are being updated and must be consistent. Batch processing is
common in accounting applications.
Optimistic locking locks a row only for the time that it is being
accessed in the database. When you read the row from the database, it
is locked during the read but released as soon as it is in memory. The
row is then locked again when you perform your update or delete.
This approach allows multiple people to work with the same row
simultaneously, but can cause people to overwrite each others
updates. Consider the following example.
Next, User A unmarks the checkbox so that it is set to no, and the
database row is updated.
At the same time User B is updating different fields and leaves the
Preferred Customer checkbox as yes.
When User B saves the changes and updates the row, it overwrites
the update from User A and sets the Preferred Customer checkbox
back to yes.
Database Basics
A-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
A
Locking
To resolve this shortcoming in the optimistic locking strategy, you
could use a timestamp on each row, which is updated with each
update.
Before updating the row, reread the row and compare the
timestamp to the one in memory for that row.
At that point, you can include programming that will warn the user
that the record has changed since he or she first accessed it, and ask
Do you want to see the changes? or Do you want to make your
changes? Depending on the response, you would refresh the data or
perform your update.
Optimistic locking is best for online processing, such as updating a
master record for a customer.
A-12
A
SQL Basics
Overview
Review the following if you are not familiar with SQL syntax.
The SQL standard specifies a set of commands and a specific syntax
for the retrieval and modification of data, as well as commands for the
administration of tables. Each SQL statement is issued to the database
system and parsed.
There are five main categories of SQL; most statements fall into the
second category, Data Manipulation Language (DML):
You can read the syntax of SQL clauses like English commands. For
example, a SQL command could be to get me all of the fields in the
table named Employee Data, where the employee ID is 10223. If the
Employee Data table contained fields that held a name, employee ID,
date of hire, social security number, and current salary, you would
expect to receive a single employee record with these values.
Database Basics
A-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
A
SQL Basics
Overview
This command is written using the following statement syntax:
SELECT * FROM employee_data WHERE employee_id = '10223'
Note The employee_id field is presented here as a string, but if it
were an integer or a real number, you would not need the single
quotes.
SQL statements are not case sensitive, but the examples shown
highlight the keywords with capital letters.
SELECT Statement
Overview
The SELECT statement is the primary command used for data retrieval
from a SQL database. It supports the following:
A-14
Joins
ORDER BY clauses
A
SQL Basics
SELECT Statement
Syntax
The formal syntax for SQL the SELECT is:
SELECT [table.]column [ , [table.]column ]...
FROM table [ , table]...
[ WHERE [table.]column OPERATOR VALUE
[ AND | OR [table.]column OPERATOR VALUE]... ]
[ ORDER BY [table.]column [DESC] [, [table.]column [DESC] ]
OPERATOR can be <, >, =, <=, >=, <>, or LIKE.
VALUE can be a literal value or a column name.
The regular expression syntax supported by LIKE clauses is that of
standard SQL:
Examples
SELECT first_name, last_name FROM emp_details
WHERE dept = 'finance'
The following shows the returned data in ascending order by
last_name and descending order by first_name.
SELECT first_name, last_name FROM emp_details
WHERE dept = 'finance'
ORDER BY last_name, first_name DESC
Note Here DESC applies to both last_name and first_name.
Database Basics
A-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
A
SQL Basics
SELECT Statement
Examples
To remove any duplicate rows, you can use the DISTINCT operator:
SELECT DISTINCT first_name, last_name FROM emp_details
WHERE dept = 'finance'
ORDER BY last_name, first_name DESC
Note DISTINCT is useful when you do not have a primary key.
To search for anyone in the finance department whose last name
consists of a letter followed by ughes, such as Hughes, the query
could look like the following:
SELECT first_name, last_name FROM emp_details
WHERE dept = 'finance' AND last_name LIKE '_ughes'
Joins
The power of a relational query language is apparent when you start
joining tables during a SELECT operation. For example, if you have
two tables definedone containing staff details and another listing the
projects being worked on by each staff memberand each staff
member has been assigned an employee number that is unique to that
person, you can generate a sorted list of who was working on what
project with the following query:
SELECT emp_details.first_name, emp_details.last_name,
project_details.project
FROM emp_details, project_details
WHERE emp_details.emp_id = project_details.emp_id
ORDER BY emp_details.last_name, emp_details.first_name
Most relational databases place no restriction on the number of tables
joined during a query. You would have 15 tables, all containing
information related to an employee ID in some manner. You can
extract data from each of those tables, though slowly, by a single
query.
A-16
A
SQL Basics
SELECT Statement
Joins
Note You must qualify all column names with a table name. SQL
does not support the concept of uniquely named columns spanning
multiple tables. You must qualify every column name as soon as you
access more than one table in a single SELECT.
INSERT Statement
Note Unlike ANSI SQL, you cannot nest a SELECT statement within
an INSERT statement. That is, you cannot insert the data returned by a
SELECT statement.
The INSERT statement adds new SQL records to a table. You must
specify the names of the fields into which the data is to be inserted.
You cannot specify the values without the field name; the server does
not insert the data into the correct fields by default.
Use the following syntax for INSERT:
INSERT INTO table_name ( column [ , column ]... )
VALUES (value [, value]... )
For example:
INSERT INTO emp_details ( first_name, last_name, dept, salary)
VALUES ('Joe', 'Mays', 'I.T.S.','12345')
The number of values supplied must match the number of columns.
However, the column names are optional if every column value is
matched with an INSERT value.
Database Basics
A-17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
A
SQL Basics
DELETE Statement
The DELETE statement removes records from a SQL table. The syntax
for DELETE is:
DELETE FROM table_name
WHERE column OPERATOR value
[ AND | OR column OPERATOR value ]...
OPERATOR can be <, >, =, <=, >=, <>, or the keyword LIKE.
For example:
DELETE FROM emp_details WHERE emp_id = '12345'
UPDATE Statement
The UPDATE statement is the SQL mechanism for changing the contents
of a SQL record. To change a particular record, you must identify what
record from the table you want to change. The UPDATE statement
cannot use a column name as a value. You can use only literal values
as an UPDATE value. The syntax for UPDATE is:
UPDATE table_name SET column=value [ , column=value ]...
WHERE column OPERATOR value
[ AND | OR column OPERATOR value ]...
OPERATOR can be <, >, =, <=, >=, <>, or the keyword LIKE.
For example:
UPDATE emp_details SET salary=30000 WHERE emp_id = '1234'
A-18
Using SQLJ
Objectives
Upon completion of this appendix, you should be able to:
This appendix defines SQLJ, and describes how to use SQLJ to connect
a Java application to a relational database.
B-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
B
References
Additional resources The following resource can provide additional
detail on the topics presented in this module:
B-2
B
SQLJ Overview
SQL is used for defining and manipulating data in a relational
database; embedded SQL is SQL written directly in the source file of a
program. Most applications written in C and C++ that interact with a
relational database use embedded SQL.
Oracle Corporation, in conjunction with other leading database
vendors, wanted to be able to embed SQL in the Java programming
language. This group created SQLJ. SQLJ is a language for embedding
static SQL in the Java programming language. It is an alternative
method, in addition to the JDBC API, to connect a Java application to a
relational database.
SQLJ is for static SQL, as opposed to the JDBC API, which is for static
or dynamic SQ:; you can use both in your programs. SQLJ uses JDBC
calls, so you can combine the two in the same program. You can
initialize a JDBC connection with a SQLJ connection context, or a SQLJ
connection with a JDBC connection context.
You still need a JDBC driver to connect to the database using SQLJ.
While you need the driver for both the JDBC API and SQLJ, using
SQLJ is sometimes a better choice because its source programs are
smaller and it does compile-time type checking. You can verify queries
against the database before actually running the application.
SQLJ code can be smaller, more compact, and more self-explanatory
than JDBC code.
You also can create a JDBC ResultSet from a SQLJ iterator, covered
later in this module in the Executing the Query and Reviewing the
Result Set Using Iterator Objects. section. Therefore, the dynamic SQL
API for SQLJ is the JDBC API.
Using SQLJ
B-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
B
SQLJ Architecture
Figure B-1 shows that the architecture of a database application using
SQLJ is similar to one that uses the JDBC API.
Java application*
SQLJ Runtime
JDBC API
JDBC-Net
Driver
JDBC-ODBC
Bridge driver
Driver A
Driver B
...
ODBC and
DB drivers
* Contains SQLJ program files
Figure B-1
SQLJ Architecture
The SQLJ Runtime is a thin layer of 100% Pure Java code that is
located above the JDBC driver and is used to communicate with your
program. Programs translated by SQLJ can access any database with a
JDBC driver and a compliant SQLJ Runtime. This allows programs to
be portable across platforms and databases.
B-4
B
How SQLJ Works
SQLJ program files contain the static SQL calls to connect to the
relational database, and are indicated with a .sqlj extension.
SQLJ uses a translator, a preprocessor, to replace the embedded static
SQL in the SQLJ program with calls to the JDBC API. The SQLJ
Translator is run against the .sqlj file, using the compile command
sqlj filename, and produces one or more .java source files that
you can compile with any standard Java programming language
compiler.
Figure B-2 shows the series of compilation steps.
sqlj filename.sqlj
Step 1
.sqlj file
SQLJ Translator
.java file(s)
javac filename.java
Step 2
.java file
Figure B-2
javac compiler
.class file(s)
Using SQLJ
B-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
B
How SQLJ Works
Note If a program is compiled pointing to database A, then run on
database B with tables that are not in sync with the tables in database
A, there can be errors at runtime.
Code Example
To see how the .sqlj file looks before and after compiling, open the
lab files directory for this course. Locate the directory for SQLJ, and
open the files named SqljDemo.sqlj and SqljDemo.java.
B-6
B
Using SQLJ
The steps for using SQLJ to connect to and review data from a
database are similar to the six main steps that you follow to use the
JDBC API, and shown in Table B-1.
Table B-1 SQLJ Development Steps
Step 1 Registering a driver
Step 2 Establishing a connection to
the database
Using SQLJ
B-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
B
Registering and Connecting to the Database Using Database
Connection Management
SQLJ defines a default database connection that is global to the SQLJ
program; you do not have to explicitly define the connection.
You also can use SQLJ programs to manipulate multiple database
connections. You can explicitly create a connection context at any point
that a Java programming language class declaration is permitted. A
connection context manages a set of SQL operations performed during
a session with a specific database. SQLJ comes with a
DefaultContext that you can use, or you can define your own
context that will be specific to your application.
Syntax
DefaultContext ctxtVariable;
ctxtVariable = new DefaultContext (JDBCConnection);
DefaultContext.setDefaultContext (ctxtVariable);
This syntax corresponds to the bold lines in the following example.
B-8
B
Registering and Connecting to the Database Using Database
Connection Management
Example
The following is a sample generic Connection class that returns a
Connection or DefaultContext. The sample was created by Oracle
Corporation and is included as part of the SQLJ implementation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Using SQLJ
B-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
B
Registering and Connecting to the Database Using Database
Connection Management
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 }
B-10
DriverManager.registerDriver((Driver)driverClass.newInstance());
conn = DriverManager.getConnection (dburl, uid, pwd);
} catch (Exception e) {
System.err.println( "Could not establish the JDBC connection:") ;
System.err.println(e); System.exit(1);
}
return conn;
}
/**
Returns the currently installed SQLJ default context.
If the current default context is null, a new default context
instance is set up using a connection obtained from
<code>getConnection()</code>.
**/
static public DefaultContext initContext()
{
DefaultContext ctx = DefaultContext.getDefaultContext();
if (ctx == null) {
try {
ctx = new DefaultContext(newConnection());
} catch (SQLException e) {
System.out.println("Error: could not get a default context");
System.err.println(e) ; System.exit(1);
}
DefaultContext.setDefaultContext(ctx);
}
return ctx;
}
B
Registering and Connecting to the Database Using Database
Connection Management
The ConnectionManager class makes it easy to create a new context.
The new context is used with the SQLJ clause in the resetTable
method, in line 19. The SQL DELETE statement now uses the DemoCtx
context instead of the DefaultContext.
1 import java.sql.* ;
2
3 /* Declare a ConnectionContext class named DemoCtx. Instances of this
4
class can be used to specify where SQL operations should execute.
5 */
6 #sql context DemoCtx;
7
8 class ContextDemo {
9
private DemoCtx ctx;
10
11 public ContextDemo() {
12
try {
13
ctx = new DemoCtx(ConnectionManager.newConnection());
14
} catch (Exception e) {
15
System.err.println
("Error setting database connection: " + exception);
16
}
17 }
18
19 public resetTables() throws SQLException {
20
#sql [ctx] { DELETE FROM TABLE1 };
21 }
22 }
Using SQLJ
B-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
B
Creating a Statement Using SQLJ Clauses and Host Variables
SQLJ Clauses
Static SQL appears in a SQLJ program as a SQLJ clause. A SQLJ clause
begins with the token #sql and then contains a SQL statement that is
enclosed in curly braces. A SQLJ clause can be any place in the
program that a Java programming language statement might appear.
Syntax
#sql {SQLString};
Example
The following SQLJ clause selects the first and last name from the
Customer table for a given customer ID:
1
2
3
4
B-12
String firstName;
String lastName;
int customerID;
#sql{SELECT fname, lname INTO :firstName, :lastName FROM Customer
WHERE custID = :customerID};
B
Creating a Statement Using SQLJ Clauses and Host Variables
Host Variables
Host variables are used to pass the input and output of SQL
statements. A host variable is a Java programming language variable,
parameter, or field that is embedded in a SQL statement prefixed by a
colon.
type variable
Example
String firstName
:variable
Example
The IterDemo1.sqlj file in your sqlj directory uses the following.
:itemID,:itemName,:dateSold,:totalCost,:salesRepID,:salesRepName
Using SQLJ
B-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
B
Executing the Query and Reviewing the Result Set Using
Iterator Objects
In a SQLJ program, a result set returned by a SQL query is accessed by
means of an iterator object, which iterates through the rows in the result
set. You can define an iterator class with the #sql token and the
keyword iterator. The clause that defines a named iterator lists the
names and types of columns in a row returned in the result set. You
can define iterators anywhere a class definition can appear.
B-14
B
Executing the Query and Reviewing the Result Set Using
Iterator Objects
Using an Iterator Class
Syntax
tableName iteratorRefVar;
#sql iterator = {SQL_statement};
Example
1 SalesRecs sales;
2
3
4
5
6
7
8
9
10
11
12
13
14
15 }
16 }
Using SQLJ
B-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Glossary
ANSI
American National Standards Institute.
Business rules
Rules governing what operations are permitted on application
data and what constraints apply to those operations. These
rules generally vary depending on the business requirements of
the application being designed.
Client/server
An application architecture where functionality is divided
between service requestors (clients) and service providers
(servers). Generally, the client part of the architecture allows the
user to interact with the system and the server provides the
ability to store and manipulate application data or resources.
Client/server architectures tend to be very flexible, allowing
one or more clients to use resources from one or more servers.
Column
A description of a data element that resides in a relational table.
The description of a column is referred to as its metadata, and
consists of the elements name, data type, and special attributes,
such as being a non-null field.
Commit
The act of finalizing a transaction (set of operations) on a
database.
Concurrency
In databases, the attempt by several users to access the same
database structure. In relational databases, this means accessing
the same table.
Glossary-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Connection pool
A managed set of database connections. A connection pool can
be used in a distributed system and can provide performance
improvements for the application.
Database
A shared collection of logically related data and a description of
the data elements.
Database Management System (DBMS)
A software system allowing users to define, create, and
maintain databases and the data stored within. A DMBS also
provides controlled access to a database.
Dynamic SQL
An approach to generating SQL queries where the SQL
command is first stored in a local variable, then is passed to the
database for execution. This provides the application with the
flexibility to change the SQL instruction and execute the
command on the fly. In the Java programming language, JDBC
provides support for dynamic SQL.
Embedded SQL
Hard-coded SQL instructions directly written into a program. In
the Java programming language, SQLJ provides this capability.
Foreign key
In relational databases, a column that matches database rows in
one table to zero or more rows within another table. This is
used to represent a one-to-many relationship for tables in
databases.
ISO
International Standards Organization.
Java 2 SDK
The latest release of a set of program modules, applications, and
class files used to develop and run applications written in the
Java programming language (previously referred to as the
JDK).
Java Naming and Directory Interface (JNDI)
An extension to the Java platform that provides applications
with a unified interface to multiple naming and directory
services in an enterprise environment.
Glossary-2
Glossary
Glossary-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Glossary-4
Row
A single set of associated values stored within a table of a
relational database. A row is also called a database record.
SQL
A language used to programmatically query databases. It has
become the de facto standard for communications with
databases in general, and Relational Databases in particular.
Although it is not an acronym, SQL is often referred to as the
Structured Query Language. SQL is a standard maintained by
ISO and ANSI committees. The three standards are commonly
referred to as SQL/89, SQL92 (also called SQL2) and SQL3.
SQLJ (Java)
A standard for embedding static SQL statements and constructs
in Java technology programs. See also SQL and Embedded SQL.
Table
In relational databases, a structure for data storage consisting of
rows and columns. A column represents one data type within
the table. A row is a database record, a set of values for the
given table.
Three-tier
An architecture for client/server systems, consisting of three
logical layers, or tiers. The first tier (sometimes called the front
end or presentation tier) is generally located on a users
machine; it displays data and allows a user to interact with the
application. The front end communicates with a middle tier
(also known as the business logic tier), which coordinates client
requests and commands and is often used to implement
business rules for the application. The middle tier passes client
requests to the third tier. (also called the back end or data tier)
The third tier provides data management and storage services
to the client(s) through one or more middle tiers.
Tier
A part of an application architecture responsible for fulfilling
some function. A tier might not be an independent code
module. More than one tier can reside on the same machine.
Tiers are sometimes referred to as layers.
Glossary
Glossary-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Transaction
In database manipulation, a logical group of work consisting of
one or more instructions. For a transaction to execute
successfully, all of its instructions must be successfully executed
for the database. If there is an error any time during transaction
execution, the previous operations must be reversed. This is
referred to as backing out or performing a rollback on a
transaction.
Two-tier
An architecture for client/server systems. Normally, a client
interface, located on a users computer system, interacts with a
database management system on another machine. The
database management system generally services requests from
many clients.
Glossary-6
Copyright 2000 Sun Microsystems Inc., 901 San Antonio Road, Palo Alto, California 94303, Etats-Unis. Tous droits
rservs.
Ce produit ou document est protg par un copyright et distribu avec des licences qui en restreignent lutilisation, la
copie, la distribution, et la dcompilation. Aucune partie de ce produit ou document ne peut tre reproduite sous aucune
forme, par quelque moyen que ce soit, sans lautorisation pralable et crite de Sun et de ses bailleurs de licence, sil y en a.
Le logiciel dtenu par des tiers, et qui comprend la technologie relative aux polices de caractres, est protg par un
copyright et licenci par des fournisseurs de Sun.
Des parties de ce produit pourront tre drives du systmes Berkeley 4.3 BSD licencis par lUniversit de Californie.
UNIX est une marque dpose aux Etats-Unis et dans dautres pays et licencie exclusivement par X/Open Company Ltd.
Sun, Sun Microsystems, le logo Sun, Solaris, JDK, PersonalJava, Java, JavaBeans, 100% Pure Java, JDBC Compliant,
JavaSoft, Java Naming and Directory Interface, JavaBlend, JavaScript, et JDBC sont des marques de fabrique ou des
marques dposes de Sun Microsystems, Inc. aux Etats-Unis et dans dautres pays.
Toutes les marques SPARC sont utilises sous licence sont des marques de fabrique ou des marques dposes de SPARC
International, Inc. aux Etats-Unis et dans dautres pays.
Les produits portant les marques SPARC sont bass sur une architecture dveloppe par Sun Microsystems, Inc.
Linterfaces dutilisation graphique OPEN LOOK et Sun a t dveloppe par Sun Microsystems, Inc. pour ses
utilisateurs et licencis. Sun reconnat les efforts de pionniers de Xerox pour larecherche et le dveloppement du concept
des interfaces dutilisation visuelle ou graphique pour lindustrie de linformatique. Sun dtient une licence non exclusive
de Xerox sur linterface dutilisation graphique Xerox, cette licence couvrant galement les licencis de Sun qui mettent
en place linterface dutilisation graphique OPEN LOOK et qui en outre se conforment aux licences crites de Sun.
Laccord du gouvernement amricain est requis avant lexportation du produit.
Le systme X Window est un produit de X Consortium, Inc.
LA DOCUMENTATION EST FOURNIE EN LETAT ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET
GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA
LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE
MARCHANDE, A LAPTITUDE A UNE UTILISATION PARTICULIERE OU A LABSENCE DE CONTREFAON.
Please
Recycle