Sie sind auf Seite 1von 340

Database Application Programming

With Java Technology


SL-330

Student Guide

Sun Microsystems, Inc.


MS BRM01-209
500 Eldorado Boulevard
Broomfield, Colorado 80021
U.S.A.

Revision A.1, October 1999

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

Identifying a Database Using a URL............................................ 1-24


Overview ..................................................................................1-24
Basic URL Syntax ....................................................................1-26
jdbc...........................................................................................1-27
subprotocol ...........................................................................1-28
subname ...................................................................................1-30
Connecting to a Remote Server.............................................1-31
Check Your Progress ...................................................................... 1-32
Think Beyond .................................................................................. 1-33
Using JDBC ................................................................................................2-1
Objectives ...........................................................................................2-1
Relevance............................................................................................ 2-2
Creating a Basic JDBC Application ................................................ 2-3
Step 1 Registering a Driver ........................................................... 2-6
Overview ....................................................................................2-6
Using the Class Loader...........................................................2-8
Instantiating a Driver..............................................................2-9
Using the jdbc.drivers Property ......................................2-11
Choosing the Best Registration Approach ..........................2-14
Step 2 Establishing a Connection to the Database .................. 2-15
Connection Process.................................................................2-15
DriverManager.getConnection........................................2-18
Driver.connect.....................................................................2-20
Step 3 Creating a Statement........................................................ 2-22
Statement................................................................................2-23
PreparedStatement..............................................................2-25
CallableStatement..............................................................2-27
Comparing Statement Interfaces ..........................................2-29
Step 4 Executing the SQL Statement ......................................... 2-30
Statement................................................................................2-31
PreparedStatement and CallableStatement................2-32
Step 5 Processing the Results ..................................................... 2-33
Step 6 Closing Down JDBC Objects........................................... 2-35
Exercise: Using JDBC...................................................................... 2-37
Tasks .........................................................................................2-37
Exercise Summary...................................................................2-38
Check Your Progress ...................................................................... 2-39
Think Beyond .................................................................................. 2-40
OOAD and Database Design ..................................................................3-1
Objectives ...........................................................................................3-1
Relevance............................................................................................ 3-2
References .......................................................................................... 3-3
Module Overview ............................................................................. 3-4
Object ID Overview .......................................................................... 3-5
Object IDs and Primary Keys .......................................................... 3-6
iv

Database Application Programming With Java Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Creating Object IDs......................................................................... 3-11


Single-row Table .....................................................................3-11
High/Low ................................................................................3-12
Object-Relational Mapping............................................................ 3-15
Mapping Classes to Tables ............................................................ 3-18
One Table for Every Class .....................................................3-19
One Table for Each Concrete Class ......................................3-23
One Table for an Entire Class Hierarchy .............................3-26
Mapping Two Classes to One Table.....................................3-29
Mapping Class Attributes to Table Columns ............................. 3-31
Mapping Class Relationships to Tables....................................... 3-33
One-to-One Relationships......................................................3-34
One-to-Many Relationships...................................................3-36
Many-to-Many Relationships................................................3-38
Exercise: OOAD and Database Design ........................................ 3-41
Tasks .........................................................................................3-41
Exercise Summary...................................................................3-42
Check Your Progress ...................................................................... 3-43
Think Beyond .................................................................................. 3-44
JDBC Advanced Topics ...........................................................................4-1
Objectives ...........................................................................................4-1
Relevance............................................................................................ 4-2
Exceptions .......................................................................................... 4-3
Overview ....................................................................................4-3
SQLException...........................................................................4-4
SQLWarning ...............................................................................4-6
Metadata............................................................................................. 4-7
Database Metadata....................................................................4-8
Result Set Metadata ..................................................................4-9
Transactions ..................................................................................... 4-10
Overview ..................................................................................4-10
JDBC Transaction Methods ...................................................4-11
Basic Syntax .............................................................................4-12
Concurrency Control ..............................................................4-13
Exercise: JDBC Advanced Topics ................................................. 4-17
Tasks .........................................................................................4-17
Exercise Summary...................................................................4-18
Check Your Progress ...................................................................... 4-19
Think Beyond .................................................................................. 4-20
JDBC 2.0 Core Features ............................................................................5-1
Objectives ...........................................................................................5-1
Relevance............................................................................................ 5-2
Enhancements to the JDBC 2.0 API ................................................ 5-3

v
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Result Set Enhancements ................................................................. 5-5


Scrollability ................................................................................5-6
Updatability .............................................................................5-14
Statement Enhancements for Batch Updates .............................. 5-19
Statement................................................................................5-20
PreparedStatement..............................................................5-24
CallableStatement..............................................................5-26
Advanced Data Types .................................................................... 5-27
Overview ..................................................................................5-27
Using SQL3 Data Types .........................................................5-29
Blob, Clob, and Array Objects .............................................5-32
Structured Types and Distinct Types...................................5-34
Structured Types .....................................................................5-35
Distinct Types ..........................................................................5-37
SQL3 Advanced Features ......................................................5-39
Exercise: JDBC 2.0 Core Features.................................................. 5-40
Tasks .........................................................................................5-40
Exercise Summary...................................................................5-41
Check Your Progress ...................................................................... 5-42
Think Beyond .................................................................................. 5-43
JDBC 2.0 Standard Extensions ................................................................6-1
Objectives ...........................................................................................6-1
Relevance............................................................................................ 6-2
References .......................................................................................... 6-3
Standard Extension Enhancements to the JDBC 2.0 API ............ 6-4
JNDI .................................................................................................... 6-5
Overview ....................................................................................6-5
JNDI Advantages ......................................................................6-6
JDBC DataSource.....................................................................6-8
Registering a DataSource Object .........................................6-12
Establishing a Connection Using JNDI................................6-14
Connection Pooling ........................................................................ 6-16
Overview ..................................................................................6-16
Connecting ...............................................................................6-19
Distributed Transactions................................................................ 6-20
Overview ..................................................................................6-20
Architecture .............................................................................6-21
Implementation .......................................................................6-23
Row Sets ........................................................................................... 6-26
Overview ..................................................................................6-26
Types of Row Set Implementations......................................6-28
Row Sets at Design Time........................................................6-30
Row Sets at Runtime...............................................................6-35

vi

Database Application Programming With Java Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Overview of Row Set Implementation ........................................ 6-38


Check Your Progress ...................................................................... 6-40
Think Beyond .................................................................................. 6-41
Row Set Implementation .........................................................................7-1
Objectives ...........................................................................................7-1
Relevance............................................................................................ 7-2
CachedRowSet Class Overview ...................................................... 7-3
Creating a CachedRowSet................................................................ 7-6
Retrieving Data.................................................................................. 7-7
Miscellaneous Methods.................................................................. 7-15
Reading and Writing Data............................................................. 7-16
Overview ..................................................................................7-16
RowSetReader.........................................................................7-20
RowSetWriter.........................................................................7-22
Exercise: Row Set Implementations ............................................. 7-23
Tasks .........................................................................................7-23
Exercise Summary...................................................................7-24
Check Your Progress ...................................................................... 7-25
Think Beyond .................................................................................. 7-26
JDBC and Application Architecture ......................................................8-1
Objectives ...........................................................................................8-1
Relevance............................................................................................ 8-2
References .......................................................................................... 8-3
Tiered Application Architecture Overview .................................. 8-4
Tiers and Components ..................................................................... 8-6
Two-Tier Architecture ...................................................................... 8-7
Three-Tier Architecture.................................................................... 8-9
N-Tier Architecture......................................................................... 8-13
Choosing an Architecture .............................................................. 8-16
Two-Tier Architecture ............................................................8-16
Three-Tier and N-Tier Architecture .....................................8-18
Check Your Progress ...................................................................... 8-20
Think Beyond .................................................................................. 8-21
Database Basics ........................................................................................A-1
Objectives ..........................................................................................A-1
References ......................................................................................... A-2
Database Overview.......................................................................... A-3
Data Independence .......................................................................... A-6
Transactions ...................................................................................... A-7
Locking ............................................................................................ A-11

vii
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

SQL Basics ....................................................................................... A-13


Overview .................................................................................A-13
SELECT Statement...................................................................A-14
INSERT Statement...................................................................A-17
DELETE Statement...................................................................A-18
UPDATE Statement...................................................................A-18
Using SQLJ ................................................................................................ B-1
Objectives .......................................................................................... B-1
References ......................................................................................... B-2
SQLJ Overview ................................................................................. B-3
SQLJ Architecture ............................................................................ B-4
How SQLJ Works ............................................................................. B-5
Using SQLJ ........................................................................................ B-7
Registering and Connecting to the Database Using
Database Connection Management............................................ B-8
Creating a Statement Using SQLJ Clauses and Host
Variables....................................................................................... B-12
SQLJ Clauses........................................................................... B-12
Host Variables ....................................................................... B-13
Executing the Query and Reviewing the Result Set
Using Iterator Objects................................................................. B-14
Defining an Iterator Class ..................................................... B-14
Using an Iterator Class .......................................................... B-15
Glossary ....................................................................................... Glossary-1

viii

Database Application Programming With Java Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

About This Course


Course Goal
Database Application Programming With Java Technology is a focusedtechnology course that provides you with a hands-on approach to
developing database applications using Java technology and the
JDBC application programming interface (API). You will learn to use
the features of the JDBC 1.0 API, and will learn about the new features
added in JDBC 2.0.
Note JDBC is not an acronym; however, it is considered to stand for
Java database connectivity.
You will also learn how to map an object-oriented design to a
relational database, and how to design a multi-tier database
application.

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.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

About This Course


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Module-by-Module Overview
This course contains the following modules:

Module 1 JDBC Overview


This module describes how the JDBC API is used, and how it
enables a Java application to connect to a database.

Module 2 Using JDBC


This module describes the steps necessary to enable a Java
application to connect to a relational database and retrieve data
using JDBC 1.0 capabilities.

Module 3 OOAD and Database Design


This module describes how to map your object-oriented Java
application to the tables and columns of a relational database, and
identify each object uniquely.

About This Course

xiii

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Module-by-Module Overview

Module 4 JDBC Advanced Topics


This module describes the JDBC 1.0 topics of exception handling,
metadata, and data manipulation.

Module 5 JDBC 2.0 Core Features


This module describes how to use the core features, such as
forward and backward scrolling, which were added to the JDBC
API in the latest release.

Module 6 JDBC 2.0 Standard Extensions


This module describes how to use the advanced features, such as
support for Java Naming and Directory Interface (JNDI), which
were added to the JDBC API in the latest release.

Module 7 Row Set Implementation


This module describes the CachedRowSet implementation and
row set readers and writers.

Module 8 JDBC and Application Architecture


This module describes application architecture considerations
related to JDBC.

xiv

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Module-by-Module Overview

Appendix A Database Basics


This appendix reviews different types of databases, concepts such
as locking and transactions, and basic structured query language
(SQL) commands, such as SELECT and UPDATE.

Appendix B Using SQLJ


This appendix defines SQLJ, and describes how to use SQLJ to
connect a Java application to a relational database.

About This Course


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

xv

Course Objectives
Upon completion of this course, you should be able to:

xvi

Design a multi-tier database application architecture

Create a multi-tier database application using the Java


programming language and the JDBC 1.0 API

Map an object-oriented design to a relational database

Explain the features added to the JDBC 2.0 API

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Skills Gained by Module


The skills for Database Application Programming With Java Technology are
shown in column 1 of the following matrix. The black boxes indicate
the main coverage for a topic; the gray boxes indicate the topic is
briefly discussed.
Module
Skills Gained

2 3 4 5

6 7 8

Design a multi-tier database application architecture


Create a multi-tier database application using the
Java programming language and the JDBC 1.0 API
Map an object-oriented design to a relational database
Explain the features added to the JDBC 2.0 API

About This Course

xvii

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Guidelines for Module Pacing


The following table provides a rough estimate of pacing for this
course:
Module

xviii

Day 1

About This Course

A.M.

JDBC Overview

A.M.

Using JDBC

P.M.

Day 2

OOAD and Database Design

A.M.

JDBC Advanced Topics

P.M.

Day 3

JDBC 2.0 Core Features

A.M.

JDBC 2.0 Standard Extensions

P.M.

Day 4

Row Set Implementation

A.M.

JDBC and Application Architecture

P.M.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Topics Not Covered


This course does not cover the topics shown on the above overhead.
Many of the topics listed on the overhead are covered in other courses
offered by Sun Educational Services:

Object-oriented theory Covered in SL-210: Migrating to OO


Programming with Java Technology and OO-226: Application Analysis
and Design for Java Technology

Java programming language basics Covered in SL-275: Java


Programming Language

Relational database design and SQL basics

Refer to the Sun Educational Services catalog for specific information


and registration.

About This Course

xix

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

How Prepared Are You?


To be sure you are prepared to take this course, can you perform the
topics shown on the above overhead?

xx

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

About This Course

xxi

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

How to Use Course Materials


To enable you to succeed in this course, these course materials employ
a learning model that is composed of the following components:

xxii

Objectives What you should be able to accomplish upon


completion of the module is listed here.

Relevance The Relevance section for each module provides


scenarios or questions that introduce you to the information
contained in the module and provoke you to think about how the
module content relates to database application programming.

Overhead image Reduced overhead images for the course are


included in the course materials to help you easily follow where
the instructor is at any point in time. Overheads do not appear on
every page.

Lecture The instructor will present information specific to the


topic of the module. This information will help you learn the
knowledge and skills necessary to succeed with the exercises.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

How to Use Course Materials

Exercise Lab exercises will give you the opportunity to practice


your skills and apply the concepts presented in the lecture.

Check your progress Module objectives are restated, sometimes


in question format, so that before moving on to the next module
you are sure that you can accomplish the objectives of the current
module.

Think beyond Thought-provoking questions are posed to help


you apply the content of the module or predict the content in the
next module.

About This Course

xxiii

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Course Icons and Typographical Conventions


The following icons and typographical conventions are used in this
course to represent various training elements and alternative learning
resources.

Icons
Additional resources Indicates additional reference materials are
available.

Discussion Indicates a small-group or class discussion on the current


topic is recommended at this time.

Exercise objective Indicates the objective for the lab exercises that
follow. The exercises are appropriate for the material being discussed.

Note Additional important, reinforcing, interesting or special


information.

xxiv

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Course Icons and Typographical Conventions


Typographical Conventions
Courier is used for the names of commands, files, and directories, as
well as on-screen computer output. For example:
Use ls -al to list all files.
system% You have mail.
Courier bold is used for characters and numbers that you type. For
example:
system% su
Password:

Courier italic is used for variables and command-line


placeholders that are replaced with a real name or value. For example:
To delete a file, type rm filename.
Palatino italics is used for book titles, new words or terms, or words
that are emphasized. For example:
Read Chapter 6 in Users Guide.
These are called class options.
You must be root to do this.

About This Course

xxv

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Course Icons and Typographical Conventions


Syntax Conventions
Whenever possible, both the syntax of a particular language element
and an example are shown. The following example of this approach
shows the syntax, then an example of declaring an integer variable.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

JDBC Overview

Objectives
Upon completion of this module, you should be able to:

Describe the purpose of the JDBC API

Explain how to use the JDBC API to connect a Java application to


a database

Define the different components of the JDBC architecture

Select the correct kind of JDBC driver for a given application


architecture

Describe the uniform resource locator (URL) syntax used to


identify a database

This module describes the components of the JDBC API, how it is


used, and how it enables a Java application to connect to a database.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

1
References
Additional resources The following resources can provide
additional detail on the topics presented in this module, as well as the
entire course.

Main JDBC download page, including access to the Java Platform,


Standard Edition; the Java 2 Platform, Enterprise Edition; the JDBC
2.0 Core API; and JDBC 2.0 Standard Extension API. [Online.]
Available: http://java.sun.com/products/jdbc

JDBC documentation. [Online.] Available:


http://www.javasoft.com/products/jdk/1.2/docs/guide/
jdbc/index.html

Java 2 Platform API Specification. [Online.] Available:


http://java.sun.com/products/jdk/1.2/docs/api/
index.html

Bowman, Judith S., Sandra L. Emerson, Marcy Darnovsky. 1996.


The Practical SQL Handbook: Using Structured Query Language.
Addison-Wesley.

Navathe, Shamkant B., Ramez A. Elmasri. Fundamentals of Database


Systems/Oracle Programming. Addison-Wesley.

White, Seth, Maydene Fisher, Rick Cattell, Graham Hamilton,


Mark Hapner. Universal Data Access for the Java 2 Platform (Java
Series). Addison-Wesley.

Reese, George. Database Programming with JDBC and Java. OReilly


& Associates. 1997.

JDBC Overview

1-3

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

What Is the JDBC API?


The JDBC API is a standard data access interface, developed by Sun
Microsystems and its partners who incorporate Java technology.
This API provides universal access to a wide range of relational
databases, enabling you to focus on the major application
development issues, rather than the mechanics of connecting to a
specific database.
The JDBC API is a set of classes and interfaces provided in the Java 2
Software Development Kit (J2SDK). JDBC has been included since
JDK 1.1 was released. Since its first release, JDBC has had one major
revision. JDK 1.1 comes with JDBC 1.0, while the J2SDK includes JDBC
2.0.
JDBC makes it possible to do three main tasks:

1-4

Establish a connection with a database

Send a SQL query as a String directly to the database

Process the results

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

What Is the JDBC API?


There are two major components of JDBC, the developer interface and
the implementation interface. This course concentrates on the
developer interface.

An interface for Java programming language developers. This


provides developers with the class and method definitions
required to use the features implemented in the JDBC drivers,
created by database providers or other driver vendors.
The developer interface consists of two packages.

java.sql, included with the Java 2 Platform, Standard Edition


and JDK 1.1

javax.sql, included with the Java 2 Platform, Enterprise


Edition.

An implementation interface for database providers. This provides


vendors with the requirements they must fulfill to produce JDBC
drivers, which allow Java applications to use their database
functionality. The implementation specifications and tools are
supplied by Sun Microsystems.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Allows ODBC drivers to be


used as JDBC drivers; was
implemented to get the
JDBC API working quickly

No

Direct

Native API
based

Built on top of a native


database client library;
translates the JDBC calls
into calls to the API of the
database client library

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

Translates JDBC calls


directly into the network
protocol used by the
DBMS, allowing direct calls
from the client to the
database

Yes

Direct

JDBC-Net and Native protocol are the preferred way to access


databases from the JDBC API, because they are pure Java technology.
JDBC-ODBC bridge and Native API are considered interim solutions
until pure Java technology drivers are available.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

JDBC Developer Interface


Packages
The JDBC API is expressed as a series of Java technology interfaces, in
the following packages:

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.

javax.sql Contains extended functionality introduced with the


JDBC 2.0 API
This package is part of the Java 2 Platform, Enterprise Edition, and
also can be downloaded separately.

JDBC Overview

1-19

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

JDBC Developer Interface


Classes and Interfaces
Note Functionality in the javax.sql package is covered in Module
5, JDBC 2.0 Core Features and Module 6, JDBC 2.0 Standard
Extensions.
The following are the basic JDBC classes and interfaces.

1-20

DriverManager

Driver

Connection

Statement

PreparedStatement

CallableStatement

ResultSet

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

java.sql Core API Class Hierarchy

1-23

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Identifying a Database Using a URL


Overview
A JDBC URL provides a way of identifying a database so that the
appropriate driver can recognize it and establish a connection with it.
The protocol, subprotocol, and specific data source are identified in the
URL. For example, the URL jdbc:odbc:fred indicates that the driver
should use the jdbc protocol to connect to an ODBC-type data source
named fred.
Driver vendors determine the JDBC URL that identifies their
particular driver. You do not need to form a JDBC URL; simply use the
URL supplied with the drivers you are using. The role of the JDBC API
is to recommend conventions for driver writers to follow when
structuring their JDBC URLs.

1-24

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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 allow driver writers to encode all necessary


connection information within them. For example, an applet can
talk to a given database to open the database connection without
requiring the user to do any system administration tasks.

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

Identifying a Database Using a URL


Basic URL Syntax
This section describes the standard syntax for JDBC URLs. The syntax
has three parts, separated by colons.
URL syntax
jdbc:subprotocol:subname
Example
jdbc:odbc:wombat
The protocol is always jdbc; the subprotocol is the type of connection,
odbc in this example; and the subname fred identifies the database.
Variations on this basic syntax are sometimes required for remote
connections, providing more information about connecting to the
database, and so on.
Each part of the URL is covered in the following sections.

1-26

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Identifying a Database Using a URL


jdbc
This is the protocol. The protocol in a JDBC URL is always jdbc.

JDBC Overview

1-27

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Identifying a Database Using a URL


subprotocol
This is the name of the driver or the type of database connectivity
mechanism, which can be supported by one or more drivers. Different
drivers must have a different subprotocol identifier for the
DriverManager to be able to distinguish among them.
In the example jdbc:odbc:wombat, the subprotocol is odbc.

1-28

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Identifying a Database Using a URL


subname
The subname provides enough information to locate the database. The
subname is determined by the driver vendor doing the
implementation (identified by the subprotocol).
In the example jdbc:odbc:fred, fred identifies the database.
A subsubname is sometimes required after the subprotocol; the syntax
is determined by the driver vendor.

1-30

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Identifying a Database Using a URL


Connecting to a Remote Server
In the example jdbc:odbc:fred, fred is enough to identify the
database because ODBC provides the remainder of the information.
However, a database on a remote server requires more information.
For example, if users will access the database over the Internet, the
network address should be included in the JDBC URL as part of the
subname. In this case, follow the standard Internet URL naming
convention.
URL syntax for connecting to a remote server
jdbc:subprotocol://hostname:port/subsubname
Example
Assume that dbnet is a protocol for connecting to a host on the
Internet.
jdbc:dbnet://wombat:3560/fred

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

Describe the purpose of the JDBC API

Explain how to use the JDBC API to connect a Java application to


a database

Define the different components of the JDBC architecture

Select the correct kind of JDBC driver for a given application


architecture

Describe the URL syntax used to identify a database

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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:

Select an appropriate method to register a JDBC driver

Establish a database connection with the registered JDBC driver

Query a database using the JDBC connection

Select the appropriate type of statement given the data query


requirements

Manipulate data in the database using a JDBC connection

Process the results of a query

Shut down the appropriate objects after a JDBC process is


complete

This module describes the steps necessary to enable a Java application


to connect to a relational database and retrieve data. The material
covered in this module is valid for both the JDBC 1.0 and 2.0 API
specifications.
Note Module 5, JDBC 2.0 Core Features and Module 6, JDBC 2.0
Standard Extensions, cover the functionality that is available only in
the latest JDBC release.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Creating a Basic JDBC Application


Now that you have learned the components of the JDBC API in
Module 1, JDBC Overview, the next step is to develop the code to
request and return information from a relational database
management system (RDBMS). The six main steps are as follows:
Note This list and the following sections cover the standard methods
for using the JDBC API to connect with and retrieve data from a
database. The information is not specific to versions 1.0 or 2.0.
Advanced features of JDBC 1.0, and the enhancements added with
JDBC 2.0, are covered in subsequent modules.

Step 1 Register a driver.


The driver connects to the database using DriverManager.

Step 2 Establish a connection to the database.


The DriverManager.getConnection method requires a URL to
locate the appropriate driver to use.

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

Step 3 Create a statement.


With the connection established, you can create (instantiate) a
Statement, CallableStatement, or PreparedStatement object,
which is used for your SQL command.

Step 4 Execute the SQL.


Use the executeQuery method of the Statement object to execute
the SQL statement.

Step 5 Process the results.


The Statement object returns a ResultSet. The ResultSet object
is all the rows of the table that satisfy the query. You can step
through the set to view each row. There are several methods
within the ResultSet to retrieve the data items from the row.

Step 6 Close down JDBC objects.


Close down the connection and other components of the JDBC
function.

2-4

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Step 1 Registering a Driver


Overview
The driver makes the connection to the database through the
DriverManager class. When attempting to connect to a database, the
JDBC API uses the first driver it finds that can successfully connect to
the given URL. Registering the driver is simple but critical, because
without the driver, you cannot make a connection to the database.
You do not need to create an object unless you need to explicitly
reference it.
Loading a driver consists only of loading the correct class into a
running Java Virtual Machine (JVM) session. It brings in the correct
bytecodes, and registers the driver with the appropriate structure in
the Java Virtual Machine: the driver manager. Registration lasts for the
duration of a particular JVM session only.
You can load multiple drivers in memory at the same time.

2-6

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

2
Step 1 Registering a Driver
Approaches to Registering a Driver
There are several ways to register a driver within a Java application:

Use the Class loader

Instantiate a driver

Use the jdbc.drivers property

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

Step 1 Registering a Driver


Using the Class Loader
To communicate with a particular database engine using the JDBC
API, you must first load the JDBC driver. The driver has a static
initializer that creates a Driver object, which registers the driver with
the driver manager. This driver remains behind the scenes, handling
any requests of that type of database.
To load the driver using the Class loader, call the driver name using
the complete path.
Syntax
Class.forName(driverName);
Example
The following line shows how to load the Oracle driver:
Class.forName("oracle.jdbc.driver.OracleDriver");

2-8

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 1 Registering a Driver


Instantiating a Driver
If you need an explicit reference to the Driver object, use the new
keyword to register the driver. You do not need to associate the driver
object with a variable, because it exists in memory and is accessible to
the DriverManager.
Syntax
Driver drvRefVar = new DriverConstructor;
Example
This example registers the driver with the driver manager, which
subsequently manages the driver for the JVM session. It is not
necessary to retain a reference to the created object.
Driver drv = new oracle.jdbc.driver.OracleDriver();

Using JDBC

2-9

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

2
Notes

2-10

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 1 Registering a Driver


Using the jdbc.drivers Property
A running JVM has a number of properties, which allow you to define
and retrieve values associated with JVM functionality. One of those
properties is jdbc.drivers.
You can register the driver using two approaches:

Defining the jdbc.drivers property

Using the -D option with the java command

Defining the jdbc.drivers Property


You can register a driver by defining the jdbc.drivers property as a
colon-separated list of driver class names.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 1 Registering a Driver


Using the jdbc.drivers Property
Using the -D Option With the java Command
When attempting to connect to a database, the JDBC API uses the first
driver it finds that can successfully connect to the given URL. It first
tries each driver specified in the properties list, in order from left to
right. It then tries any drivers that are already loaded in memory, in
the order that the drivers were loaded.
You can register the driver by loading it into the system properties. To
use this method, specify the name=value pair (the name is always
jdbc.drivers and the value is the driver name).
Syntax
java -Djdbc.drivers=driverName[:driverName]
Example
java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver:acme.cool.Driver

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 2 Establishing a Connection to the Database


Connection Process
The steps for establishing a connection occur in the following order:
1. The DriverManager calls getConnection(urlString), which
calls Driver.connect(urlString) on all the registered drivers
until a match is found.
Note The URL is described in Identifying a Database Using a URL
on page 1-24 in Module 1, JDBC Overview.
The drivers are checked in the following order:

Properties list

Memory

2. The URL is parsed.


3. When a driver responds positively to the database URL, the
DriverManager makes a connection to the database.

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

Database Application Programming With Java Technology


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

Example of Database Resolution

Note If a driver attempts to connect but fails, DriverManager


continues through the list of additional drivers.

Using JDBC

2-17

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 2 Establishing a Connection to the Database


You can use either of two methods to establish a connection.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Step 2 Establishing a Connection to the Database


Driver.connect
The Driver.connect method attempts to make a database connection
to the given URL.
This method makes a direct call to a specific Driver object. Use it to
avoid the problems of the standard approach to finding a driver, in
which DriverManager calls first one driver, then the next, and so on. If
the DriverManager requests a driver that is written badly to connect
to a given database, the driver may attempt to do so, even if it cannot,
and prevents other drivers from connecting.

2-20

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Step 3 Creating a Statement


You can use three types of statements.

2-22

Statement Executes a standard query

PreparedStatement Executes a precompiled SQL statement

CallableStatement Executes non-SQL statement

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 3 Creating a Statement


Statement
To submit a standard query, first get a Statement object from the
Connection.createStatement method.
Syntax
Statement stmtRefVar = conRefVar.createStatement();
Examples
1
2
3
4
5
6
7

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 3 Creating a Statement


PreparedStatement
If the same SQL statements are executed multiple times, use a
PreparedStatement object. A prepared statement is a precompiled SQL
statement that is more efficient than calling the same SQL statement
over and over. The SQL statement is parsed only once. The
PreparedStatement interface extends the Statement interface to add
the capability of passing parameters inside of a statement.
Syntax
PreparedStatement pstmtRefVar = conRefVar.prepareStatement(sqlString);
You can use question marks within the SQL statement as placeholders
for data values.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 3 Creating a Statement


CallableStatement
A callable statement allows non-SQL statements (such as stored
procedures) to be executed against the database. The
CallableStatement interface extends the PreparedStatement
interface, which provides the methods for setting IN parameters.
Because the PreparedStatement interface extends the Statement
interface, methods for retrieving multiple results with a stored
procedure are supported with the Statement.getMoreResults
method.
Syntax
CallableStatement cstmtRefVar = conRefVar.prepareCall(sqlString);

sqlString must be a query statement.


As with PreparedStatement, you can use question marks within the
SQL statement as placeholders for data values.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

2
Step 3 Creating a Statement
Comparing Statement Interfaces
Table 2-1 compares the three types of statement interfaces.
Table 2-1

Comparing Statement Interfaces


Statement

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

High the first time,


then low

Low

Portability

High

High, provided the


database supports
PreparedStatement

Low

Efficiency for
transferring
data

Low

Low the first time,


then high

High

Using JDBC

2-29

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 4 Executing the SQL Statement


When you submit the SQL statement to the database, the JDBC API
passes the SQL statement to the underlying database connection
unaltered. The JDBC API does not attempt to interpret queries.
The result of executing a query statement is a table of data that you
can access using a java.sql.ResultSet object.
The statement, whether it is a Statement, CallableStatement, or
PreparedStatement object, is coupled with the corresponding
ResultSet. If you run the statement again, the contents of the first
ResultSet will be overwritten by the results of the second statement.

2-30

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 4 Executing the SQL


Statement
You can use several approaches to execute the SQL statement.

For a SELECT statement, use


Statement.executeQuery(sqlString).

For INSERT, UPDATE, or DELETE statements, use


Statement.executeUpdate(sqlString), which returns an
integer.

For any process, you can use


Statement.execute(sqlString), which returns a boolean,
indicating whether a result set has been returned.

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

PreparedStatement and CallableStatement


Use the same three approaches listed for the Statement interface,
except that the PreparedStatement and CallableStatement
interfaces do not take an argument because the statement is already
defined.

2-32

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 5 Processing the Results


To retrieve data from the ResultSet object that was returned, use its
assessor methods, which enable access to the various column values of
the current row. One method is provided for each SQL type.
You can retrieve these values using either a column name or an index.
You should use an index when referencing a column. When you use a
name to reference a column, one or more columns could have the same
name, which causes a conflict. Indexes begin at 1.
Note The name used to reference a column is case sensitive.
A ResultSet keeps a cursor pointing to the current row of data and is
initially positioned before its first row. The first call to next makes the
first row the current row, the second call makes the second row the
current row, and so on.

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 }

column can be either the column name or column number.


Example
The following example retrieves specific columns in the coffee table
from the ResultSet. Column names are shown, but you could use
column IDs instead.
1 while (rs.next()) {
2
System.out.println();
3
System.out.println("Coffee Name:
4
System.out.println("Supplier ID:
5
System.out.println("Price
:
6
System.out.println("Sales
:
7 }

2-34

"
"
"
"

+
+
+
+

rs.getString(1));
rs.getInt(2));
rs.getFloat(3));
rs.getInt(4));

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Step 6 Closing Down JDBC Objects


After each connection and retrieval of data, close down the following
JDBC objects:

Connection Disconnects from the database in a controlled


manner.

Statement Detaches the statement from its previous business


function

ResultSet Deallocates JDBC-based resources.

None of the three are reusable after closing.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

2
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:

Select an appropriate method to register a JDBC driver

Establish a database connection with the registered JDBC driver

Query a database using the JDBC connection

Select the appropriate type of statement given the data query


requirements

Manipulate data in the database using a JDBC connection

Process the results of a query

Shut down the appropriate objects after a JDBC process is


complete

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

OOAD and Database Design

Objectives
Upon completion of this module, you should be able to:

Describe the purpose of an object ID

Describe two ways to create an object ID

Given a class diagram, map objects to a relational database

Given a class diagram, map object relationships in the database

This module covers the design issues associated with object-oriented


applications.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

3
References
Additional resources The following resources can provide
additional detail on the topics presented in this module:

Object-relational mapping strategies. [Online.] Available:


http://www.objectmatter.com/vbsf/docs/maptool/
ormapping.html

Ambler, Scott W. Mapping Objects to Relational Databases. [Online.]


Available: http://www.ambysoft.com/mappingObjects.pdf

Yoder, Joseph W., Ralph E. Johnson, Quince D. Wilson. Connecting


Business Objects to Relational Databases. [Online.] Available:
http://jerry.cs.uiuc.edu/~plop/plop98/
final_submissions/P51.pdf

Keller, Wolfgang. Mapping Objects to Tables: A Pattern Language.


[Online.] Available:
http://www.sdm.de/g/arcus/publicat/mapo2t.ps

OOAD and Database Design

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:

How you will uniquely identify each row in the database

How the database tables will relate to the objects in your


application

How the database tables will relate to each other

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

OOAD and Database Design

3-5

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Object IDs and Primary Keys


Using primary keys has the advantage of being easy to implement and
maintain. OIDs, on the other hand, must be generated and maintained
outside of individual tables. However, there are several advantages, to
offset the extra maintenance:

OIDs can transcend individual tables.


Unlike indexes, OIDs can be generated for every object to be
stored in the database, rather than only being unique for each
table. The result is that you can store the unique OID for every
object in the database, regardless of its table mapping, and have a
simple, efficient way to retrieve all of the data for any object in
your system.

3-6

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

3
Object IDs and Primary Keys

OIDs can transcend databases.


In more complex architectures, client applications can access
different database servers over time. In such a system, you can
generate unique OIDs for multiple databases, and therefore know
that the object ID was truly unique across all of the applications.
This is an important issue if data is shared among databases.

OIDs simplify mapping of an object to a table or multiple tables


(mapping is described later in the Object-Relational Mapping
section on page 3-15).
If an object is mapped to multiple tables, you must join the tables
to retrieve the object. This is easily done with an OID. Without the
OID, you would have to create or use an existing attribute to link
the tables together.

OIDs do not have unnecessary ties to business meaning


Primary keys are often based on the content of the record. For
example, an employee ID is the primary key for the employee
table and uniquely identifies each employee. The employee
number field has a set format, such as XX-MMDDYY-1234. The
format has business meaning; the first part could identify the
employees department, the second could specify the employees
start date, and the third a unique number assigned to the
employee.
However, the departments can change and be identified with three
letters, or the company might grow so that the last part of the ID
needs to be longer to make the IDs unique. In this case, the format
of the ID must change, so the tables must change. An OID does
not need to change when the business changes.
If the employee ID were based on department, start date, and
clearance, two employees might have the same ID, and developers
would need to add business logic to ensure thatthis would not
happen. With OIDs, this is not a consideration, because they have
no business meaning and are automatically guaranteed to be
unique.

OOAD and Database Design

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Object IDs and Primary Keys


You can make an OID unique within a class, unique within a class
hierarchy, or unique across all classes.

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.

OOAD and Database Design

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

It could be faster to generate OIDs (because you generate a


unique OID for each table. You are not tying up the entire
database when you create an OID, you are just locking that
specific table)

You generate separate OIDs for each table, so there will


probably be duplicate values for the tables. This means that if
you have a row entry for an employee who then becomes a
customer, you must work out a strategy to map between the
customer and employee tables in the database. You cannot
assume that you can carry over the OID from the employee
table, because it is entirely possible that the OID has already
been assigned to a different record in the customer table.

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.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Creating Object IDs


You can use the following approaches to calculate OIDs.

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.

OOAD and Database Design

3-11

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Creating Object IDs


High/Low
With the high/low approach, the OID is a String composed of two
parts, a high and a low value. By appending the low value to the high,
you create a unique OID for each object.

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.

The second part, or low value, is assigned and incremented by the


application. It is appended to the high value, and is incremented
with each new object. It typically occurs with any save operation;
the value is sometimes incremented using a third value to
distinguish between saves.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

OOAD and Database Design

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

50011 C244SOL Kara

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

OOAD and Database Design

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Object-Relational Mapping
To connect your object model with the database, complete these steps
before you begin defining your database.

Map classes to tables

Map attributes to columns

Map class relationships to tables

OOAD and Database Design

3-17

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Mapping Classes to Tables


Classes map to tables, but usually not directly. With a simple object
model, you can achieve a one-to-one mapping of object to table.
However, most object models are not simple.
Most object models have some inheritance, which causes the most
complexity when mapping classes to tables. There are three
fundamental approaches to mapping class inheritance to a relational
database; you can choose to follow any that meet your needs.

One table for each class

One table for an entire class hierarchy

One table for each concrete class

Note Depending on the method or methods you choose, your object


model can change because you might not need some attributes. These
changes are noted on the following pages.

3-18

In addition, with any of these approaches, you might need to map


two or more classes to one table, if you have created some objects
with very few attributes.

Database Application Programming With Java Technology


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

Mapping One Table for Each Class

OOAD and Database Design

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Mapping Classes to Tables


One Table for Every Class
Advantages

This approach most closely conforms to object-oriented concepts.

It supports polymorphism because an object can have multiple


roles.

It is easy to add an attribute to a class, because you affect only one


table. Maintenance is simple because there is no duplication. You
can quickly create new subclasses by adding an additional table.

OOAD and Database Design

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

There are many tables to maintain.

It takes longer to read and write to the tables, because you might
have to read from multiple tables to create one object.

Reporting without a prepared report becomes extremely difficult


because of all the different tables, though you can alleviate this by
using database views.

Database Application Programming With Java Technology


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

Mapping One Table for Each Concrete Class

OOAD and Database Design

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Mapping Classes to Tables


One Table for Each Concrete Class
Advantages

Reporting directly from tables, without a prepared report, is still


easy, because all the data you need to access is available from one
table per class.

Disadvantages

To modify a class, you must modify its table and the tables for any
subclasses.

Data definitions are duplicated. In the Person abstract class


example, if a Person is both a Customer and an Employee, data for
the Person class is duplicated in both the Customer and Employee
tables. Therefore, the data is difficult to maintain.

OOAD and Database Design

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

Mapping One Table for an Entire Class Hierarchy

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Mapping Classes to Tables


One Table for an Entire Class Hierarchy
Advantages

It is easy to understand how the tables are related.

Polymorphism is supported.

ad hoc reporting (reporting directly from tables without a pre-made


report) is easy. For example, assume there is an abstract Person
class that has subclasses of Employee and Customer. With one
table for the entire class hierarchy, if the Person were to take on
different roles then all the necessary data is available.

OOAD and Database Design

3-27

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Mapping Classes to Tables


One Table for an Entire Class Hierarchy
Disadvantages

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.

It is difficult and costly to enforce rules on the database. Business


rules needed for only some fields are applied to all fields in the
row, and the rules can conflict, slow performance, or both.

Each time you add a new attribute anywhere in the class


hierarchy, the database table requires a change.

When you add a new column, if it cannot have a null value, you
must update all records with a value for that column.

Routine maintenance, such as removing damaged rows, takes


longer.

Many operations need to access the same table, which can reduce
performance.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

line2 city state postcodeOID postalCode

Mapping Two Classes to One Table

OOAD and Database Design

3-29

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Mapping Classes to Tables


Mapping Two Classes to One Table
Figure 3-5 shows an example of an Address class that has a postal
code. You might want postal code to be a class of its own, so you can
verify that the postal code is valid for a state and city. However, when
you map to the relational table, you would combine the Address and
Postal Code classes into one table.

3-30

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Mapping SQL Types to Java Types

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

OOAD and Database Design

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Mapping Class Relationships to Tables


Now that you have mapped the classes to tables, you need to map the
object relationships to tables in the database.
Foreign keys are used to reference a row in another table, to implement
class relationships in their corresponding tables. If you store the
primary key from table A in table B, that primary key is a foreign key
for table A.
To implement the one-to-one or one-to-many relationships in an object
model, you need a primary key in one table and a foreign key in the
other. If you use the OID as the primary key, then that OID becomes a
foreign key in the related table.

OOAD and Database Design

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Mapping Class Relationships to Tables


One-to-One Relationships
Figure 3-6 shows an example of the relationship between a Car class
and an Engine class, with a corresponding table for each. It is a one-toone relationship where the Car OID would be in the Engine table as a
foreign key, or the Engine OID would be in the Car table as a foreign
key.

OOAD and Database Design

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

One-to-Many Relationship Mapping

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Mapping Class Relationships to Tables


One-to-Many Relationships
In an order entry program, for example, there are many line items for
each order, so the orderOID is added to the OrderLine table. Add the
orderLineOID to the Order table because you need an array in the
Order table to handle all the orderLineOIDs that are associated with
the order.

OOAD and Database Design

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

CustomerAddress table (join table)


addrOID

custOID

Many-to-Many Relationship Mapping

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Mapping Class Relationships to Tables


Many-to-Many Relationships
Figure 3-8 show the relationship of Address to Customer; a Customer
can have many Addresses and an Address can belong to many
Customers. In this case, you can use a join table, such as
CustomerAddress, to link the class attributes.

OOAD and Database Design

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

Join Table in Many-to-Many Relationship

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

OOAD and Database Design

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

3
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:

Describe the purpose of an object ID

Describe two ways to create an object ID

Given a class diagram, map objects to a relational database

Given a class diagram, map object relationships in the database

OOAD and Database Design

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

JDBC Advanced Topics

Objectives
Upon completion of this module, you should be able to:

Write code to catch exceptions in JDBC processes

View metadata for a table or result set

Create transactions

Use concurrency control to determine how data is read and


changed

This module describes the JDBC 1.0 topics of exception handling,


metadata, transactions, and concurrency control.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Exceptions
Overview
When a Java application communicates with the database, the
following elements are present:

The application

The JDBC code, which takes requests from the application,


translates them to queries, then executes them on the server

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.

JDBC Advanced Topics

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

JDBC-server communication, such as physical problems with the


connecting cable

Incorrectly formatted commands

Use of unsupported functions

Referencing records that do not exist

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC Advanced Topics

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Result set metadata

JDBC Advanced Topics

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC Advanced Topics

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

4
Transactions
JDBC Transaction Methods
To perform transactions in JDBC, perform the following steps:

Call the setAutoCommit method with a boolean value of false.


This method allows you to turn on or off the default commit
process. In standard data manipulation, a connection by default
has auto-commit enabled. This means that every SQL statement is
considered a transaction and is committed upon successful
completion of the SQL statement. setAutoCommit(false) turns
off auto-commit mode.

Perform one or more operations on the database. For transactions,


you can perform SQL INSERT, DELETE, and UPDATE operations.
You can do this using the executeUpdate method (available for
Statement, PreparedStatement and CallableStatement).

To finalize the changes, call the commit method. Calling the


commit method on the connection makes all changes that have
been made since the previous commit/rollback permanent and
releases any database locks currently held by the Connection.
This method should be used only when auto-commit mode has
been disabled.

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.

Note Put a rollback in a catch block when performing exception


handling in transactional code.

JDBC Advanced Topics

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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:

Dirty reads When a row changed by one transaction is read by


another transaction before any changes in that row have been
committed.

Non-repeatable reads When one transaction reads a row, a


second transaction alters the row, and the first transaction rereads
the row, getting different values the second time.

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.

JDBC Advanced Topics

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

TRANSACTION_NONE Indicates that transactions are not


supported. This is typically used to test whether a driver or
database supports transactions.

TRANSACTION_READ_UNCOMMITTED Allows dirty reads,


non-repeatable reads, and phantom reads. If any of the changes
are rolled back, the second transaction will have retrieved an
invalid row.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

4
Transactions
Concurrency Control

TRANSACTION_READ_COMMITTED Prevents dirty reads.


Non-repeatable reads and phantom reads can occur.

TRANSACTION_REPEATABLE_READ Prevents dirty reads and


non-repeatable reads. Phantom reads can occur.

TRANSACTION_SERIALIZABLE Prevents dirty reads, nonrepeatable reads, and phantom reads.

JDBC Advanced Topics

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC Advanced Topics

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

4
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:

Write code to catch exceptions in JDBC processes

View metadata for a table or result set

Create transactions

Use concurrency control to determine how data is read and


changed

JDBC Advanced Topics

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

JDBC 2.0 Core Features

Objectives
Upon completion of this module, you should be able to:

List the new features in the JDBC 2.0 Core API

Explain how to scroll forward and backward within a result set

Understand how to use a scroll cursor to process the results of a


query

Use a scroll cursor to manipulate data in the database

Describe how to perform batch processing with statements

List the new data types added to JDBC 2.0

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Enhancements to the JDBC 2.0 API


JDBC 2.0 has two sets of enhancements.

The JDBC 2.0 Core API


Based on current Java technology features, and provided in the
java.sql package. These features are covered in this module.

The JDBC 2.0 Standard Extension API


Based on extended Java technology features not included in the
Java 2 Standard Edition, and provided in the javax.sql package.
These features are covered in Module 6, JDBC 2.0 Standard
Extensions.

JDBC 2.0 Core Features

5-3

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Enhancements to the JDBC 2.0 API


Core API Enhancements
These features are almost all required to be implemented by driver
vendors who want to be JDBC 2.0 compliant.
JDBC 2.0 is a superset of JDBC 1.0. The classes and interfaces in the
java.sql package works for database drivers for either specification,
provided that you do not try to use the expanded JDBC 2.0
functionality with a JDBC 1.0 driver. Core API features in the JDBC 2.0
include:

Result set enhancements

Scrollability

Updatability

Enhancements to Statement, CallableStatement, and


PreparedStatement, for batch updates

Advanced JDBC data types to support SQL3

Each of these features is covered in more detail in this module.


5-4

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Result Set Enhancements


The JDBC 2.0 API includes two types of enhancements for result sets.

Scrollability

Allows you to scroll forward and backward within a result set

Enables absolute and relative positioning

Updatability Allows you to manipulate data using a scroll cursor

Note JDBC driver vendors are not required to implement these


enhancements to be designated as JDBC 2.0 compliant.

JDBC 2.0 Core Features

5-5

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Result Set Enhancements


Scrollability
Scroll Settings
In JDBC 1.0, a ResultSet was forward only. In JDBC 2.0, a ResultSet
can be any of the following:

Forward-only

Scroll-insensitive

Scroll-sensitive

The forward-only mode matches the functionality provided in JDBC


1.0.

5-6

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

5
Result Set Enhancements
Scrollability
Scroll Settings
Scroll-sensitive and scroll-insensitive result sets differ in two ways
from the JDBC 1.0 functionality.

You can move forward or backward within the ResultSet.

You can specify whether the ResultSet displays changes made


while it is open (scroll-sensitive) or whether it does not (scrollinsensitive).

A scroll-sensitive ResultSet provides a dynamic view of the


database. This means that while your ResultSet is open, any
changes that clients make to the rows in the database also
show up in your ResultSet.

The scroll-insensitive ResultSet is generally not sensitive to


changes that are made to the database data while it is open. It
is a static view of the underlying database, meaning the order
of rows and column values are set at the time of creation.

Use the Statement.getResultSetType method to determine what a


result sets scrolling type is currently set to.

JDBC 2.0 Core Features

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

The concurrency mode for a


ResultSet object that you can not
update.

CONCUR_UPDATABLE

static int

The concurrency mode for a


ResultSet object that you can
update. You can update, insert,
and delete rows in an updatable
result set.

FETCH_FORWARD

static int

The rows in a result set are


processed in a forward direction;
first-to-last.

FETCH_REVERSE

static int

The rows in a result set are


processed in a reverse direction;
last-to-first.

FETCH_UNKNOWN

static int

The order in which rows in a result


set are processed is unknown.

TYPE_FORWARD_ONLY

static int

The type for a ResultSet object


whose cursor can move only
forward.

TYPE_SCROLL_INSENSITIVE

static int

The type for a ResultSet object


that is scrollable but not sensitive
to changes made by others.

TYPE_SCROLL_SENSITIVE

static int

The type for a ResultSet object


that is scrollable and sensitive to
changes made by others.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

JDBC 2.0 Core Features

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Result Set Enhancements


Scrollability
Positioning
A ResultSet can also support absolute and relative positioning.
Absolute positioning is the ability to move directly to a row by
specifying its position in the ResultSet. Relative positioning is the
ability to move to a row by specifying a new row that is forward a
given number of rows from the current row position.

JDBC 2.0 Core Features

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

Moves the cursor to the given row


number in the result set.

afterLast()

void

Moves the cursor to the end of the


result set, just after the last row.

beforeFirst()

void

Moves the cursor to the front of the


result set, just before the first row.

first()

boolean

Moves the cursor to the first row in


the result set.

last()

boolean

Moves the cursor to the last row in


the result set.

next()

boolean

Moves the cursor down one row


from its current position.

previous()

boolean

Moves the cursor to the previous


row in the result set.

relative(int)

boolean

Moves the cursor a relative


number of rows, either positive or
negative.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Methods for Maneuvering Within the ResultSet

Method

Type

Description

isAfterLast()

boolean

Indicates whether the cursor is


after the last row in the result set.

isBeforeFirst()

void

Indicates whether the cursor is


before the first row in the result set.

isFirst()

void

Indicates whether the cursor is on


the first row of the result set.

isLast()

boolean

Indicates whether the cursor is on


the last row of the result set.

JDBC 2.0 Core Features

5-13

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Result Set Enhancements


Updatability
Updatability allows you to manipulate data using the ResultSet scroll
cursor. This provides the capability of using one query to read
multiple rows from a database, then update rows in the database one
at a time. You can update, delete, and insert rows.
You can update a result set if the concurrency type is
CONCUR_UPDATABLE. You can use the
Statement.getResultSetConcurrency method to determine what a
result sets concurrency type is currently set to. The statement
constructor allows you to set the concurrency type. Table 5-1 on page
5-8 lists concurrency types.

5-14

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Core Features

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

Inserting a New Row


To insert a new row, use the method moveToInsertRow to position the
cursor at the next empty row for creating the context of a new row.
Use the same updateXXX methods to set the values of specific columns
of the insert row before inserting it into the database with insertRow.
A ResultSet tracks the previous cursor position while the cursor is
temporarily positioned at the insert row, and the cursor is
automatically returned to that cursor position after the insert is
completed.
Syntax
Write an updateXXX statement for each column to update.

resultsetRefVar.movetoInsertRow();
resultsetRefVar.updateXXX(column, value);
resultsetRefVar.insertRow();

5-16

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

JDBC 2.0 Core Features

5-17

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Result Set Enhancements


Updatability
Restrictions
Due to differences in database implementations, the JDBC 2.0 API
does not specify an exact set of SQL queries that yield an updatable
result set. This is regardless of whether concurrency is set to
CONCUR_UPDATABLE.
Queries that meet the following criteria can produce an updatable
ResultSet. Other scenarios depend on the JDBC driver vendors
implementation.

5-18

The query references only a single table.

The query does not contain any join operations.

The query selects the primary key of the table.

The query selects all of the non-nullable columns in the table, and
all columns that do not have a default value.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Statement Enhancements for Batch Updates


The batch update feature allows you to submit multiple SQL
commands to a database for processing at once. Submitting multiple
updates together, instead of individually, can greatly improve
performance in some situations.
The JDBC API cannot perform any operation during batch processing
that would produce a result set; if a result set is produced, an
exception is thrown. This ensures that you do not write code that can
generate multiple ResultSet objects during batch operations. Any
attempt to execute a ResultSet that produces a JDBC action during
batch operations results in an exception.
You can use the following to submit batch updates:

Statement

PreparedStatement

CallableStatement

JDBC 2.0 Core Features

5-19

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Statement Enhancements for Batch Updates


Statement
The batch update feature allows a Statement object to submit a set of
heterogeneous update commands together as a single unit, or batch, to
the underlying DBMS. In the following example, all of the update
operations required to insert a new employee record into a company
database are submitted as a single batch.
Syntax
Statement stmtRefVar = conRefVar.createStatement();
stmtRefVar.addBatch(sqlString);
// submit a batch of update commands for execution
intArrayRefVar = stmtRefVar.executeBatch();

5-20

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Core Features

5-21

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Statement Enhancements for Batch Updates


Statement
In JDBC 2.0, a Statement object can keep track of a list of commands
that can be submitted together for execution. When a statement is
created, its associated list of commands is empty. The
Statement.addBatch method adds an element (a SQL command) to
the calling statements list of commands.
A SQLException is thrown when Statement.executeBatch is called
if the batch contains a command that attempts to return a result set.
Only Data Definition Language (DDL) and Data Manipulation
Language (DML) commands that return a simple update count can be
executed as part of a batch. You can call the method
Statement.clearBatch to reset a batch if the application decides not
to submit a batch of commands that has been constructed for a
statement.

5-22

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Core Features

5-23

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Statement Enhancements for Batch Updates


PreparedStatement
The batch update feature is used with prepared statements to associate
multiple sets of input parameter values with a single
PreparedStatement object. The sets of parameter values can then be
sent to the underlying DBMS engine for execution as one unit.
The following example inserts two new employee records into a
database as a single batch. The PreparedStatement.setXXX methods
create each parameter set (one for each employee), and the
PreparedStatement.addBatch method adds a set of parameters to
the current batch.

5-24

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Core Features

5-25

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Statement Enhancements for Batch Updates


CallableStatement
The batch update feature works the same way with
CallableStatement objects as it does with PreparedStatement
objects. You can associate multiple sets of input parameter values with
a callable statement and send them to the DBMS together.
Stored procedures invoked using the batch update facility with a
callable statement:

Must return an update count

Cannot have out or inout parameters

This means that you can perform batch operations on


CallableStatement objects, such as database stored procedures, but
you cannot have any values in the CallableStatement that can
potentially be output. The CallableStatement.executeBatch
method should throw an exception if this restriction is violated.

5-26

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Advanced Data Types


Overview
The data types commonly referred to as SQL3 types are the new data
types being adopted in the next version of the ANSI/ISO standard
(American National Standards Institute/International Organization for
Standardization). The JDBC 2.0 API provides interfaces that represent
the mapping of these SQL3 data types into the Java programming
language. With these new interfaces, you can work with SQL3 data
types the same way you do other data types.
The new SQL3 data types give a relational database more flexibility in
what can be used as a type for a table column. For example, you can
now use a column to store the new type BLOB (binary large object),
which can store large amounts of data as raw bytes. A column can also
be of type CLOB (character large object), which can store large amounts
of data in character format. The new type ARRAY makes it possible to
use an array as a column value. The new SQL user-defined types,
structured types, and distinct types, can now be stored as column
values.

JDBC 2.0 Core Features

5-27

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Advanced Data Types


Overview
The following list includes the JDBC 2.0 interfaces that map the SQL3
types.

5-28

A Blob instance maps a SQL BLOB instance (stores a large amount


of binary data, such as images, audio files, and objects; size is
typically database specific).

A Clob instance maps a SQL CLOB instance (stores a large amount


of text data, such as documents and large strings; size is typically
database specific).

An Array instance maps a SQL ARRAY instance.

A Struct instance maps a SQL structured type instance.

A Ref instance maps a SQL REF instance.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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 Types and Corresponding Methods

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

REF (structured type)

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.

JDBC 2.0 Core Features

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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 }

JDBC 2.0 Core Features

5-31

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Advanced Data Types


Blob, Clob, and Array Objects
An important feature of Blob, Clob, and Array objects is that you can
manipulate them without having to bring all of the data from the
database server to your client machine. An instance of any of these
types is actually a logical pointer to the object in the database that the
instance represents. A SQL BLOB, CLOB, or ARRAY object can be large, so
this feature can improve performance dramatically.
You can use SQL commands and the JDBC 1.0 and 2.0 API with Blob,
Clob, and Array objects just as if you were operating on the actual
object in the database. However, if you want to work with any of them
as an object in the Java programming language, you need to bring all
their data to the client, which is referred to as materializing the object.

5-32

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Core Features

5-33

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Advanced Data Types


Structured Types and Distinct Types
SQL structured types and distinct types are the two data types that a
user can define in SQL. They are often referred to as UDTs (userdefined types), and you create them with a SQL CREATE TYPE
statement.

5-34

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Advanced Data Types


Structured Types
A SQL structured type is similar to structured types in the Java
programming language in that it has members, called attributes, that
can be of any data type. In fact, an attribute can be another structured
type.
This example shows a simple definition creating a new SQL data type:
1 CREATE TYPE PLANE_POINT
2 (
3
X FLOAT,
4
Y FLOAT
5 )

JDBC 2.0 Core Features

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Advanced Data Types


Distinct Types
The second SQL type that a user can define in a SQL CREATE TYPE
statement is a distinct type. A SQL distinct type is similar to a typedef
in C or C++ because it is a new type based on an existing type. The
following is an example of creating a distinct type.
CREATE TYPE MONEY AS NUMERIC(10, 2)
This definition creates the new type called MONEY, which is a number of
type NUMERIC that is always base 10 with two digits after the decimal
point. MONEY is now a data type in the schema in which it was defined,
and you can store instances of MONEY in a table that has a column of
type MONEY.

JDBC 2.0 Core Features

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Advanced Data Types


SQL3 Advanced Features
The Struct interface is the standard mapping for a SQL structured
type. To make working with a SQL structured type easier, you can
map it to a class in the Java programming language. The structured
type becomes a class, and its attributes become fields. You do not have
to use a custom mapping, but it is often more convenient.
You might want to work with a logical pointer to a SQL structured
type rather than with all the values contained in the structured type.
This might be true, for example, if the structured type has many
attributes or if the attributes are themselves large. To reference a
structured type, you can declare a SQL REF type that represents a
particular structured type. A SQL REF object is mapped to a Ref object
in the Java programming language, and you can operate on it as if you
were operating on the structured type object that it represents.

JDBC 2.0 Core Features

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

JDBC 2.0 Core Features

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

List the new features in the JDBC 2.0 Core API

Explain how to scroll forward and backward within a result set

Understand how to use a scroll cursor to process the results of a


query

Use a scroll cursor to manipulate data in the database

Describe how to perform batch processing with statements

List the new data types added to JDBC 2.0

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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?

JDBC 2.0 Core Features

5-43

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

JDBC 2.0 Standard Extensions

Objectives
Upon completion of this module, you should be able to:

List the features in the JDBC 2.0 Standard Extension API

Understand how to use Java Naming and Directory Interface


functionality to reduce the dependence of a JDBC program on a
particular driver

Describe how connection pooling is used to connect an application


to a database

Understand how distributed transactions work

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

6
References
Additional resources The following resources can provide
additional detail on the topics presented in this module:

javax.sql package download page and JDBC 2.0 Standard


Extension API. [Online.] Available:
http://java.sun.com/products/jdbc/download.html

JNDI Documentation page. [Online.] Available:


http://java.sun.com/products/jndi/docs.html

Java Transaction API (JTA) Specification. [Online.] Available:


http://java.sun.com/products/jta/index.html

Java Transaction Service (JTS) Specification. [Online.] Available:


http://java.sun.com/products/jts/index.html

Enterprise JavaBeans Specification. [Online.] Available:


http://java.sun.com/products/ejb/docs.html

JDBC 2.0 Standard Extensions

6-3

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Standard Extension Enhancements to the JDBC 2.0 API


These features are optional and driver vendors are not required to
implement them. The features are included in the javax.sql package,
which is included in the Java 2 Platform, Enterprise Edition, and also
from the following site.
http://java.sun.com/products/jdbc/download.html
Standard extension API changes with JDBC 2.0 include:

Support for JNDI

Connection pooling

Distributed transactions

Row sets

Each of these features is covered in more detail in this module.

6-4

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

The second program references that data source name.

This makes changing the driver easier, because you need to change it
in only one place.

JDBC 2.0 Standard Extensions

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

public interface DataSource {


Connection getConnection() throws SQLException;
Connection getConnection(String username, String password) throws
SQLException;
...
}
Like other interfaces in the JDBC API, such as java.sql.Connection
and java.sql.ResultSet, implementations of
javax.sql.DataSource are provided by JDBC driver vendors as part
of their JDBC 2.0 products.

6-8

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Standard Data Source Properties

Property Name

Type

Description

databaseName

String

Name of a database on a server

dataSourceName

String

Name of the class that


implements the data source
functionality

description

String

Description of this data source

networkProtocol

String

Network protocol used to


communicate with the server

password

String

A database password

portNumber

int

Port number where a server


listens for requests

roleName

String

The initial SQL role name

serverName

String

Database server name

user

String

Users account name

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Standard Extensions

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

DataSourceClass is a class provided by a vendor.


DataSourceClass dataSourceRefVar = new DataSourceClassConstructor();
dataSourceRefVar.mutatorMethod(serverName);
dataSourceRefVar.accessorMethod(databaseName);
Context contextRefVar = new InitialContext();
contextRefVar.bind (logicalDatasource, dataSourceRefVar);

6-12

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

6
JNDI
Registering a DataSource Object
Example
This example registers a data source object with a JNDI naming
service.
1
2
3
4
5

SampleDataSource sds = new SampleDataSource();


sds.setServerName("akron");
sds.setDatabaseName("accounts-payable");
Context ctx = new InitialContext();
ctx.bind("jdbc/AccountMain", sds);
The first line of code in the example creates a data source object. The
SampleDataSource class implements the javax.sql.DataSource
interface. (A JDBC driver vendor supplies the SampleDataSource
class.) The next two lines initialize the data sources properties. Then, a
Java programming language object that references the initial JNDI
naming context is created by calling the InitialContext constructor,
which is provided by JNDI. System properties (not shown) are used to
tell JNDI the service provider to use.
The JNDI name space is hierarchical; this is similar to the directory
structure of many file systems. The data source object is bound to a
logical JNDI name by calling Context.bind. In this case, the JNDI
name identifies a subcontext, jdbc, of the root naming context and a
logical name, EmployeeDB, within the jdbc subcontext. This code is
sufficient to deploy a data source object within JNDI.
Note This example is provided mainly for illustrative purposes.
Developers or system administrators should normally use a graphical
user interface (GUI) tool to deploy a data source object.

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Three-tier Application Using Connection Pooling

In Figure 6-1, the client portion of the application is shown invoking


some application codefor example, a Java technology servlet that
executes in the middle tier. The middle-tier application code uses the
JDBC API to access a database. The application developer uses the
DataSource interface in the standard way to obtain a Connection
object. The DataSource implementation performs connection pooling
and is implemented, in this case, by the middle-tier server vendor. The
connection pooling implementation uses the features provided by the
JDBC 2.0 driver vendor to implement the connection caching
algorithm that it chooses.
The three parts of this example are performed by the JDBC driver
vendor, the middle-tier server vendor, and the application developer.

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Middle-tier server code


XADataSource
JDBC driver

Tier 2
Figure 6-2

Network

DBMS

Tier 3

Components of Application Using Distributed


Transactions

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Standard Extensions

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.

Disconnected Row Sets


A disconnected row set obtains a connection to a data source to get or
change data in the data source, but most of the time it does not have a
connection open. While it is disconnected, it does not need a JDBC
driver or the full JDBC API, so its footprint is small. A row set is an
ideal format for sending data over a network to a thin client.

6-28

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

Connected Row Sets


A connected row set obtains a connection and keeps it open for as long
as the row set is in use.

JDBC 2.0 Standard Extensions

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

rset = new RowSet();


rset.setDataSourceName("jdbc/SomeDataSourceName");
rset.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
rset.setCommand("SELECT NAME, BREED, AGE FROM CANINE");
This example uses a variable rset of type RowSet, and sets three
RowSet properties: data source name, transaction isolation, and
command. The data source name property is used by a RowSet to look
up a JDBC DataSource object in a JNDI naming service. (JDBC data
sources are the most common type of data source used by row sets.)

6-30

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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 change events indicate that a particular row has been


inserted, updated, or deleted.

Row set change events indicate that the entire contents of a row set
changed. For example, this can happen when RowSet.execute is
called.

JDBC 2.0 Standard Extensions

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

JDBC 2.0 Standard Extensions

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

// iterate forward through the row set


rset.beforeFirst();
while (rset.next()) {
System.out.println(rset.getString(1) + " " + rset.getFloat(2));
}
You iterate backward through the row set, positioning the cursor to a
specific row, and so on in the same way as a result set.

6-36

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC 2.0 Standard Extensions

6-37

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Overview of Row Set Implementation


Most implementations are provided by vendors offering RowSet
classes designed for fairly specific purposes. To make writing an
implementation easier, the Java Software division of Sun Microsystems
plans to provide reference implementations for three different styles of
row sets in the future.

6-38

A CachedRowSet class Currently available from


http://java.sun.com/products/jdbc. It is a disconnected row
set that caches its data in memory; not suitable for large data sets,
but an ideal way to provide thin Java technology clients, such as a
Personal Digital Assistant (PDA) or Network Computer (NC),
with tabular data.

A JDBCRowSet class A connected row set that serves mainly as a


thin wrapper around a ResultSet object to make a JDBC driver
look like a JavaBeans component.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

6
Overview of Row Set Implementation

A WebRowSet class A connected row set that uses the HTTP


protocol internally to talk to a Java technology servlet that
provides data access. This is used to make it possible for thin Web
clients to retrieve and possibly update a set of rows.

CachedRowSet is described in Module 7, Row Set Implementation.


JDBCRowSet and WebRowSet are not covered, but are listed here to
give a preview of the types of row set implementations that will likely
be available in the future.

JDBC 2.0 Standard Extensions

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

List the features in the JDBC 2.0 Standard Extension API

Understand how to use Java Naming and Directory Interface


functionality to reduce the dependence of a JDBC program on a
particular driver

Describe how connection pooling is used to connect an application


to a database

Understand how distributed transactions work

Explain how to use row sets to encapsulate rows for use with the
JavaBeans component model

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

6
Think Beyond
What elements might be necessary in an implementation of the
CachedRowSet class?

JDBC 2.0 Standard Extensions

6-41

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Row Set Implementation

Objectives
Upon completion of this module, you should be able to:

Explain how to use the CachedRowSet implementation

Modify a RowSetReader or RowSetWriter

Understand the benefit provided by using the CachedRowSet


implementation

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

CachedRowSet Class Overview


The CachedRowSet class is similar to row set implementations that
provide a disconnected, serializable, scrollable container for tabular
data. You can think of a CachedRowSet object as a disconnected set of
rows that are being cached outside of a data source. Because all data is
cached in memory, CachedRowSets are not appropriate for extremely
large data sets.
Note The CachedRowSet implementation is available at
http://java.sun.com/products/jdbc

Row Set Implementation

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.

You can pass a CachedRowSet between different components in a


distributed system.
Figure 7-1 shows that you can use a CachedRowSet to provide Java
technology clients with access to tabular data in situations where it
would be inappropriate to use a JDBC driver directly in the client
due to resource limitations or security considerations.

Java client

Tier 1

RMI/CORBA
CachedRowSet
Tier 2
JDBC

DBMS

Figure 7-1

7-4

Tier 3

CachedRowSet Architecture

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

7
CachedRowSet Class Overview

CachedRowSets can also provide scrolling and updating for


ResultSets that do not provide these capabilities themselves. You
can use a CachedRowSet to augment the capabilities of a JDBC
driver that does not have full support for scrolling and updating.

Row Set Implementation

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Row Set Implementation

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

// There is already a connection associated


// with the CachedRowSet
CachedRowSet crset = new CachedRowSet();
crset.setCommand(
"SELECT year, model FROM car WHERE manufacturer = FORD");
5 crset.execute();

Row Set Implementation

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

Row Set Implementation

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

Row Set Implementation

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

Row Set Implementation

7-15

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Reading and Writing Data


Overview
The row set framework provides an extensible reader/writer facility
that allows you to customize data retrieval and updating, for complex
or specialized situations.The CachedRowSet class uses this facility.
Custom readers and writers are useful because they can enable a
RowSet to read its data from a regular file data source or from some
other non-SQL data source, such as a spreadsheet.
This approach separates where you get data from, and what you do
with it.
You can make a CachedRowSet style implementation that has been
configured with a custom reader/writer available as a normal
JavaBeans component. Therefore, developers writing applications can
generally ignore the details of the customization process and focus on
more important aspects of using row sets.

7-16

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Reading and Writing Data


Overview
When an application calls the CachedRowSet.execute method:

The CachedRowSet invokes an object that implements the


RowSetReader interface internally to handle the task of reading
data from a data source.

The RowSetReader interface provides a single method, readData,


which is called to read the new contents of the row set.

A CachedRowSet object exposes itself as an object of type


RowSetInternal to the RowSetReader.The RowSetInternal
interface contains some additional methods that are needed by the
RowSetReader to do its work.

Row Set Implementation

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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*

*A database, spreadsheet, or other source of data


Figure 7-2

RowSetReader and RowSetWriter Interaction

Row Set Implementation

7-19

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Reading and Writing Data


RowSetReader
Refer to Appendix C of the JDBC 2.0 Standard Extension API (file name
jdbc20stdext.pdf), included in the specifications directory in your
lab files for this course, for an example of a RowSetReader
implementation.
The example in the appendix uses JDBC to read data from a SQL
database. A row set that supports the reader/writer paradigm should
implement the RowSetInternal interface and pass a reference to itself
when invoking the readData method.
The example readData method uses the calling row sets properties to
create a Connection to a data source. A PreparedStatement is
created using the command property and the PreparedStatement is
passed any properties that were set on the row set.

7-20

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

Row Set Implementation

7-21

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Reading and Writing Data


RowSetWriter
Refer to Appendix D of the JDBC 2.0 Standard Extension API (file name
jdbc20stdext.pdf), included in the specifications directory in your
lab files for this course, for an example of a RowSetWriter
implementation.
This writer works in conjunction with the reader shown in the
previous section. The writer enforces an optimistic concurrency control
policy that requires a row in the database to be unchanged for it to be
updated. For simplicity, some details are not shown.
The writer calls the reader to create a Connection, and to find out if it
needs to reset itself. This might be necessary if new data has been read
since the command used to read the data might have changed. The
writer iterates through each row of the row set and updates the
underlying database when necessary.

7-22

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

Row Set Implementation

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

7
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:

Explain how to use the CachedRowSet implementation

Modify a RowSetReader or RowSetWriter

Understand the benefit provided by using the CachedRowSet


implementation

Row Set Implementation

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

JDBC and Application Architecture

Objectives
Upon completion of this module, you should be able to:

Define the components in a multi-tier application

Explain which components belong to each tier in a multi-tier


application

Explain where JDBC components should be installed in a multitier application

Describe when to use a two-tier application architecture in a


database application

Describe when to use a three-tier application architecture

Describe when to use an n-tier application architecture

This module explores the issues associated with multi-tier database


application design and JDBC.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

8
References
Additional resources The following reference can provide additional
details on the topics discussed in this module:

Balick, Fritzinger, and Siegel. 1996. Effective 3-tiered Engineering.


SunSoft, Sun Microsystems Inc.

Fritzinger, Steve, Dan Berg. 1997. Advanced Java Programming


Techniques. Wiley.

JDBC and Application Architecture

8-3

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Tiered Application Architecture Overview


A tier is a software module that supplies some part of functionality for
a full application. A tier can be, but is not always, a standalone
program, and resides on a separate machine from other tiers or on the
same machine.
The advantage of dividing parts of a full application into separate tiers
is so that you can change one aspect of the application, such as the
presentation, with minimal impact on other parts, such as how the
data is stored or the business rules.

8-4

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Coordinating Clients Using a Middle Tier

The JDBC API supports multi-tier architectures for database access.

JDBC and Application Architecture

8-5

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Tiers and Components


Distributed applications are frequently characterized in terms of three
logical components, sometimes called layers. Each part of the
application provides certain services and fulfills certain responsibilities
within the architecture.
The following components make up both the two-tier and three-tier
designs, shown in the diagrams in the next section.

8-6

Presentation This component receives the data and data


processing requests. It is the graphical user interface (GUI) or
character-based interface, and is typically in the first tier, the client.

Business logic This component implements business rules, such


as how data must be formatted, or what data must be checked
before you can enter other data. It is typically in the first tier in a
two-tier model, or in the second tier in a three-tier model.

Data This component stores and allows access to the data, and is
typically in the third tier, the server.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC and Application Architecture

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

*You can store business logic on either tier or both tiers


Figure 8-2

Two-Tier Database Design

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

HTTP Hypertext transfer protocol

RMI Remote method invocation

CORBA Common object request broker architecture

TCP/IP (sockets) Transmission control protocol/Internet


protocol

UDP User datagram protocol

JDBC and Application Architecture

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

It enables using secure socket classes, caching data, and managing


business rules separately.

It enables the rules to be created once and then kept in a single,


easily maintained location.

It allows you to use database connection pooling.

You can manage connections among multiple data sources.

It enables data synchronization.

It simplifies the client requirements. A Web client needs no JDBC


code or driver, only the capability of using HTTP 1.0.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC and Application Architecture

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

Three-Tier Database Design

For greater security, do not include SQL and the business logic on the
client.

8-12

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

Vertically Adds tiers between client and server to further


subdivide the functionality of the middle layer in the architecture.
The vertical n-tier architecture can be thought of as a way to
augment the application capabilities. If the interface between the
tiers is sufficiently well planned, you can add new functionality
with a minimum amount of rework.

JDBC and Application Architecture

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

Vertical N-Tier Architecture

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

8
N-Tier Architecture

Horizontally Creates additional parts of client functionality that


can be managed by a server or servers, and breaks these out into
additional tiers. An example, shown in Figure 8-5, is a client that
requests a different service from a different server, such as a print
server.

First tier
Client

Second tier

Application server

Print server

Third tier
DBMS

Figure 8-5

Horizontal N-Tier Architecture

JDBC and Application Architecture

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

In a three-tier or n-tier application, you would need to install the


driver code on only one or two application servers (the middle tier
of a three-tier application).

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.

JDBC and Application Architecture

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

JDBC and Application Architecture

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

Define the components in a multi-tier application

Explain which components belong to each tier in a multi-tier


application

Explain where JDBC components should be installed in a multitier application

Describe when to use a two-tier application architecture in a


database application

Describe when to use a three-tier application architecture

Describe when to use an n-tier application architecture

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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?

JDBC and Application Architecture

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:

Define database and database management system (DBMS)

Identify three major DBMS categories

Describe major characteristics of relational databases

Describe guidelines for partitioning work into transactions

Explain the importance of SQL

Query a database using the SQL statement SELECT

Modify database contents using the SQL statements INSERT,


UPDATE, and DELETE

This appendix describes database concepts, introduces commonly


used database management systems, and presents characteristics of
relational database management systems. Use these concepts when
writing SQL queries, and when designing databases for your Java
application.

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

Bowman, Judith S., Sandra L. Emerson, Marcy Darnovsky. 1996.


The Practical SQL Handbook: Using Structured Query Language.
Addison-Wesley.

Melton, Jim, Alan Simpson. 1993. Understanding the New SQL. San
Francisco: Morgan Kauffman Publishers.

Codd, E. F. Is your DBMS really relational? Computerworld, October


14, 1985: 1-9.

Codd, E. F. Does your DBMS run by the rules? Computerworld,


October 21, 1985: 49-64.

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

Create, change, and delete databases

Store, retrieve, and modify data stored in a database

Manage users and user permissions for the database

For data to be stored in a database and managed by a DBMS, three


conditions must be met:

The data must have a format that the DBMS and computer system
understands.

The data should be stored, retrieved, and changed only by the


DBMS.

The data should be under transaction controlthat is, a formal set


of rules should be enforced to ensure the integrity of the data.
For example, when money is transferred from one bank account to
another, it is common to subtract the transfer amount from one
account and add it to the other. If the operation is interrupted after
the subtraction but before the addition, the money would not be in
either account. A DBMS can prevent this from happening by
applying rules to the operations.

Database management systems are categorized according to the


approach they use for storing and managing their data. Most
applications developed today use one of three main kinds of database
management systems:

Relational Database Management System (RDBMS)

Object-Oriented Database Management System (ODBMS)

Object/Relational Database Management System (ORDBMS)

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.

Information must be represented in tables.

The logical representation of data must be independent of its


physical storage characteristics.

A high-level language must be provided to permit structuring,


querying, and changing the data.

This course focused principally on developing Java applications to


interact with RDBMS data sources.

A-4

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

2210 23rd St.

Montclair

NJ

10029

Table A-1 Example Table


In most cases, a column is used in a table to hold values to uniquely
identify records. In this case, the column is referred to as the primary
key for the table.
Additionally, a database record sometimes references one or more
records in other tables. In this case, there must be a column that
contains a value that can be used to reference the other record(s). This
type of column is referred to as a foreign key, because it can be used to
reference records in a different table of the database.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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:

Can you have a customer without an order?

Can you have an order without items?

Can you have a completed order without payment?

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

June Jacobson 1688 Ashley Lk Rd Denver

CO

80022

C7842

Bran Andrews

NJ

10022

678 Zinc Spur

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

Customer table, after:


CustID

Name

Addr

City

State PostalCode

C303

Joe Mays

408 E Sperling

Fargo

ND

58012

C272

Eliza Durham

PO Box 709

Juneau

AK

99821

C7640

June Jacobson 1688 Ashley Lk Rd

Denver

CO

80022

C7842
C8014

Bran Andrews
Agata Omole

678 Zinc Spur

Netcong

NJ

10022

99 W Slade

Kalispell

MT

59901

Figure A-1

Database Basics

Begin Work and Commit Work

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

June Jacobson 1688 Ashley Lk Rd Denver

CO

80022

C7842

Bran Andrews

NJ

10022

678 Zinc Spur

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

June Jacobson 1688 Ashley Lk Rd

Denver

CO

80022

C7842

Bran Andrews

Netcong

NJ

10022

Figure A-2

A-10

678 Zinc Spur

Begin Work and Rollback

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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.

User A opens a customer information window and selects a


record, so the row from the database is read by the program. When
User A opens the record, the Preferred Customer checkbox to set it
to yes.

User B then opens the same record.

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.

Read the timestamp on the row when it is opened.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Data Definition Language (DDL) Used to create and alter the


structure of a database.

Data Manipulation Language (DML) Used for operations, such


as SELECT, INSERT, UPDATE, and DELETE.

SELECT Retrieves zero or more records from a named table

INSERT Adds a new record to a named table

DELETE Removes one or more records from a table

UPDATE Modifies one or more fields of particular records

Transaction control language Provides the ability to perform


commit and rollback actions on a sequence of Data Manipulation
Language commands.

Session control language Used for operations on clients in a


client/server environment.

System control language Used for operations on the server in a


client/server environment.

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

DISTINCT row selection

ORDER BY clauses

Regular expression matching

Column-to-column comparisons in WHERE clauses

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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:

An underscore (_) matches any single character.

A percent sign (%) matches zero or more characters of any value.

A back slash (\) escapes special characters (for example, \%


matches % and \\ matches \).

All other characters match themselves.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Using SQLJ

Objectives
Upon completion of this appendix, you should be able to:

Explain how SQLJ works

Explain the purpose of the SQLJ Translator

Code database queries with SQLJ

Code database manipulation with SQLJ

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

SQLJ Group resources. [Online.] Available:


http://www.sqlj.org

Database Programming in SQLJ: The ANSI Standard for Embedded


SQL in the Java Programming Language. [Online.] Available:
http://industry.java.sun.com/javaone/99/
event/0,1768,616,00.html

Oracle SQLJ resources. [Online.] Available:


http://www.oracle.com/java/sqlj

SQLJ: The open sesame of Java database applications. [Online.]


Available: http://www.javaworld.com/javaworld/
jw-05-1999/jw-05-sqlj.html

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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)

Compiling a SQLJ Program

The SQLJ Translator performs two important functions. It replaces the


static SQL with JDBC calls, and performs SQL syntax-checking,
schema-checking, and type-checking of host variables at the time of
translation. This means that the SQL will work and not generate an
error, if executed against the same database.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

These two steps are completed using


the SQLJ database connection
management feature.

Step 3 Creating a statement

Use the SQLJ clauses and host


variables features to complete this
step.

Step 4 Executing the SQL


Step 5 Processing the results

You can use iterator objects to


complete these two steps.

Step 6 Shutting down objects

Complete this step in the same way


you would for a JDBC application.

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

Database Application Programming With Java Technology


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

/* Copyright (c) 1997 Oracle Corporation */


import java.sql.*;
import sqlj.runtime.ref.DefaultContext;
/**
This is a utility class for establishing SQLJ connections.
**/
public class ConnectionManager {
private static String uid
= "system" ;
private static String pwd
= "manager" ;
private static String dburl =
"jdbc:oracle:thin:@java1.com:1521:stock1";
private static String driver = "oracle.jdbc.driver.OracleDriver";
/**
Creates and returns a new JDBC Connection object.
If an error occurs, an error message is printed to System.err
and the programs exits.
**/
static public Connection newConnection() {
Connection conn = null;
//Verify that the access parameters are defined.
if (uid== null || pwd==null || dburl==null )
{
System.err.println
("Please set DBURL, UID, and PWD, and try again." ) ;
System.exit(1) ;
}
try {
Class driverClass = Class.forName(driver);

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

Database Application Programming With Java Technology


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

Database Application Programming With Java Technology


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

Defining a Host Variable


Syntax
type can be a primitive type or reference type.

type variable
Example
String firstName

Using a Host Variable


Syntax

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

Defining an Iterator Class


Syntax
#sql iterator tableName(type columnName[, type columnName]);
Example
The following code creates an iterator for a SalesRecs table row.
#sql iterator SalesRecs(
int item_number,
String item_name,
Date sales_date,
double cost,
Integer sales_rep_number,
String sales_rep_name );

B-14

Database Application Programming With Java Technology


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

#sql sales = { SELECT item_number,item_name,sales_date,cost,


sales_rep_number,sales_rep_name FROM sales };
while( sales.next() )
{
System.out.println( "ITEM ID: " + sales.item_number() );
System.out.println( "ITEM NAME: " + sales.item_name() );
System.out.println( "COST: " + sales.cost() );
System.out.println( "SALES DATE: " + sales.sales_date() );
System.out.println( "SALES REP ID: " + sales.sales_rep_number() );
System.out.println( "SALES REP NAME: " + sales.sales_rep_name() );
System.out.println();
}
sales.close() ;

Note At this time, SQLJ supports only moving forward within a


result set, like the JDBC 1.0 ResultSet.
To see a complete .sqlj file and the resulting .java file using
iterators, open the lab files directory for this course. Locate the
directory for SQLJ, and open the files named IterDemo1.sqlj and
IterDemo1.java.

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Java Runtime Environment (JRE)


The set of program modules needed to run Java technology on a
computer. This is different than the Java technology plug-in,
which is used to run Java applets on a client Web browser.
JDBC
The Java API used to connect to a database and execute SQL
statements on it. Although JDBC is not an acronym, it is often
referred to as Java Database Connectivity. JDBC has been a
part of the Java programming language since JDK 1.1; to date,
there have been two major releases of the API.
Join
An operation in SQL that involves creating a temporary table
with columns from multiple database tables. The join table can
be used to organize and represent data in ways that go beyond
the physical storage within the relational database. SQL defines
two kinds of joins: outer joins and inner joins. For an inner join,
records that do not match the join criteria are not included in
the result table. An outer join includes records that do not
match join criteria, filling in subsequent fields in the table with
null values.
Layer
A part of an application architecture. The terms layer and tier
are sometimes used interchangeably.
Locking
Preventing multiple users from accessing a specific database
resource. Relational databases typically support row-level
locking, where one or more database records can be modified,
accessed, or both, by only one user at a time.
Metadata
In a relational database, information that describes the tables
and columns in the database.
n-Tier
An architecture for client/server systems. N-tier architectures
extend the concept of three-tier systems, allowing multiple
functional servers to be defined for different functions within
the application. See also two-tier and three-tier.
Object ID (OID)
A way to uniquely identify an object within a database that is
not tied to business meaning.

Glossary

Glossary-3

Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

Object Oriented Database Management System (OODBMS)


A database management system that supports storage and
maintenance of a persistent and sharable collection of objects.
Object Relational Database Management System (ORDBMS)
A hybrid between an RDBMS and an OODBMS. An object
relational database management system is a relational database
management system that provides extended support for object
storage and retrieval. The SQL3 standard defines the extensions
to SQL required to support this model.
Optimistic Locking
A locking strategy, where transactions are allowed to run until
completion. At commit time, a check is made to see if a conflict
occurred. In the case of conflict, the transaction that caused the
conflict is rolled back and restarted.
Pessimistic Locking
A locking strategy where one or more rows in a database table
are locked (unavailable) for the duration of a specific
transaction. During this time, other transactions cannot perform
operations on the locked row or rows.
Primary key
A column in a relational database table used to uniquely
identify records within that table.
Query
In SQL, a request, command, or instruction for the database.
Relational Database Management System (RDBMS)
A kind of database management system that stores its data in
tables 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. RDBMS systems allow data to be
freely organized between the storage tables, providing a flexible
strategy for dynamically relating data elements based on the
needs of an application. Most RDBMS systems define some
form of SQL to provide the capability for clients to perform
operations on the relational database.
Rollback
In a transaction, the act of reversing the previous operations to
restore a database to its previous state. This is also called
backing out of a transaction.

Glossary-4

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Database Application Programming With Java Technology


Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

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

Das könnte Ihnen auch gefallen