Upload
sherifdba
View
59
Download
1
Embed Size (px)
Citation preview
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 1/339
Sun Microsystems, Inc.MS BRM01-209500 Eldorado BoulevardBroomfield, Colorado 80021U.S.A.
®
DatabaseApplicationProgrammingWithJavaTechnology
Revision A.1, October 1999
SL-330
StudentGuide
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 2/339
lease
ecycle
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 documentmay be reproduced in anyform by any meanswithout priorwritten authorization of Sunand 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 trademarksof Sun Microsystems, Inc. in the U.S. and other countries.
All SPARC trademarks are usedunder 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 SunMicrosystems, 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 SunMicrosystems, Inc. for its users and licensees.Sunacknowledges the pioneeringefforts of Xerox in researching and developingthe concept of visual or graphical userinterfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface,which license also covers Sun’s licensees who implement OPEN LOOK GUIs and otherwise comply with Sun’s writtenlicense agreements.
U.S. Government approval required whenexporting 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).
DOCUMENTATIONIS PROVIDED "AS IS" AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS,AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR APARTICULAR PURPOSEOR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCHDISCLAIMERS ARE HELDTO BE LEGALLY INVALID.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 3/339
iiiCopyright1999Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Contents
About This Course ......................................................................................ix
Course Goal .........................................................................................ixCourse Overview ................................................................................. xCourse Map......................................................................................... xiiModule-by-Module Overview....................................................... xiiiCourse Objectives.............................................................................. xviSkills Gained by Module................................................................ xviiGuidelines for Module Pacing ..................................................... xviiiTopics Not Covered.......................................................................... xixHow Prepared Are You?................................................................... xxIntroductions ..................................................................................... xxiHow to Use Course Materials ........................................................ xxii
Course Icons and Typographical Conventions ......................... xxivIcons ......................................................................................... xxivTypographical Conventions ...................................................xxvSyntax Conventions ............................................................... xxvi
JDBC Overview ........................................................................................1-1Objectives ...........................................................................................1-1Relevance............................................................................................ 1-2References .......................................................................................... 1-3What Is the JDBC API? ..................................................................... 1-4Drivers ................................................................................................ 1-7
Overview....................................................................................1-7Type 1 – JDBC/ODBC Bridge Plus ODBC Driver .............1-10Type 2 – Native API................................................................1-12Type 3 – JDBC-Net ..................................................................1-14Type 4 – Native Protocol........................................................1-16Finding Drivers .......................................................................1-18
JDBC Developer Interface.............................................................. 1-19Packages ...................................................................................1-19Classes and Interfaces.............................................................1-20
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 4/339
iv Database A pplication Programming With Java TechnologyCopyright1999Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Identifying a Database Using a URL............................................ 1-24Overview..................................................................................1-24Basic URL Syntax ....................................................................1-26
jdbc...........................................................................................1-27subprotocol ...........................................................................1-28subname ...................................................................................1-30Connecting to a Remote Server.............................................1-31
Check Your Progress ...................................................................... 1-32Think Beyond .................................................................................. 1-33
Using JDBC ................................................................................................2-1Objectives ...........................................................................................2-1Relevance............................................................................................ 2-2Creating a Basic JDBC Application ................................................ 2-3
Step 1 – Registering a Driver ........................................................... 2-6Overview....................................................................................2-6Using the Class Loader...........................................................2-8Instantiating a Driver..............................................................2-9Using the jdbc.drivers Property ......................................2-11Choosing the Best Registration Approach ..........................2-14
Step 2 – Establishing a Connection to the Database .................. 2-15Connection Process.................................................................2-15DriverManager.getConnection ........................................2-18Driver.connect.....................................................................2-20
Step 3 – Creating a Statement........................................................ 2-22
Statement................................................................................2-23PreparedStatement ..............................................................2-25CallableStatement ..............................................................2-27Comparing Statement Interfaces ..........................................2-29
Step 4 – Executing the SQL Statement ......................................... 2-30Statement................................................................................2-31PreparedStatement and CallableStatement................2-32
Step 5 – Processing the Results ..................................................... 2-33Step 6 – Closing Down JDBC Objects........................................... 2-35Exercise: Using JDBC...................................................................... 2-37
Tasks .........................................................................................2-37Exercise Summary...................................................................2-38
Check Your Progress ...................................................................... 2-39Think Beyond .................................................................................. 2-40
OOAD and Database Design ..................................................................3-1Objectives ...........................................................................................3-1Relevance............................................................................................ 3-2References .......................................................................................... 3-3Module Overview............................................................................. 3-4Object ID Overview .......................................................................... 3-5Object IDs and Primary Keys.......................................................... 3-6
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 5/339
vCopyright1999Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Creating Object IDs......................................................................... 3-11Single-row Table .....................................................................3-11High/Low................................................................................3-12
Object-Relational Mapping............................................................ 3-15Mapping Classes to Tables ............................................................ 3-18One Table for Every Class .....................................................3-19One Table for Each Concrete Class ......................................3-23One Table for an Entire Class Hierarchy.............................3-26Mapping Two Classes to One Table.....................................3-29
Mapping Class Attributes to Table Columns ............................. 3-31Mapping Class Relationships to Tables....................................... 3-33
One-to-One Relationships......................................................3-34One-to-Many Relationships...................................................3-36Many-to-Many Relationships................................................3-38
Exercise: OOAD and Database Design ........................................ 3-41Tasks .........................................................................................3-41Exercise Summary...................................................................3-42
Check Your Progress ...................................................................... 3-43Think Beyond .................................................................................. 3-44
JDBC Advanced Topics ...........................................................................4-1Objectives ...........................................................................................4-1Relevance............................................................................................ 4-2Exceptions .......................................................................................... 4-3
Overview....................................................................................4-3
SQLException ...........................................................................4-4SQLWarning ...............................................................................4-6
Metadata............................................................................................. 4-7Database Metadata....................................................................4-8Result Set Metadata ..................................................................4-9
Transactions..................................................................................... 4-10Overview..................................................................................4-10
JDBC Transaction Methods ...................................................4-11Basic Syntax .............................................................................4-12Concurrency Control ..............................................................4-13
Exercise: JDBC Advanced Topics ................................................. 4-17Tasks .........................................................................................4-17Exercise Summary...................................................................4-18
Check Your Progress ...................................................................... 4-19Think Beyond .................................................................................. 4-20
JDBC 2.0 Core Features ............................................................................5-1Objectives ...........................................................................................5-1Relevance............................................................................................ 5-2Enhancements to the JDBC 2.0 API ................................................ 5-3
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 6/339
vi Database A pplication Programming With Java TechnologyCopyright1999Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Result Set Enhancements ................................................................. 5-5Scrollability ................................................................................5-6Updatability.............................................................................5-14
Statement Enhancements for Batch Updates .............................. 5-19Statement................................................................................5-20PreparedStatement ..............................................................5-24CallableStatement ..............................................................5-26
Advanced Data Types .................................................................... 5-27Overview..................................................................................5-27Using SQL3 Data Types .........................................................5-29Blob, Clob, and Array Objects .............................................5-32Structured Types and Distinct Types...................................5-34Structured Types.....................................................................5-35Distinct Types..........................................................................5-37
SQL3 Advanced Features ......................................................5-39Exercise: JDBC 2.0 Core Features.................................................. 5-40
Tasks .........................................................................................5-40Exercise Summary...................................................................5-41
Check Your Progress ...................................................................... 5-42Think Beyond .................................................................................. 5-43
JDBC 2.0 Standard Extensions ................................................................6-1Objectives ...........................................................................................6-1Relevance............................................................................................ 6-2References .......................................................................................... 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-8Registering a DataSource Object.........................................6-12Establishing a Connection Using JNDI................................6-14
Connection Pooling ........................................................................ 6-16Overview..................................................................................6-16Connecting ...............................................................................6-19
Distributed Transactions................................................................ 6-20Overview..................................................................................6-20Architecture .............................................................................6-21Implementation.......................................................................6-23
Row Sets ........................................................................................... 6-26Overview..................................................................................6-26Types of Row Set Implementations......................................6-28Row Sets at Design Time........................................................6-30Row Sets at Runtime...............................................................6-35
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 7/339
viiCopyright1999Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Overview of Row Set Implementation ........................................ 6-38Check Your Progress ...................................................................... 6-40Think Beyond .................................................................................. 6-41
Row Set Implementation .........................................................................7-1Objectives ...........................................................................................7-1Relevance............................................................................................ 7-2CachedRowSet Class Overview ...................................................... 7-3Creating a CachedRowSet................................................................ 7-6Retrieving Data.................................................................................. 7-7Miscellaneous Methods.................................................................. 7-15Reading and Writing Data ............................................................. 7-16
Overview..................................................................................7-16RowSetReader .........................................................................7-20
RowSetWriter .........................................................................7-22Exercise: Row Set Implementations ............................................. 7-23Tasks .........................................................................................7-23Exercise Summary...................................................................7-24
Check Your Progress ...................................................................... 7-25Think Beyond .................................................................................. 7-26
JDBC and Application Architecture ......................................................8-1Objectives ...........................................................................................8-1Relevance............................................................................................ 8-2References .......................................................................................... 8-3
Tiered Application Architecture Overview.................................. 8-4Tiers and Components ..................................................................... 8-6Two-Tier Architecture...................................................................... 8-7Three-Tier Architecture.................................................................... 8-9N-Tier Architecture......................................................................... 8-13Choosing an Architecture .............................................................. 8-16
Two-Tier Architecture............................................................8-16Three-Tier and N-Tier Architecture.....................................8-18
Check Your Progress ...................................................................... 8-20Think Beyond .................................................................................. 8-21
Database Basics ........................................................................................A-1Objectives ..........................................................................................A-1References ......................................................................................... A-2Database Overview.......................................................................... A-3Data Independence .......................................................................... A-6Transactions...................................................................................... A-7Locking ............................................................................................ A-11
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 8/339
viii Database Application Programming With Java TechnologyCopyright1999Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
SQL Basics ....................................................................................... A-13Overview.................................................................................A-13SELECT Statement...................................................................A-14
INSERT Statement...................................................................A-17DELETE Statement...................................................................A-18UPDATE Statement...................................................................A-18
Using SQLJ ................................................................................................B-1Objectives .......................................................................................... B-1References ......................................................................................... B-2SQLJ Overview................................................................................. B-3SQLJ Architecture ............................................................................ B-4How SQLJ Works............................................................................. B-5Using SQLJ........................................................................................ B-7
Registering and Connecting to the Database UsingDatabase Connection Management............................................ B-8Creating a Statement Using SQLJ Clauses and Host
Variables....................................................................................... B-12SQLJ Clauses........................................................................... B-12 Host Variables ....................................................................... B-13
Executing the Query and Reviewing the Result SetUsing Iterator Objects................................................................. B-14
Defining an Iterator Class ..................................................... B-14Using an Iterator Class.......................................................... B-15
Glossary ....................................................................................... Glossary-1
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 9/339
ixCopyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
About This Course
Course Goal
Database Application Programming With Java Technology is a focused-technology course that provides you with a hands-on approach todeveloping database applications using Java™ technology and the
JDBC™ application programming interface (API). You will learn to usethe features of the JDBC 1.0 API, and will learn about the new featuresadded 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 arelational database, and how to design a multi-tier databaseapplication.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 10/339
x Database A pplication Programming With Java TechnologyCopyright2000Sun 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 howto enable Java applications to perform operations on their databases,and allow you to write Java applications that connect to any databasethat provides drivers.
Database Application Programming With Java Technology provides youwith the information and skills to connect a Java application to arelational database management system (RDBMS) and retrieve andmanipulate data. Features of both the first and second releases of JDBCare covered; the second release includes a number of features such assupport for connection pooling and more flexible navigation within aresult set.
You will also learn how to choose the correct application architecturefor use with JDBC—two-tier, three-tier, or n-tier—and how to map thatapplication’s objects to tables in a database.
Information on SQLJ, another method for connecting a Javaapplication to a relational database, is included in an appendix.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 11/339
About This Course xiCopyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Course Overview
Note – Before taking this course, you should be somewhat familiarwith structured query language (SQL) and databases; a short review of the basics is provided in Appendix A, ‘‘Database Basics.”
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 12/339
xii Database A pplication Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Course Map
The following course map enables you to see what you haveaccomplished and where you are going in reference to the coursegoals.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 13/339
About This Course xiiiCopyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 itenables 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 datausing JDBC 1.0 capabilities.
Module 3 – “OOAD and Database Design”
This module describes how to map your object-oriented Javaapplication to the tables and columns of a relational database, andidentify each object uniquely.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 14/339
xiv Database Application Programming With Java TechnologyCopyright2000Sun 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 asforward and backward scrolling, which were added to the JDBCAPI in the latest release.
Module 6 – “JDBC 2.0 Standard Extensions”
This module describes how to use the advanced features, such assupport for Java Naming and Directory Interface™ (JNDI), whichwere added to the JDBC API in the latest release.
Module 7 – “Row Set Implementation”
This module describes the CachedRowSet implementation androw set readers and writers.
Module 8 – “JDBC and Application Architecture”
This module describes application architecture considerationsrelated to JDBC.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 15/339
About This Course xvCopyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Module-by-Module Overview
Appendix A – “Database Basics”
This appendix reviews different types of databases, concepts suchas 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 toconnect a Java application to a relational database.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 16/339
xvi Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Course Objectives
Upon completion of this course, you should be able to:
Design a multi-tier database application architecture
Create a multi-tier database application using the Javaprogramming 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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 17/339
About This Course xviiCopyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Skills Gained by Module
The skills for Database Application Programming With Java Technology areshown in column 1 of the following matrix. The black boxes indicatethe main coverage for a topic; the gray boxes indicate the topic is
briefly discussed.
Module
Skills Gained 1 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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 18/339
xviii Database Application Programming With Java TechnologyCopyright2000Sun 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 thiscourse:
Module Day 1 Day 2 Day 3 Day 4
About This Course A.M.
JDBC Overview A.M.
Using JDBC P.M.
OOAD and Database Design A.M.
JDBC Advanced Topics P.M.
JDBC 2.0 Core Features A.M.
JDBC 2.0 Standard Extensions P.M.
Row Set Implementation A.M.
JDBC and Application Architecture P.M.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 19/339
About This Course xixCopyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 coursesoffered by Sun Educational Services:
Object-oriented theory – Covered in SL-210: Migrating to OOProgramming with Java Technology and OO-226: Application Analysisand Design for Java Technology
Java programming language basics – Covered in SL-275: JavaProgramming Language
Relational database design and SQL basics
Refer to the Sun Educational Services catalog for specific informationand registration.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 20/339
xx Database A pplication Programming With Java TechnologyCopyright2000Sun 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 thetopics shown on the above overhead?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 21/339
About This Course xxiCopyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 theabove overhead.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 22/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 23/339
About This Course xxiiiCopyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
How to Use Course Materials
Exercise – Lab exercises will give you the opportunity to practiceyour skills and apply the concepts presented in the lecture.
Check your progress – Module objectives are restated, sometimesin question format, so that before moving on to the next moduleyou are sure that you can accomplish the objectives of the currentmodule.
Think beyond – Thought-provoking questions are posed to helpyou apply the content of the module or predict the content in thenext module.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 24/339
xxiv Database Application Programming With Java TechnologyCopyright2000Sun 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 thiscourse to represent various training elements and alternative learningresources.
Icons
Additional resources – Indicates additional reference materials areavailable.
Discussion – Indicates a small-group or class discussion on the currenttopic is recommended at this time.
Exercise objective – Indicates the objective for the lab exercises thatfollow. The exercises are appropriate for the material being discussed.
Note – Additional important, reinforcing, interesting or specialinformation.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 25/339
About This Course xxvCopyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Course Icons and Typographical Conventions
Typographical Conventions
Courier is used for the names of commands, files, and directories, aswell 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. Forexample:
system% su
Password:
Courier italic is used for variables and command-lineplaceholders 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 User’s Guide.These are called class options.You must be root to do this.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 26/339
xxvi Database Application Programming With Java TechnologyCopyright2000Sun 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 elementand an example are shown. The following example of this approachshows 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 valuessubstituted 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}
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 27/339
1-1Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JDBC Overview 1
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 toa 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 toidentify a database
This module describes the components of the JDBC API, how it isused, and how it enables a Java application to connect to a database.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 28/339
1
1-2 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Relevance
Discussion – What main tasks should JDBC complete to be useful inconnecting an application to a database?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 29/339
1
JDBC Overview 1-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
References
Additional resources – The following resources can provideadditional detail on the topics presented in this module, as well as theentire course.
Main JDBC download page, including access to the Java Platform,Standard Edition; the Java 2 Platform, Enterprise Edition; the JDBC2.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 (JavaSeries). Addison-Wesley.
Reese, George. Database Programming with JDBC and Java. O’Reilly& Associates. 1997.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 30/339
1
1-4 Database Application Programming With Java TechnologyCopyright2000Sun 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 SunMicrosystems™ and its partners who incorporate Java technology.This API provides universal access to a wide range of relationaldatabases, enabling you to focus on the major applicationdevelopment issues, rather than the mechanics of connecting to aspecific database.
The JDBC API is a set of classes and interfaces provided in the Java 2Software Development Kit (J2SDK). JDBC has been included since
JDK™ 1.1 was released. Since its first release, JDBC has had one majorrevision. JDK 1.1 comes with JDBC 1.0, while the J2SDK includes JDBC2.0.
JDBC makes it possible to do three main tasks:
Establish a connection with a database
Send a SQL query as a String directly to the database
Process the results
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 31/339
1
JDBC Overview 1-5Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
What Is the JDBC API?
There are two major components of JDBC, the developer interface andthe implementation interface. This course concentrates on thedeveloper interface.
An interface for Java programming language developers. Thisprovides developers with the class and method definitionsrequired 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 Editionand JDK 1.1
javax.sql, included with the Java 2 Platform, EnterpriseEdition.
An implementation interface for database providers. This providesvendors with the requirements they must fulfill to produce JDBCdrivers, which allow Java applications to use their databasefunctionality. The implementation specifications and tools are
supplied by Sun Microsystems.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 32/339
1
1-6 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.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 developersubsequently uses JDBC methods in the developer interface, thevendor-supplied classes in the drivers provide code for databaseoperations.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 33/339
1
JDBC Overview 1-7Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Drivers
Overview
A JDBC driver is a collection of classesthat implement the JDBCinterfaces required to connect a Java application to a database. Eachdatabase driver must provide a class that has implemented thejava.sql.Driver interface. The database driver class then is used bythe generic java.sql.DriverManager class when it needs a driver toconnect to a particular database using a URL string.
The JDBC driver test suite is provided for driver vendors. Only driversthat pass the JDBC driver test suite can be designated JDBCCompliant™. You can download the driver test suite from thefollowing site:
http://java.sun.com/marketing/enterprise/jdbc.html
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 34/339
1
1-8 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.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 standardizedAPI 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) canaccess multiple database systems through one or more drivers.
Figure 1-1 JDBC Drivers
Java application
JDBC
JDBC-NETdriver
Driver A Driver BJDBC-ODBCBridge driver
ODBC and
DB drivers
JDBC API
URL URLURL URL
driver manager
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 35/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 36/339
1
1-10 Database Application Programming With Java TechnologyCopyright2000Sun 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 lesspopular database management systems (DBMSs) if JDBC drivers arenot 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 oneach database client. Therefore, this driver is most appropriate forcorporate networks where client installations are not a major problem,or for an application server in a three-tier architecture.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 37/339
1
JDBC Overview 1-11Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Drivers
Type 1 – JDBC/ODBC Bridge Plus ODBC Driver
This approach allows companies with a heavy investment in ODBC toleverage that investment with the newer Java programming languagetools.
The disadvantage to this approach is that the application code calls the JDBC driver manager, which invokes the JDBC driver. The driver callsthe ODBC driver manager, which invokes the ODBC driver, whofinally contacts the database. Failure can occur at several points in this
system.
The JDBC-ODBC bridge is bundled with the J2SDK, in the packagenamed 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.
Figure 1-2 JDBC-ODBC Bridge
Client
JDBC API
Application
ODBC bridge ODBC driver
Database
Server
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 38/339
1
1-12 Database Application Programming With Java TechnologyCopyright2000Sun 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 tothe API of the database client library. The library is distributed by theprovider 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 onceand run anywhere. If a particular DBMS vendor has not created aclient API for its database, then it becomes difficult to switch from oneDBMS to another.
This type of driver is not always uniformly distributed, so you mightnot be able to run your application on all platforms capable of running
Java technology.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 39/339
1
JDBC Overview 1-13Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Drivers
Type 2 – Native API
Figure 1-3 illustrates a system using this driver.
Figure 1-3 Native API
Client
JDBC API
Application
Server
Native codelibraries Database
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 40/339
1
1-14 Database Application Programming With Java TechnologyCopyright2000Sun 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 isspecific to the intermediary. These calls are translated by theintermediary 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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 41/339
1
JDBC Overview 1-15Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Drivers
Type 3 – JDBC-Net
Figure 1-4 illustrates a system using this driver.
Figure 1-4 JDBC-Net
Client
JDBC API
Application
ServerIntermediary server
DatabaseJDBC-NetDBMS-specifictranslator
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 42/339
1
1-16 Database Application Programming With Java TechnologyCopyright2000Sun 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 networkprotocol used by the DBMS. This allows direct calls from the client tothe database. These protocols are proprietary, so the database provideris the primary source for the driver. Several vendors have these inprogress.
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 toallow for switching to different types of DBMSs.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 43/339
1
JDBC Overview 1-17Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Drivers
Type 4 – Native Protocol
Figure 1-5 illustrates a system using this driver.
Figure 1-5 Native Protocol
Client
JDBC API
Application
Server
DatabaseNative protocol
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 44/339
1
1-18 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Drivers
Finding Drivers
To view the latest information about drivers, check the following JDBCWeb page:
http://java.sun.com/products/jdbc/drivers.html
The first vendors with category 3 drivers available were SCO, OpenHorizon, Visigenic, and WebLogic.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 45/339
1
JDBC Overview 1-19Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JDBC Developer Interface
Packages
The JDBC API is expressed as a series of Java technology interfaces, inthe following packages:
java.sql – Contains the classes and interfaces used for the basefunctionality of JDBC
This package has been part of the Java programming languagesince the JDK 1.1 was released. It is included in the Java 2Platform, 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, andalso can be downloaded separately.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 46/339
1
1-20 Database Application Programming With Java TechnologyCopyright2000Sun 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 Module5, ‘‘JDBC 2.0 Core Features” and Module 6, ‘‘JDBC 2.0 StandardExtensions.”
The following are the basic JDBC classes and interfaces.
DriverManager
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 47/339
1
JDBC Overview 1-21Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JDBC Developer Interface
Classes and Interfaces
DriverManagerClass
The DriverManager class manages database drivers and providessupport for creating new database connections. It connects Javaapplications 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 driverscan point to the same database.
Different drivers must have a different subprotocol identifier for theDriverManager to distinguish among them. Subprotocols are coveredlater 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 adatabase. 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 specificdatabase. The Connection allows developers to create statementobjects to represent database queries. In addition, you can use aConnection to obtain information about the database and about the
JDBC driver capabilities.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 48/339
1
1-22 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
JDBC Developer Interface
Classes and Interfaces
Statement, PreparedStatement,and CallableStatementInterfaces
Statement functions as a container for executing a SQL statement on agiven connection. There are two important subtypes of Statement:PreparedStatement and CallableStatement. PreparedStatementholds 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 SELECTSQL queries are executed; it is the result of executing a statement.Within a row, you can access its column values in any order. You canuse the ResultSetMetaData interface to get information about theResultSet. A ResultSet maintains a cursor pointing to its currentrow 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 inFigure 1-6.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 49/339
1
JDBC Overview 1-23Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JDBC Developer Interface
Figure 1-6 java.sql Core API Class Hierarchy
PreparedStatement
CallableStatement
Connection
DatabaseMetaData
Driver
ResultSet
ResultSetMetaData
java.lang.Object
java.util.Date
DateDriverManagerDriverPropertyInfo
Time
TimeStamp
Types
DataTruncation
SQLException
SQLWarning
Statement
java.lang.Throwable
java.lang.Exception
Legend
Class
Interface
Abstract
Extends
Class
Ref*
BatchUpdateException
Array*
Blob*
Clob*
Struct*
SQLData*
SQLInput*
SQLOutput*
* New with JDBC 2.0
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 50/339
1
1-24 Database Application Programming With Java TechnologyCopyright2000Sun 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 theappropriate driver can recognize it and establish a connection with it.The protocol, subprotocol, and specific data source are identified in theURL. For example, the URL jdbc:odbc:fred indicates that the drivershould use the jdbc protocol to connect to an ODBC-type data sourcenamed fred.
Driver vendors determine the JDBC URL that identifies theirparticular driver. You do not need to form a JDBC URL; simply use theURL supplied with the drivers you are using. The role of the JDBC APIis to recommend conventions for driver writers to follow whenstructuring their JDBC URLs.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 51/339
1
JDBC Overview 1-25Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Identifying a Database Using a URL
Overview
The JDBC URL mechanism is intended to provide a framework so thatdifferent drivers can use different naming systems that are appropriatefor their needs. Each driver need only understand a single URLnaming syntax, and can reject any other URLs that it encounters. Theconventions are flexible, implementing the following features.
JDBC URLs allow driver writers to encode all necessaryconnection information within them. For example, an applet can
talk to a given database to open the database connection withoutrequiring 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 isdynamically translated to the actual name by a network namingsystem.
This allows system administrators to avoid specifying particularhosts as part of the JDBC name. There are several differentnetwork name services (such as the network information service,
NIS), and there is no restriction on which ones you can use.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 52/339
1
1-26 Database Application Programming With Java TechnologyCopyright2000Sun 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 syntaxhas three parts, separated by colons.
URL syntax
jdbc:subprotocol:subname
Examplejdbc: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 remoteconnections, providing more information about connecting to thedatabase, and so on.
Each part of the URL is covered in the following sections.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 53/339
1
JDBC Overview 1-27Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 54/339
1
1-28 Database Application Programming With Java TechnologyCopyright2000Sun 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 connectivitymechanism, which can be supported by one or more drivers. Differentdrivers must have a different subprotocol identifier for theDriverManager to be able to distinguish among them.
In the example jdbc:odbc:wombat, the subprotocol is odbc.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 55/339
1
JDBC Overview 1-29Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.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 serviceshould resolve the database name “accounts-payable” into a morespecific 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.”
odbcSubprotocol
The odbc subprotocol is reserved for URLs that specify ODBC-styledata 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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 56/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 57/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 58/339
1
1-32 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Check Your Progress
Before continuing on to the next module, check that you are able toaccomplish or answer the following:
Describe the purpose of the JDBC API
Explain how to use the JDBC API to connect a Java application toa database
Define the different components of the JDBC architecture
Select the correct kind of JDBC driver for a given applicationarchitecture
Describe the URL syntax used to identify a database
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 59/339
1
JDBC Overview 1-33Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 60/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 61/339
2-1Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
UsingJDBC 2
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 queryrequirements
Manipulate data in the database using a JDBC connection
Process the results of a query
Shut down the appropriate objects after a JDBC process iscomplete
This module describes the steps necessary to enable a Java applicationto connect to a relational database and retrieve data. The materialcovered 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.0Standard Extensions,” cover the functionality that is available only inthe latest JDBC release.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 62/339
2
2-2 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Relevance
Discussion – Suppose you are tasked with writing an application thatretrieves, 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 differentdatabase is used?
3. What considerations must be made to make the system flexible
and responsive to changes in the business? For example, supposethat you deny service to certain customers.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 63/339
2
Using JDBC 2-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Creating a Basic JDBC Application
Now that you have learned the components of the JDBC API inModule 1, ‘‘JDBC Overview,” the next step is to develop the code torequest and return information from a relational databasemanagement system (RDBMS). The six main steps are as follows:
Note – This list and the following sections cover the standard methodsfor using the JDBC API to connect with and retrieve data from adatabase. 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 tolocate the appropriate driver to use.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 64/339
2
2-4 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Creating a Basic JDBC Application
Step 3 – Create a statement.
With the connection established, you can create (instantiate) aStatement, 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 executethe SQL statement.
Step 5 – Process the results.
The Statement object returns a ResultSet. The ResultSet objectis all the rows of the table that satisfy the query. You can stepthrough the set to view each row. There are several methodswithin 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 JDBCfunction.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 65/339
2
Using JDBC 2-5Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 machinenamed 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 33 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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 66/339
2
2-6 Database Application Programming With Java TechnologyCopyright2000Sun 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 theDriverManager class. When attempting to connect to a database, the
JDBC API uses the first driver it finds that can successfully connect tothe given URL. Registering the driver is simple but critical, becausewithout 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 arunning Java Virtual Machine (JVM) session. It brings in the correct
bytecodes, and registers the driver with the appropriate structure inthe Java Virtual Machine: the driver manager. Registration lasts for theduration of a particular JVM session only.
You can load multiple drivers in memory at the same time.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 67/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 68/339
2
2-8 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Step 1 – Registering a Driver
Using the ClassLoader
To communicate with a particular database engine using the JDBCAPI, you must first load the JDBC driver. The driver has a staticinitializer that creates a Driver object, which registers the driver withthe driver manager. This driver remains behind the scenes, handlingany 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");
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 69/339
2
Using JDBC 2-9Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 newkeyword to register the driver. You do not need to associate the driverobject with a variable, because it exists in memory and is accessible tothe DriverManager.
Syntax
Driver drvRefVar = new DriverConstructor ;
Example
This example registers the driver with the driver manager, whichsubsequently manages the driver for the JVM session. It is notnecessary to retain a reference to the created object.
Driver drv = new oracle.jdbc.driver.OracleDriver();
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 70/339
2
2-10 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Notes
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 71/339
2
Using JDBC 2-11Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Step 1 – Registering a Driver
Using the jdbc.driversProperty
A running JVM has a number of properties, which allow you to defineand retrieve values associated with JVM functionality. One of thoseproperties 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.driversProperty
You can register a driver by defining the jdbc.drivers property as acolon-separated list of driver class names.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 72/339
2
2-12 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Step 1 – Registering a Driver
Using the jdbc.driversProperty
Defining the jdbc.driversProperty
Note – This approach must be done on the command line, or run by ascript, before launching the Java application.
Syntax
jdbc.drivers = driverName[:driverName]
Example
jdbc.drivers = oracle.jdbc.driver.OracleDriver:acme.cool.Driver
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 73/339
2
Using JDBC 2-13Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Step 1 – Registering a Driver
Using the jdbc.drivers Property
Using the -DOption With the javaCommand
When attempting to connect to a database, the JDBC API uses the firstdriver it finds that can successfully connect to the given URL. It firsttries each driver specified in the properties list, in order from left toright. It then tries any drivers that are already loaded in memory, inthe order that the drivers were loaded.
You can register the driver by loading it into the system properties. Touse this method, specify the name=value pair (the name is alwaysjdbc.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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 74/339
2
2-14 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Step 1 – Registering a Driver
Choosing the Best Registration Approach
Discussion – For each approach, what are the advantages anddisadvantages, and why?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 75/339
2
Using JDBC 2-15Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 ), whichcalls Driver.connect(urlString ) on all the registered driversuntil 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, theDriverManager makes a connection to the database.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 76/339
2
2-16 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Step 2 – Establishing a Connection to the Database
Connection Process
4. If the driver does not match, null is returned and the next driveris checked.
5. If the Java application cannot connect to the database, aSQLException is thrown. This would happen if no suitable drivercan be found, or because the last driver found was suitable butfailed during the attempt to connect.
Exception handling in JDBC is covered in Module 4, ‘‘JDBCAdvanced Topics.”
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 77/339
2
Using JDBC 2-17Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Step 2 – Establishing a Connection to the Database
Connection Process
Figure 2-1 illustrates how a DriverManager resolves a URL stringpassed in the getConnection method. When the driver returns a null,the driver manager continues to call the next registered driver untileither the list is exhausted or a Connection object is returned.
Figure 2-1 Example of Database Resolution
Note – If a driver attempts to connect but fails, DriverManagercontinues through the list of additional drivers.
DriverManager
jdbc:A
driver
Application
getConnection(urlString )
accounts
connect(urlString )
null nullConnection
Successfulconnection
jdbc:B
driver
jdbc:odbc
driver
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 78/339
2
2-18 Database Application Programming With Java TechnologyCopyright2000Sun 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);
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 79/339
2
Using JDBC 2-19Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Step 2 – Establishing a Connection to the Database
DriverManager.getConnection
Example
The following example establishes a connection con to the databasenamed accounts on the specified host.
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@java1.com:1521:accounts");
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 80/339
2
2-20 Database Application Programming With Java TechnologyCopyright2000Sun 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 connectionto the given URL.
This method makes a direct call to a specific Driver object. Use it toavoid the problems of the standard approach to finding a driver, inwhich 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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 81/339
2
Using JDBC 2-21Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 followingexample, 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 kind11 // of recovery action here. Options might include
12 // connecting to an alternate DB, prompting the user
13 // for action, or exiting the application.
14 }
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 82/339
2
2-22 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Step 3 – Creating a Statement
You can use three types of statements.
Statement – Executes a standard query
PreparedStatement – Executes a precompiled SQL statement
CallableStatement – Executes non-SQL statement
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 83/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 84/339
2
2-24 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Step 3 – Creating a Statement
Statement
Note – For more information about SQL commands, refer to AppendixA, ‘‘Database Basics.”
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 85/339
2
Using JDBC 2-25Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Step 3 – Creating a Statement
PreparedStatement
If the same SQL statements are executed multiple times, use aPreparedStatement object. A prepared statement is a precompiled SQLstatement that is more efficient than calling the same SQL statementover and over. The SQL statement is parsed only once. ThePreparedStatement interface extends the Statement interface to addthe capability of passing parameters inside of a statement.
Syntax
PreparedStatement pstmtRefVar = conRefVar .prepareStatement(sqlString );
You can use question marks within the SQL statement as placeholdersfor data values.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 86/339
2
2-26 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
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 indexof 1, not 0.
Refer to the PreparedStatement interface in the Java 2 Platform APISpecification for a list of the setXXX methods. These methods, usedfor setting SQL IN parameter values, must specify types that arecompatible with the defined SQL type of the input parameter. Forexample, if the INparameter has SQL type Integer, then use setInt.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 87/339
2
Using JDBC 2-27Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Step 3 – Creating a Statement
CallableStatement
A callable statement allows non-SQL statements (such as storedprocedures) to be executed against the database. TheCallableStatement interface extends the PreparedStatementinterface, which provides the methods for setting IN parameters.Because the PreparedStatement interface extends the Statementinterface, methods for retrieving multiple results with a storedprocedure 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 theSQL statement as placeholders for data values.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 88/339
2
2-28 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Step 3 – Creating a Statement
CallableStatement
Example
You could use a CallableStatement if you wanted to store aprecompiled SQL statement to query a database containing the coffeeinventory 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 callregisterOutParameter to register the java.sql.Type of any SQLOUT parameters.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 89/339
2
Using JDBC 2-29Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 codecreated?
Client Client Server
Where is codestored?
Client Server Server
Technologies forwriting code
Java programminglanguage, SQLoperations
Java programminglanguage, SQLoperations
The procedurallanguage for thedatabase on thetarget platform, suchas PLSQL (theprocedural languagefor SQL)
Configurability High High the first time,then low Low
Portability High High, provided thedatabase supportsPreparedStatement
Low
Efficiency fortransferringdata
Low Low the first time,then high
High
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 90/339
2
2-30 Database Application Programming With Java TechnologyCopyright2000Sun 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 APIpasses the SQL statement to the underlying database connectionunaltered. The JDBC API does not attempt to interpret queries.
The result of executing a query statement is a table of data that youcan access using a java.sql.ResultSet object.
The statement, whether it is a Statement, CallableStatement, orPreparedStatement object, is coupled with the correspondingResultSet. If you run the statement again, the contents of the firstResultSet will be overwritten by the results of the second statement.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 91/339
2
Using JDBC 2-31Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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, useStatement.executeQuery(sqlString ).
For INSERT, UPDATE, or DELETE statements, useStatement.executeUpdate(sqlString ), which returns aninteger.
For any process, you can useStatement.execute(sqlString ), which returns a boolean,indicating whether a result set has been returned.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 92/339
2
2-32 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
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");
PreparedStatementand 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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 93/339
2
Using JDBC 2-33Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Step 5 – Processing the Results
To retrieve data from the ResultSet object that was returned, use itsassessor 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 aname to reference a column, one or more columns could have the samename, 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 isinitially positioned before its first row. The first call to next makes thefirst row the current row, the second call makes the second row thecurrent row, and so on.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 94/339
2
2-34 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Step 5 – Processing the Results
Refer to the Java 2 Specification API for the getXXX methods to accesscolumns within the ResultSet. These include getBoolean(intcolumnIndex), getByte(int columnIndex), and getInt(int
columnIndex).
To retrieve data from the ResultSet object, you must be familiar withthe columns returned and their data types. A table mapping Java typesto SQL data types is provided in Table 3-1 of Module 3, ‘‘OOAD andDatabase Design.”
Syntax1 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 tablefrom the ResultSet. Column names are shown, but you could usecolumn IDs instead.
1 while (rs.next()) {
2 System.out.println();
3 System.out.println("Coffee Name: " + rs.getString(1));
4 System.out.println("Supplier ID: " + rs.getInt(2));
5 System.out.println("Price : " + rs.getFloat(3));
6 System.out.println("Sales : " + rs.getInt(4));
7 }
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 95/339
2
Using JDBC 2-35Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 controlledmanner.
Statement – Detaches the statement from its previous businessfunction
ResultSet – Deallocates JDBC-based resources.
None of the three are reusable after closing.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 96/339
2
2-36 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Step 6 – Closing Down JDBC Objects
The following example shows how to close down a ResultSet,Statement, and Connection object, and catching any resultingexceptions.
1 try {
2 rs.close();
3 stmt.close();
4 con.close();
5 }
6 catch (SQLException ex) {
7 ex.printStackTrace();
8 }
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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 97/339
2
Using JDBC 2-37Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Exercise: Using JDBC
Exercise objective – Practice the concepts and tasks you have learnedin this module.
Tasks
Go to the SL330 directory on your computer and change to the lab filesdirectory. Open the directory for this module, then the directory forthis exercise, and read the readme file. Follow the instructions in thatfile to complete this exercise.
If additional instructions or materials are required, your instructor willprovide them.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 98/339
2
2-38 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Exercise: Using JDBC
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,or discoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 99/339
2
Using JDBC 2-39Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Check Your Progress
Before continuing on to the next module, check that you are able toaccomplish 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 queryrequirements
Manipulate data in the database using a JDBC connection
Process the results of a query
Shut down the appropriate objects after a JDBC process iscomplete
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 100/339
2
2-40 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Think Beyond
The Java programming language is object oriented; a relationaldatabase is not. What do you need to do to connect the Javatechnology object model logically to the database?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 101/339
3-1Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
OOADandDatabaseDesign 3
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-orientedapplications.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 102/339
3
3-2 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Relevance
Discussion – What would be the best way to correlate objects withtables in your database?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 103/339
3
OOAD and Database Design 3-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
References
Additional resources – The following resources can provideadditional 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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 104/339
3
3-4 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Module Overview
When you develop an object-oriented application that accesses adatabase, it is important to also consider how you will store data fromobjects 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 yourapplication
How the database tables will relate to each other
This module describes how to deal with these issues, through objectIDs (OIDs) and object-relational mapping.
Note – The principles discussed apply to any object-orientedapplication, not only to those created using the Java programminglanguage.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 105/339
3
OOAD and Database Design 3-5Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Object ID Overview
A requirement in classic relational DBMS is that every row entry in atable must be uniquely identifiable—that is, there should be a way touniquely identify every record.
In databases, this is represented at the table level by a primary key, avalue unique for every database record in the table. However,sometimes you need to retrieve and combine data from multipletables, and the primary key might not be unique in this case.
This section describes object IDs (OIDs), which are unique recordidentifiers that have no business meaning, and explains how they can
be used more effectively than other indexes, such as primary keys, touniquely identify objects (records) in one or more databases.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 106/339
3
3-6 Database Application Programming With Java TechnologyCopyright2000Sun 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 andmaintain. OIDs, on the other hand, must be generated and maintainedoutside of individual tables. However, there are several advantages, tooffset the extra maintenance:
OIDs can transcend individual tables.
Unlike indexes, OIDs can be generated for every object to bestored in the database, rather than only being unique for eachtable. The result is that you can store the unique OID for every
object in the database, regardless of its table mapping, and have asimple, efficient way to retrieve all of the data for any object inyour system.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 107/339
3
OOAD and Database Design 3-7Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Object IDs and Primary Keys
OIDs can transcend databases.
In more complex architectures, client applications can accessdifferent database servers over time. In such a system, you cangenerate unique OIDs for multiple databases, and therefore knowthat 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 tablesto retrieve the object. This is easily done with an OID. Without theOID, you would have to create or use an existing attribute to linkthe tables together.
OIDs do not have unnecessary ties to business meaning
Primary keys are often based on the content of the record. Forexample, an employee ID is the primary key for the employeetable and uniquely identifies each employee. The employee
number field has a set format, such as XX-MMDDYY-1234. Theformat has business meaning; the first part could identify theemployee’s department, the second could specify the employee’sstart date, and the third a unique number assigned to theemployee.
However, the departments can change and be identified with threeletters, or the company might grow so that the last part of the IDneeds to be longer to make the IDs unique. In this case, the formatof 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, andclearance, two employees might have the same ID, and developerswould need to add business logic to ensure thatthis would nothappen. With OIDs, this is not a consideration, because they haveno business meaning and are automatically guaranteed to beunique.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 108/339
3
3-8 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Object IDs and Primary Keys
Another example could be a national identification number (socialsecurity number in the United States). Many applications use thisnumber 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, theapplication and tables would need to change.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 109/339
3
OOAD and Database Design 3-9Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 anyother classes in the class diagram.
This is not a problem until an employee needs to become acustomer or a customer wants to be an employee. At this point,you would need to assign the employee object a new OID.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 110/339
3
3-10 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Object IDs and Primary Keys
If you make OIDs unique to each class, you separately create OIDsfor every table that stores object data in the system. This has thefollowing implications.
It could be faster to generate OIDs (because you generate aunique OID for each table. You are not tying up the entiredatabase when you create an OID, you are just locking thatspecific table)
You generate separate OIDs for each table, so there willprobably be duplicate values for the tables. This means that if
you have a row entry for an employee who then becomes acustomer, you must work out a strategy to map between thecustomer and employee tables in the database. You cannotassume that you can carry over the OID from the employeetable, 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 bothtables. This is costly because you must find one that is free in
both tables, use a database join table, which is less efficient, orplace 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 isalleviated. You do not need to reassign OIDs when changes occurwithin the class hierarchy, such as a customer becoming anemployee.
If the OIDs are unique across all classes, you never have to changethem based on the object model. This provides the best results forunique object identification, but can result in slower performance.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 111/339
3
OOAD and Database Design 3-11Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 anobject, you must lock the table and update the OID to ensure the OIDis not duplicated. This can significantly decrease performance becausethe same table must be accessed every time a new object is created.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 112/339
3
3-12 Database Application Programming With Java TechnologyCopyright2000Sun 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 twoparts, a high and a low value. By appending the low value to the high,you create a unique OID for each object.
The first part, or high value, comes from a single-row table that isretrieved at the beginning of the session. However, the high-lowapproach is different from the single-row table approach becauseyou do not have to retrieve the value from the table for eachobject; you do it only once per user session. Each user retrieves adifferent value, but during that session each user has the samehigh 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 theapplication. It is appended to the high value, and is incrementedwith each new object. It typically occurs with any save operation;the value is sometimes incremented using a third value todistinguish between saves.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 113/339
3
OOAD and Database Design 3-13Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Creating Object IDs
High/Low
For example, assume a single-row table has the value 5000 and isincremented 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 highvalue from the table (5000). User A uses this high valuethroughout 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 newcustomer record, the OID is 5000 with 1 appended to produce theOID 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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 114/339
3
3-14 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Creating Object IDs
High/Low
Figure 3-1 illustrates each step in the example.
Figure 3-1 High/Low Example
5000
High Value
50025001
User A
CustID
C239PPL
FirstName
High Value
5001
High Value
5000
High Value
5000
OID
50001
LastName SSN
Joe Mays 674-58-4013
User B
CustID
C244SOL
FirstNameOID
50011
LastName SSN
Kara Stelter 101-12-0086
C249FGW50012 Mike Grom 503-50-9901
User A
User A
User B
User B
1
2
3
4
5
6
5001
5001
5000
5001
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 115/339
3
OOAD and Database Design 3-15Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Object-Relational Mapping
Once you have determined how to uniquely identify each object, youneed to design the tables in your database, and decide how they willrelate to the classes in your application.
In an object-oriented application, data is stored as sets of relatedvalues (attributes in OOAD terminology) within an object. (You canstore the attributes of an object in the relational database, but not theoperations.)
Relational databases store data as sets of related values (rows) within
one or more tables. This means that an important task in determininga data storage strategy for an application is to map the object model tothe relational model. To do so, map the attributes of the classes to theappropriate relational tables.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 116/339
3
3-16 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Object-Relational Mapping
Inheritance complicates mapping classes to tables, because anysubclass has more attributes than are in the class definition. Animportant part of mapping is deciding how to store the inheritedattributes in the database: in the same table as the subclass table, or inanother table.
Note – Objects, not classes, are stored in tables. The point at which youactually save the objects in the database is implementation-dependent.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 117/339
3
OOAD and Database Design 3-17Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 118/339
3
3-18 Database Application Programming With Java TechnologyCopyright2000Sun 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 objectmodel, 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 mostcomplexity when mapping classes to tables. There are threefundamental approaches to mapping class inheritance to a relationaldatabase; 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 objectmodel can change because you might not need some attributes. Thesechanges are noted on the following pages.
In addition, with any of these approaches, you might need to maptwo or more classes to one table, if you have created some objectswith very few attributes.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 119/339
3
OOAD and Database Design 3-19Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 thetable, so no data is duplicated across tables.
Figure 3-2 Mapping One Table for Each Class
Classes
abstractPerson
personOID
firstNamelastNameaddress
Customer
customerOID
Employee
employeeOIDsalutation SSN
Tables
SSNemployeeOID
personOID firstName addresslastName
Person
Employee
personOIDsalutationcustomerOID
Customer
personOID
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 120/339
3
3-20 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Mapping Classes to Tables
One Table for Every Class
Note – personOID is not in the Customer and Employee classes in theobject model in Figure 3-2, but was added to the Customer andEmployee tables so that it can be used to look up information in thosetables. It is stored and maintained in all three tables.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 121/339
3
OOAD and Database Design 3-21Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 multipleroles.
It is easy to add an attribute to a class, because you affect only onetable. Maintenance is simple because there is no duplication. Youcan quickly create new subclasses by adding an additional table.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 122/339
3
3-22 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Mapping Classes to Tables
One Table for Every Class
Disadvantages
There are many tables to maintain.
It takes longer to read and write to the tables, because you mighthave 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 byusing database views.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 123/339
3
OOAD and Database Design 3-23Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Mapping Classes to Tables
One Table for Each Concrete Class
This approach has one table per concrete class (a class that is notabstract). Each table would contain all attributes for the class plus theattributes of the inherited class. Figure 3-3 shows mapping the Person,Employee, and Customer classes using this approach.
Figure 3-3 Mapping One Table for Each Concrete Class
Tables
salutationfirstName lastName customerOIDaddress
Customer
Classes
abstractPerson
firstNamelastNameaddress
Customer
customerOID
Employee
employeeIDsalutation SSN
SSNfirstName lastName employeeOIDaddress
Employee
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 124/339
3
3-24 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Mapping Classes to Tables
One Table for Each Concrete Class
Note – In Figure 3-3, each subclass has its own OID, because there is atable for each. personOID was removed from the abstractPerson classin the object model because there is no table in that class for thisapproach to table design.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 125/339
3
OOAD and Database Design 3-25Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 stilleasy, because all the data you need to access is available from onetable per class.
Disadvantages
To modify a class, you must modify its table and the tables for anysubclasses.
Data definitions are duplicated. In the Person abstract classexample, if a Person is both a Customer and an Employee, data forthe Person class is duplicated in both the Customer and Employeetables. Therefore, the data is difficult to maintain.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 126/339
3
3-26 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Mapping Classes to Tables
One Table for an Entire Class Hierarchy
This approach has one table for all attributes of all classes in thehierarchy. Figure 3-4 shows mapping the Person, Employee, andCustomer classes.
Figure 3-4 Mapping One Table for an Entire Class Hierarchy
Classes
Table
abstractPerson
firstNamelastNameaddresspersonOID
Customer
salutation
Employee
SSN
salutation SSNfirstName lastName personOIDaddress
Person
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 127/339
3
OOAD and Database Design 3-27Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 Personclass that has subclasses of Employee and Customer. With onetable for the entire class hierarchy, if the Person were to take ondifferent roles then all the necessary data is available.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 128/339
3
3-28 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Mapping Classes to Tables
One Table for an Entire Class Hierarchy
Disadvantages
Database tables can become extremely large. All fields are notneeded for all records; for example, the salutation field is requiredonly for customers, not employees.
It is difficult and costly to enforce rules on the database. Businessrules needed for only some fields are applied to all fields in therow, and the rules can conflict, slow performance, or both.
Each time you add a new attribute anywhere in the classhierarchy, the database table requires a change.
When you add a new column, if it cannot have a null value, youmust update all records with a value for that column.
Routine maintenance, such as removing damaged rows, takeslonger.
Many operations need to access the same table, which can reduceperformance.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 129/339
3
OOAD and Database Design 3-29Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Mapping Classes to Tables
Mapping Two Classes to One Table
In some situations, you might need to map two classes to onerelational table. Figure 3-5 shows an example.
Figure 3-5 Mapping Two Classes to One Table
Address
line1
PostalCode
postalCodeline2citystate
addressOID addressOID
Classes
Table
addressOID line1 postcodeOID
postcodeOID
line2 city state postalCode
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 130/339
3
3-30 Database Application Programming With Java TechnologyCopyright2000Sun 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 postalcode. You might want postal code to be a class of its own, so you canverify that the postal code is valid for a state and city. However, whenyou map to the relational table, you would combine the Address andPostal Code classes into one table.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 131/339
3
OOAD and Database Design 3-31Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Mapping Class Attributes to Table Columns
Once you have mapped classes to tables, you need to map the classattributes 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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 132/339
3
3-32 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Mapping Class Attributes to Table Columns
You need to understand how to manage data translation between theapplication and database so that there is no chance for data truncationor incorrect conversion. For every attribute to be stored on thedatabase, decide what its corresponding SQL data type will be.
Several of the Java types have two or more corresponding types inSQL, so you must decide how you will store data with these Java typesin the database.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 133/339
3
OOAD and Database Design 3-33Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Mapping Class Relationships to Tables
Now that you have mapped the classes to tables, you need to map theobject relationships to tables in the database.
Foreign keys are used to reference a row in another table, to implementclass relationships in their corresponding tables. If you store theprimary key from table A in table B, that primary key is a foreign keyfor table A.
To implement the one-to-one or one-to-many relationships in an objectmodel, you need a primary key in one table and a foreign key in theother. If you use the OID as the primary key, then that OID becomes aforeign key in the related table.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 134/339
3
3-34 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
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-6illustrates the one-to-one relationship.
Figure 3-6 One-to-One Relationship
Car
engOID
Engine
carOIDyearmodel
carOID engOID
Classes
1 1
model
Tables
carOID year doorsmodel
Car
doorscylindersserNum
engOID
engOID model serNumcylinders
Engine
carOID
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 135/339
3
OOAD and Database Design 3-35Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 classand an Engine class, with a corresponding table for each. It is a one-to-one relationship where the Car OID would be in the Engine table as aforeign key, or the Engine OID would be in the Car table as a foreignkey.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 136/339
3
3-36 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Mapping Class Relationships to Tables
One-to-Many Relationships
In a one-to-many relationship, for every one record in the first tablethere are one or more records in the second table. The OID of the classin the first table is added to the class of the second table.
Figure 3-7 shows tables for Order and OrderLine classes, which have aone-to-many relationship from Order to OrderLine (each order canhave one or more line items; each line item can have only one order).
Figure 3-7 One-to-Many Relationship Mapping
Order
isPrePaid
OrderLine
orderOIDnumberdateReceived
orderOID OLOID
Classes
1 *
quantity
Tables
OLOID
orderOID isPrePaid dateReceivednumber
Order
OrderLine
orderOID quantity
orderlines[ ]price
price
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 137/339
3
OOAD and Database Design 3-37Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 foreach order, so the orderOID is added to the OrderLine table. Add theorderLineOID to the Order table because you need an array in theOrder table to handle all the orderLineOIDs that are associated withthe order.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 138/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 139/339
3
OOAD and Database Design 3-39Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 Customercan have many Addresses and an Address can belong to manyCustomers. In this case, you can use a join table, such asCustomerAddress, to link the class attributes.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 140/339
3
3-40 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Mapping Class Relationships to Tables
Many-to-Many Relationships
Table 3-1 shows possible OID values in each of the three tables, withthe many-to-many relationships in boldface.
Table 3-2 Join Table in Many-to-Many Relationship
Address table Join table Customer table
addrOID addrOID custOID custOID
38 38 23 23
7 38 314 314
114 10 3 614
584 22 43 39
48 93 47 322
22 22 15 15
10 7 15 3
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 141/339
3
OOAD and Database Design 3-41Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Exercise: OOAD and Database Design
Exercise objective – Practice the concepts you have learned in thismodule.
Tasks
Go to the SL330 directory on your computer and change to the lab filesdirectory. Open the directory for this module, then the directory forthis exercise, and read the readme file. Follow the instructions in thatfile to complete this exercise.
If additional instructions or materials are required, your instructor willprovide them.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 142/339
3
3-42 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
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.
Experiences
Interpretations
Conclusions
Applications
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 143/339
3
OOAD and Database Design 3-43Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Check Your Progress
Before continuing on to the next module, check that you are able toaccomplish 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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 144/339
3
3-44 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Think Beyond
What additional features would you like to have available for use in adatabase application?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 145/339
4-1Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JDBC Advanced Topics 4
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 andchanged
This module describes the JDBC 1.0 topics of exception handling,metadata, transactions, and concurrency control.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 146/339
4
4-2 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Relevance
Discussion – Multi-user access to a database can require you to makedecisions, such as whether to allow changes that have not yet beencommitted. What similar situations might you encounter whenmanipulating data in a database?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 147/339
4
JDBC Advanced Topics 4-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Exceptions
Overview
When a Java application communicates with the database, thefollowing 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 theapplication. This is usually done using a SQLException, whichindicates any kind of error during a JDBC operation, or SQLWarning,which indicates nonfatal problems. To address exceptions, use atry/catch or throw construct.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 148/339
4
4-4 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Exceptions
SQLException
SQLException is different from other exceptions because it can have alist of exception objects.
In the SQLException class, the method getNextException returnsthe SQLException object that is next in line. In addition,getErrorCode returns an integer error code specified by the databasevendor, and getMessage returns a String error.
Possible failure points include:
JDBC-server communication, such as physical problems with theconnecting cable
Incorrectly formatted commands
Use of unsupported functions
Referencing records that do not exist
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 149/339
4
JDBC Advanced Topics 4-5Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Exceptions
SQLException
Many errors can occur on the server, such as attempting to selectcolumns that do not exist. An error is returned for each incorrectcolumn name.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 150/339
4
4-6 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Exceptions
SQLWarning
SQLWarning is a subclass of SQLException that is returned for non-fatal SQL states. SQLWarnings are not thrown; they are chainedtogether, and you can refer to them at any time. To retrieve them, callthe getWarnings method. You can call this method on severaldifferent objects: anything that could generate a warning, such as aConnection, all statement objects, and a ResultSet.
SQLWarning has the same methods as SQLException, except that youshould use getNextWarning, instead of getNextException.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 151/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 152/339
4
4-8 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Metadata
Database Metadata
Use the Connection.getMetaData method to retrieve databasemetadata.
This method returns a DatabaseMetaData reference that allows you touse a number of methods to get information about the database. Forexample, the isReadOnly method returns a boolean indicatingwhether the database is editable.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 153/339
4
JDBC Advanced Topics 4-9Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Metadata
Result Set Metadata
Use the ResultSetMetaData class to view information about a resultset. If you want to use the metadata for result set, call theResultSet.getMetaData method for your result set; it retrieves aResultSetMetaData reference.
Once the reference is retrieved, you can use a variety of methods toretrieve the information, such as getColumnCount to return an integer
that specifies the number of columns in the result set. You could theniterate through the columns and retrieve the column names.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 154/339
4
4-10 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Transactions
Overview
In database manipulation, a transaction is a logical group of workconsisting of one or more instructions. For example, the instructionsmight be to enter a customer record, create a new order record, add aline item to an order, and so on.
For a transaction to execute successfully, all of its instructions must besuccessfully executed for the database. If there is an error any time
during transaction execution, the previous operations must bereversed. This is referred to as backing out or performing a rollback ona transaction. Use transactions to partition work to minimize thechances of data corruption.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 155/339
4
JDBC Advanced Topics 4-11Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 commitprocess. In standard data manipulation, a connection by defaulthas auto-commit enabled. This means that every SQL statement isconsidered a transaction and is committed upon successfulcompletion 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 forStatement, PreparedStatement and CallableStatement).
To finalize the changes, call the commit method. Calling thecommit method on the connection makes all changes that have
been made since the previous commit/rollback permanent andreleases 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 rollbackmethod. Calling the rollback method on the connection drops allchanges that have been made since the previous commit/rollbackand releases any database locks currently held by thisConnection. This method should be used only when auto-commithas been disabled.
Note – Put a rollback in a catch block when performing exceptionhandling in transactional code.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 156/339
4
4-12 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Transactions
Basic Syntax
Syntax
In the following syntax, transactionEndMethod is either commit orrollback.
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 combinedinto 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 }
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 157/339
4
JDBC Advanced Topics 4-13Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Transactions
Concurrency ControlCreating a transaction in the JDBC API is handled through theConnection interface. For each connection, you can identify thetransaction isolation level, which determines what types of manipulationare 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 byanother transaction before any changes in that row have beencommitted.
Non-repeatable reads – When one transaction reads a row, asecond transaction alters the row, and the first transaction rereadsthe row, getting different values the second time.
Phantom reads – When one transaction reads all rows that satisfya WHERE condition, a second transaction inserts a row thatsatisfies that WHERE condition; the first transaction rereads forthe same condition, getting the additional row in the second read.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 158/339
4
4-14 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Transactions
Concurrency Control
To see the current isolation level, use the getTransactionIsolationmethod.
To set the transaction isolation level, call theConnection.setTransactionIsolation method.
The following static variables set the isolation level.
TRANSACTION_NONE – Indicates that transactions are notsupported. This is typically used to test whether a driver ordatabase supports transactions.
TRANSACTION_READ_UNCOMMITTED – Allows dirty reads,non-repeatable reads, and phantom reads. If any of the changesare rolled back, the second transaction will have retrieved aninvalid row.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 159/339
4
JDBC Advanced Topics 4-15Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Transactions
Concurrency Control
TRANSACTION_READ_COMMITTED – Prevents dirty reads.Non-repeatable reads and phantom reads can occur.
TRANSACTION_REPEATABLE_READ – Prevents dirty reads andnon-repeatable reads. Phantom reads can occur.
TRANSACTION_SERIALIZABLE – Prevents dirty reads, non-repeatable reads, and phantom reads.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 160/339
4
4-16 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Transactions
Concurrency Control
Syntax
conRefVar .setTransactionIsolation(Connection.isolationLevel);
Note – This method cannot be called while in the middle of atransaction.
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");
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 161/339
4
JDBC Advanced Topics 4-17Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Exercise: JDBC Advanced Topics
Exercise objective – Practice the concepts you have learned in thismodule.
Tasks
Go to the SL330 directory on your computer and change to the lab filesdirectory. Open the directory for this module, then the directory forthis exercise, and read the readme file. Follow the instructions in thatfile to complete this exercise.
If additional instructions or materials are required, your instructor willprovide them.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 162/339
4
4-18 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Exercise: JDBC Advanced Topics
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,or discoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 163/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 164/339
4
4-20 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Think Beyond
What additional features would be useful in a database application?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 165/339
5-1Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JDBC 2.0 Core Features 5
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 aquery
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 latestrelease of the JDBC API.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 166/339
5
5-2 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Relevance
Discussion – Should a result set show or hide changes that have beenmade to a database since it was retrieved? What advantages anddisadvantages are there for each approach?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 167/339
5
JDBC 2.0 Core Features 5-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 thejava.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 StandardExtensions.”
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 168/339
5
5-4 Database Application Programming With Java TechnologyCopyright2000Sun 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 drivervendors who want to be JDBC 2.0 compliant.
JDBC 2.0 is a superset of JDBC 1.0. The classes and interfaces in thejava.sql package works for database drivers for either specification,provided that you do not try to use the expanded JDBC 2.0functionality with a JDBC 1.0 driver. Core API features in the JDBC 2.0include:
Result set enhancements
Scrollability
Updatability
Enhancements to Statement, CallableStatement, andPreparedStatement, for batch updates
Advanced JDBC data types to support SQL3
Each of these features is covered in more detail in this module.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 169/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 170/339
5
5-6 Database Application Programming With Java TechnologyCopyright2000Sun 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 ResultSetcan be any of the following:
Forward-only
Scroll-insensitive Scroll-sensitive
The forward-only mode matches the functionality provided in JDBC1.0.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 171/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 172/339
5
5-8 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Result Set Enhancements
Scrollability
Scroll Settings
You can use the items listed in Table 5-1 to control scroll sensitivityand other aspects of the result set. (These are also listed in the Java 2Platform API Specification.)
Table 5-1 Field Summary
Field Type Description
CONCUR_READ_ONLY static int The concurrency mode for aResultSet object that you can notupdate.
CONCUR_UPDATABLE static int The concurrency mode for aResultSet object that you canupdate. You can update, insert,and delete rows in an updatableresult set.
FETCH_FORWARD static int The rows in a result set areprocessed in a forward direction;first-to-last.
FETCH_REVERSE static int The rows in a result set areprocessed in a reverse direction;last-to-first.
FETCH_UNKNOWN static int The order in which rows in a resultset are processed is unknown.
TYPE_FORWARD_ONLY static int The type for a ResultSet objectwhose cursor can move onlyforward.
TYPE_SCROLL_INSENSITIVE static int The type for a ResultSet objectthat is scrollable but not sensitiveto changes made by others.
TYPE_SCROLL_SENSITIVE static int The type for a ResultSet objectthat is scrollable and sensitive tochanges made by others.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 173/339
5
JDBC 2.0 Core Features 5-9Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 or2.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. Itestablishes the connection, then uses 2.0 features to create a scrollableresult 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");
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 174/339
5
5-10 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Result Set Enhancements
Scrollability
Scroll Settings
This example shows an example of an updatable, scroll-sensitivecursor that retrieves 25 rows at a time: To specify the number of rowsto 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");
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 175/339
5
JDBC 2.0 Core Features 5-11Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 byspecifying its position in the ResultSet. Relative positioning is theability to move to a row by specifying a new row that is forward agiven number of rows from the current row position.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 176/339
5
5-12 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Result Set Enhancements
Scrollability
Positioning
You can use the methods in Table 5-2 to move and position within theresult set; these methods and others not listed here are included in theAPI Specification.
Table 5-2 Methods
Method Type Description
absolute(int row) boolean Moves the cursor to the given rownumber in the result set.
afterLast() void Moves the cursor to the end of theresult set, just after the last row.
beforeFirst() void Moves the cursor to the front of theresult 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 inthe result set.
next() boolean Moves the cursor down one rowfrom its current position.
previous() boolean Moves the cursor to the previousrow in the result set.
relative(int) boolean Moves the cursor a relative
number of rows, either positive ornegative.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 177/339
5
JDBC 2.0 Core Features 5-13Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Result Set Enhancements
Scrollability
Positioning
The JDBC 2.0 API also provides methods for you to determine whereyou 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 isafter 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 onthe first row of the result set.
isLast() boolean Indicates whether the cursor is onthe last row of the result set.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 178/339
5
5-14 Database Application Programming With Java TechnologyCopyright2000Sun 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 scrollcursor. This provides the capability of using one query to readmultiple rows from a database, then update rows in the database oneat a time. You can update, delete, and insert rows.
You can update a result set if the concurrency type isCONCUR_UPDATABLE. You can use the
Statement.getResultSetConcurrency method to determine what aresult set’s concurrency type is currently set to. The statementconstructor allows you to set the concurrency type. Table 5-1 on page5-8 lists concurrency types.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 179/339
5
JDBC 2.0 Core Features 5-15Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 callingupdateXXX. The update performed on the result set is not applied tothe underlying database until you call updateRow. If you move thecursor from the current row before calling updateRow, then the update
is discarded. In addition, you can call cancelRowUpdate to explicitlycancel the updates, but you must call it before you make a call toupdateRow.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 180/339
5
5-16 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Result Set Enhancements
Updatability
Deleting a Row
Syntax
resultsetRefVar .deleteRow();
Example
The following example shows how to delete a row. The sixth row inthe 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 thecursor at the next empty row for creating the context of a new row.
Use the same updateXXXmethods to set the values of specific columnsof the insert row before inserting it into the database with insertRow.A ResultSet tracks the previous cursor position while the cursor istemporarily positioned at the insert row, and the cursor isautomatically returned to that cursor position after the insert iscompleted.
Syntax
Write an updateXXX statement for each column to update.
resultsetRefVar .movetoInsertRow();
resultsetRefVar .updateXXX (column, value);
resultsetRefVar .insertRow();
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 181/339
5
JDBC 2.0 Core Features 5-17Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Result Set Enhancements
Updatability
Inserting a New Row
Example
The following example shows how to insert a new row into theResultSet and database.
1 rs.moveToInsertRow(); rs.updateString(1, "100050");
2 rs.updateFloat(2, 80000.0f);3 rs.insertRow();
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 182/339
5
5-18 Database Application Programming With Java TechnologyCopyright2000Sun 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 APIdoes not specify an exact set of SQL queries that yield an updatableresult set. This is regardless of whether concurrency is set toCONCUR_UPDATABLE.
Queries that meet the following criteria can produce an updatableResultSet. Other scenarios depend on the JDBC driver vendor’simplementation.
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, andall columns that do not have a default value.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 183/339
5
JDBC 2.0 Core Features 5-19Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Statement Enhancements for Batch Updates
The batch update feature allows you to submit multiple SQLcommands to a database for processing at once. Submitting multipleupdates together, instead of individually, can greatly improveperformance in some situations.
The JDBC API cannot perform any operation during batch processingthat would produce a result set; if a result set is produced, anexception is thrown. This ensures that you do not write code that cangenerate multiple ResultSet objects during batch operations. Anyattempt 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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 184/339
5
5-20 Database Application Programming With Java TechnologyCopyright2000Sun 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, tothe underlying DBMS. In the following example, all of the updateoperations required to insert a new employee record into a companydatabase 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();
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 185/339
5
JDBC 2.0 Core Features 5-21Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Statement Enhancements for Batch Updates
Statement
Example
1 con.setAutoCommit(false);
2 Statement stmt = con.createStatement();
3 stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Mays')");
4 stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");
5 stmt.addBatch("INSERT INTO emp_dept VALUES (1000, 260)");
6 int[] updateCounts = stmt.executeBatch();
7 con.commit();
In this example, auto-commit mode is disabled to prevent the JDBCAPI from committing the transaction when theStatement.executeBatch method is called. Disabling autocommitallows the application to decide whether to commit the transaction inthe event that an error occurs and some of the commands in a batchfail to execute. For this reason, you should usually turn off auto-commit mode when you do batch updates.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 186/339
5
5-22 Database Application Programming With Java TechnologyCopyright2000Sun 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 commandsthat can be submitted together for execution. When a statement iscreated, its associated list of commands is empty. TheStatement.addBatch method adds an element (a SQL command) tothe calling statement’s 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 ManipulationLanguage (DML) commands that return a simple update count can beexecuted as part of a batch. You can call the methodStatement.clearBatch to reset a batch if the application decides notto submit a batch of commands that has been constructed for astatement.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 187/339
5
JDBC 2.0 Core Features 5-23Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Statement Enhancements for Batch Updates
Statement
The Statement.executeBatch method submits a batch of commandsto the underlying DBMS for execution. Commands are executed in theorder in which they were added to the batch. The executeBatch
method returns an array of update counts for the commands that wereexecuted. The array contains one entry for each command in the batch,and the elements in the array are ordered according to the order inwhich the commands were executed (which, again, is the same as theorder in which the commands were originally added to the batch).
Calling executeBatch closes the calling Statement object’s currentresult set if one is open. The statements’s internal list of batchcommands for the rest of the statements is reset to empty onceexecuteBatch returns.
The executeBatch method throws a BatchUpdateException if anyof the commands in the batch fail to execute properly. You can call theBatchUpdateException.getUpdateCounts method to return aninteger array of update counts (int data types) for the commands inthe batch that were executed successfully.
The executeBatchmethod stops when the first command returns anerror, and commands are executed in the order that they are added tothe batch. Thefore, if the array returned byBatchUpdateException.getUpdateCounts contains n elements, thismeans that the first n commands in the batch executed successfullywhen executeBatch was called.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 188/339
5
5-24 Database Application Programming With Java TechnologyCopyright2000Sun 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 associatemultiple sets of input parameter values with a singlePreparedStatement object. The sets of parameter values can then besent to the underlying DBMS engine for execution as one unit.
The following example inserts two new employee records into adatabase as a single batch. The PreparedStatement.setXXX methods
create each parameter set (one for each employee), and thePreparedStatement.addBatch method adds a set of parameters tothe current batch.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 189/339
5
JDBC 2.0 Core Features 5-25Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 theupdates to the DBMS, then commit. Error handling in the case of PreparedStatement objects is analogous to error handling forStatement objects.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 190/339
5
5-26 Database Application Programming With Java TechnologyCopyright2000Sun 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 withCallableStatement objects as it does with PreparedStatement
objects. You can associate multiple sets of input parameter values witha callable statement and send them to the DBMS together.
Stored procedures invoked using the batch update facility with acallable statement:
Must return an update count
Cannot have out or inout parameters
This means that you can perform batch operations onCallableStatement objects, such as database stored procedures, butyou cannot have any values in the CallableStatement that canpotentially be output. The CallableStatement.executeBatchmethod should throw an exception if this restriction is violated.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 191/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 192/339
5
5-28 Database Application Programming With Java TechnologyCopyright2000Sun 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 SQL3types.
A Blob instance maps a SQL BLOB instance (stores a large amountof binary data, such as images, audio files, and objects; size istypically 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 typicallydatabase 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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 193/339
5
JDBC 2.0 Core Features 5-29Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Advanced Data Types
Using SQL3 Data Types
Retrieve, store, and update SQL3 data types the same way you doother data types. Use either ResultSet, getXXX, orCallableStatement.getXXX methods to retrieve them,PreparedStatement.setXXX methods to store them, and updateXXX
methods to update them. Approximately 90 percent of the operationsperformed on SQL3 types involve using the getXXX, setXXX, andupdateXXX methods.
Table 5-4 shows which methods to use.
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 Statementobject.
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 storedin the table students in the row for student 2238.
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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 194/339
5
5-30 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
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 }
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 195/339
5
JDBC 2.0 Core Features 5-31Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 CLOB’s 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 }
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 196/339
5
5-32 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Advanced Data Types
Blob, Clob,andArrayObjects
An important feature of Blob, Clob, and Array objects is that you canmanipulate them without having to bring all of the data from thedatabase server to your client machine. An instance of any of thesetypes is actually a logical pointer to the object in the database that theinstance represents. A SQL BLOB, CLOB, or ARRAY object can be large, sothis 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 actualobject in the database. However, if you want to work with any of themas an object in the Java programming language, you need to bring alltheir data to the client, which is referred to as materializing the object.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 197/339
5
JDBC 2.0 Core Features 5-33Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Advanced Data Types
Blob, Clob,and ArrayObjects
For example, if you want to use a SQL ARRAY object in an applicationas if it were an array in the Java programming language, you need tomaterialize the ARRAY object on the client and then convert it to anarray in the Java programming language. Then you can use arraymethods in the Java programming language to operate on theelements of the array. The interfaces Blob, Clob, and Array all havemethods for materializing the objects they represent.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 198/339
5
5-34 Database Application Programming With Java TechnologyCopyright2000Sun 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 auser can define in SQL. They are often referred to as UDTs (user-defined types), and you create them with a SQL CREATE TYPEstatement.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 199/339
5
JDBC 2.0 Core Features 5-35Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Advanced Data Types
Structured Types
A SQL structured type is similar to structured types in the Javaprogramming language in that it has members, called attributes, thatcan be of any data type. In fact, an attribute can be another structuredtype.
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 )
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 200/339
5
5-36 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Advanced Data Types
Structured Types
Unlike Blob, Clob, and Array objects, a Struct object contains valuesfor each of the attributes in the SQL structured type and is not just alogical pointer to the object in the database. For example, suppose thata 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 valueof -5, the Struct object point contains the values 3 and -5.
You might have noticed that Struct is the only type not to have agetXXX and setXXX method with its name as XXX. You must usegetObject and setObject with Struct instances. This means thatwhen you retrieve a value using the method getObject, you get anObject in the Java programming language that you must explicitlycast to a Struct, as was done in the previous code example.
You can retrieve the internal values by calling the getAttributesmethod.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 201/339
5
JDBC 2.0 Core Features 5-37Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Advanced Data Types
Distinct Types
The second SQL type that a user can define in a SQL CREATE TYPEstatement is a distinct type. A SQL distinct type is similar to a typedefin C or C++ because it is a new type based on an existing type. Thefollowing 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 decimalpoint. 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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 202/339
5
5-38 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Advanced Data Types
Distinct Types
A SQL distinct type is mapped to the type in the Java programminglanguage to which its underlying type would be mapped. Forexample, NUMERICmaps tojava.math.BigDecimal, so the type MONEYmaps to java.math.BigDecimal. To retrieve a MONEY object, useResultSet.getBigDecimalor CallableStatement.getBigDecimal;to store a MONEY object, use PreparedStatement.setBigDecimal.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 203/339
5
JDBC 2.0 Core Features 5-39Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Advanced Data Types
SQL3 Advanced Features
The Struct interface is the standard mapping for a SQL structuredtype. To make working with a SQL structured type easier, you canmap it to a class in the Java programming language. The structuredtype becomes a class, and its attributes become fields. You do not haveto 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 manyattributes or if the attributes are themselves large. To reference astructured type, you can declare a SQL REF type that represents aparticular structured type. A SQL REF object is mapped to a Ref objectin the Java programming language, and you can operate on it as if youwere operating on the structured type object that it represents.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 204/339
5
5-40 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Exercise: JDBC 2.0 Core Features
Exercise objective – Practice the concepts and tasks you have learnedin this module.
Tasks
Go to the SL330 directory on your computer and change to the lab filesdirectory. Open the directory for this module, then the directory forthis exercise, and read the readme file. Follow the instructions in thatfile to complete this exercise.
If additional instructions or materials are required, your instructor willprovide them.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 205/339
5
JDBC 2.0 Core Features 5-41Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 206/339
5
5-42 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Check Your Progress
Before continuing on to the next module, check that you are able toaccomplish or answer the following:
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 aquery
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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 207/339
5
JDBC 2.0 Core Features 5-43Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Think Beyond
An application must specify a JDBC URL when connecting to adatabase using the driver manager. Would this be restricting at times?What system could make it easier to change the URL?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 208/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 209/339
6-1Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JDBC 2.0 Standard Extensions 6
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 aparticular driver
Describe how connection pooling is used to connect an applicationto a database
Understand how distributed transactions work
Explain how to use row sets to encapsulate rows for use with the JavaBeans™ component model
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 210/339
6
6-2 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Relevance
Discussion – So far, you have learned that you need to establish aconnection each time you want to connect to the database. Whatadvantages would there be in a system that provided an existingsupply of connections?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 211/339
6
JDBC 2.0 Standard Extensions 6-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
References
Additional resources – The following resources can provideadditional detail on the topics presented in this module:
javax.sql package download page and JDBC 2.0 StandardExtension 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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 212/339
6
6-4 Database Application Programming With Java TechnologyCopyright2000Sun 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 toimplement them. The features are included in the javax.sql package,which is included in the Java 2 Platform, Enterprise Edition, and alsofrom 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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 213/339
6
JDBC 2.0 Standard Extensions 6-5Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JNDI
Overview
The Java Naming and Directory Interface (JNDI) is a standardextension to the Java platform, providing Java technology-enabledapplications with a uniform way for applications to find and accessremote services over the network. This allows you to connectseamlessly 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 enterpriseservice, including a messaging service or application-specific service.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 214/339
6
6-6 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
JNDI
JNDI Advantages
As described in Module 1, ‘‘JDBC Overview,” an application canconnect to a database using the JDBC driver manager. In thisapproach, the JDBC driver that is used to create a database connectionmust first be registered with the JDBC driver manager.
For example, when the driver class includes an appropriate staticinitializer, the following statement loads and registers the JDBC driverimplemented 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 driverspecific to a particular vendor’s product and, therefore, non-portable.In addition, an application must specify a JDBC URL when connectingto a database using the driver manager:
Connection con = DriverManager.getConnection
("jdbc:vendorX_subprotocol:machineY:portZ");
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 215/339
6
JDBC 2.0 Standard Extensions 6-7Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JNDI
JNDI Advantages
This code demonstrates that a JDBC URL might be specific not only toa particular vendor’s JDBC product, but also to a particular machinename and port number on that machine. This can make the applicationdifficult to maintain because the computing environment changes.
Using JNDI with JDBC solves these problems by allowing anapplication to specify a logical name that JNDI associates with aparticular data source. This makes deploying and maintaining JDBC
applications easier. The driver is specified using two separateprograms:
One program associates the driver with a data source name youchoose.
The second program references that data source name.
This makes changing the driver easier, because you need to change itin only one place.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 216/339
6
6-8 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
JNDI
JDBCDataSource
A JDBC DataSource object is a Java programming language instanceof the javax.sql.DataSource interface. A data source object is afactory for JDBC connections.
1 public interface DataSource {
2 Connection getConnection() throws SQLException;
3 Connection getConnection(String username, String password) throws
4 SQLException;
5 ...
6 }
Like other interfaces in the JDBC API, such as java.sql.Connectionand java.sql.ResultSet, implementations of javax.sql.DataSource are provided by JDBC driver vendors as partof their JDBC 2.0 products.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 217/339
6
JDBC 2.0 Standard Extensions 6-9Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JNDI
JDBCDataSource
A class that implements the DataSource interface provides a set of properties that must be given values so that a connection to aparticular data source can be made. These properties, which follow thedesign pattern specified for JavaBeans model components, are usuallyset when a data source object is used. Examples of data sourceproperties include the location of the database server, the name of thedatabase, the network protocol to use to communicate with the server,and so on.
The JDBC 2.0 API specifies the following standard names for datasource 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 sourcefunctionality
description String Description of this data source
networkProtocol String Network protocol used tocommunicate with the server
password String A database password
portNumber int Port number where a serverlistens for requests
roleName String The initial SQL role name
serverName String Database server name
user String User’s account name
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 218/339
6
6-10 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
JNDI
JDBCDataSource
A data source must support the description property. Support for theother properties listed is not required because they might not beneeded by all data sources. However, if a data source needs to use oneof the properties listed in Table 6-1, it must use the standard propertyname.
The standard properties are included in the JDBC specification to
encourage uniformity among data sources from different vendors. Forexample, this standardization allows you to write a utility that listsavailable data sources and their descriptions along with otherinformation if it is available.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 219/339
6
JDBC 2.0 Standard Extensions 6-11Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JNDI
JDBCDataSource
For each property, you must be able to write to it and read it usingaccessor and mutator methods.
For example, if sds denotes a data source object that supports theserverName 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 propertiesand their accessor methods.
The accessor and mutator methods for a property are defined on theimplementation class and not in the DataSource interface. This createssome separation between the management API for DataSource objectsand the API used by applications. Applications should not need toaccess or change properties, but management tools can access themusing 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-specificname for the property.
The JDBC 2.0 API specifies a simple policy for assigning JNDI namesto data sources. All JDBC data sources should be registered in the jdbcnaming subcontext of a JNDI namespace, or in one of its childsubcontexts. The JDBC subcontext is the child of the root namingcontext.
You can use JNDI to complete the first and second steps of the JDBCprocess: registering the driver and connecting to the database.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 220/339
6
6-12 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
JNDI
Registering a DataSourceObject
To register the driver, you associate it with the DataSource object.
You can create, deploy, and manage a DataSource object within JNDIseparately from the Java applications that use it. This section describesthe 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 );
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 221/339
6
JDBC 2.0 Standard Extensions 6-13Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JNDI
Registering a DataSourceObject
Example
This example registers a data source object with a JNDI namingservice.
1 SampleDataSource sds = new SampleDataSource();
2 sds.setServerName("akron");
3 sds.setDatabaseName("accounts-payable");
4 Context ctx = new InitialContext();5 ctx.bind("jdbc/AccountMain", sds);
The first line of code in the example creates a data source object. TheSampleDataSource class implements the javax.sql.DataSourceinterface. (A JDBC driver vendor supplies the SampleDataSource
class.) The next two lines initialize the data source’s properties. Then, a Java programming language object that references the initial JNDInaming context is created by calling the InitialContext constructor,which is provided by JNDI. System properties (not shown) are used totell JNDI the service provider to use.
The JNDI name space is hierarchical; this is similar to the directorystructure of many file systems. The data source object is bound to alogical JNDI name by calling Context.bind. In this case, the JNDIname identifies a subcontext, jdbc, of the root naming context and alogical name, “EmployeeDB,” within the jdbc subcontext. This code issufficient 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 graphicaluser interface (GUI) tool to deploy a data source object.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 222/339
6
6-14 Database Application Programming With Java TechnologyCopyright2000Sun 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 applicationcan 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");
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 223/339
6
JDBC 2.0 Standard Extensions 6-15Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JNDI
Establishing a Connection Using JNDI
The first line in the example creates a Java object that references theinitial JNDI naming context. Next, the initial naming context does alookup operation using the logical name of the data source. TheContext.lookup method returns a reference to a Java object, which isnarrowed to a javax.sql.DataSource object. In the last line, theDataSource.getConnection method is called to produce a databaseconnection.
Note – The DataSource feature provides an alternative to the JDBCDriverManager, essentially duplicating all of the driver manager'suseful functionality. Although the same application can use bothmechanisms, it is a good idea to regard the DriverManager as a legacyfeature of the JDBC API. Applications should use the JNDIDataSource API whenever possible. A JDBC implementation that isaccessed using the DataSource API should not automatically registeritself with the DriverManager.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 224/339
6
6-16 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Connection Pooling
Note – For an example of using connection pooling, refer to AppendixB of the JDBC 2.0 Standard Extension API, included in the lab files forthis course.
Overview
A connection pool is a cache of database connections that ismaintained 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 Webserver capable of running Java applications.
The application does not register drivers; middle-tier code does theregistration. Connection pooling can simplify client code becauseclients no longer have to deal with registering a driver.
You can use connection pooling to complete step 2 of the JDBCprocess, establishing a connection.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 225/339
6
JDBC 2.0 Standard Extensions 6-17Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Connection Pooling
Overview
Connection pooling has no impact on the code that you write. Yousimply take advantage of a connection pool that has beenimplemented in the driver, rather than writing code yourself.
Figure 6-1 provides an example of the basic components that mightcompose a distributed, three-tier application that uses the JDBC 2.0API’s connection-pooling feature.
Figure 6-1 Three-tier Application Using Connection Pooling
In Figure 6-1, the client portion of the application is shown invokingsome application code—for 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 theDataSource interface in the standard way to obtain a Connection
object. The DataSource implementation performs connection poolingand is implemented, in this case, by the middle-tier server vendor. Theconnection pooling implementation uses the features provided by the
JDBC 2.0 driver vendor to implement the connection cachingalgorithm that it chooses.
The three parts of this example are performed by the JDBC drivervendor, the middle-tier server vendor, and the application developer.
Client(browser)
NetworkApplication code
Middle-tier server code
JDBC driver
DataSource
ConnectionPoolDataSource
Tier 1 Tier 2 Tier 3
NetworkDBMS
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 226/339
6
6-18 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Connection Pooling
OverviewTo support connection pooling, a JDBC driver vendor must provide animplementation of the javax.sql.ConnectionPoolDataSourceinterface. This interface and the closely relatedjavax.sql.PooledConnection interface (not shown in Figure 6-1)provide methods—or hooks—that enable a third party, such as amiddle-tier server vendor to implement connection pooling as a layeron top of the JDBC API.
The JDBC 2.0 API provides hooks to support connection poolinginstead 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 alsoprovide connection pooling implementations.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 227/339
6
JDBC 2.0 Standard Extensions 6-19Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Connection Pooling
Connecting
A party, such as a middle-tier server vendor, who wants to implementconnection pooling should provide a data source class (a class thatimplements the javax.sql.DataSource interface) to interact withtheir particular connection pooling implementation. Application codethat 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 aconnection.
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();
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 228/339
6
6-20 Database Application Programming With Java TechnologyCopyright2000Sun 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 (adatabase, or other entity), that need to be committed as onetransaction. For example, moving money from an account in one bankto an account in another is a distributed transaction.
Support for distributed transactions allows a JDBC driver to supportthe standard two-phase commit protocol used by the Java Transaction
API (JTA). JDBC driver support for distributed transactions allows youto write Enterprise JavaBeans that are transactional across multipleDBMS servers.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 229/339
6
JDBC 2.0 Standard Extensions 6-21Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Distributed Transactions
Architecture
Figure 6-2 shows a simplified example of the basic components in adistributed, three-tier application that uses the distributed transactionfeatures in the JDBC 2.0 API.
Figure 6-2 Components of Application Using DistributedTransactions
Client(browser)
NetworkApplication code
Middle-tier server code
JDBC driver
DataSource
XADataSource
Tier 1 Tier 2 Tier 3
Network
T r an s a c t i onm an a g er
DBMS
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 230/339
6
6-22 Database Application Programming With Java TechnologyCopyright2000Sun 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 thatexecutes in a middle-tier server environment. The middle-tier servercould be a Web server supporting Java technology, an Enterprise
JavaBeans server, or some other type of application server thatsupports the Java programming language. The middle-tier applicationcode 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 codethat you write. The application code uses the DataSource interface inthe standard way to obtain a Connection object. The DataSourceimplementation, which the middle-tier server vendor provides,interacts with the transaction manager to set up the transactionalenvironment for the Connection returned to the application, andtypically maintains a pool of database connections to achievemaximum performance. The DataSource implementation uses thefeatures provided by the JDBC 2.0 driver vendor to implement
connection pooling and to enable distributed transactions.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 231/339
6
JDBC 2.0 Standard Extensions 6-23Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Distributed Transactions
Implementation
To support distributed transactions, a JDBC driver vendor mustprovide implementations of the javax.sql.XADataSource andjavax.sql.XAConnection interfaces. These interfaces are similar tothe ConnectionPoolDataSource and PooledConnection interfaces.They provide the same hooks to enable connection pooling, and addthe ability to do distributed transactions.
A middle-tier server vendor who wants to support distributedtransactions should provide a data source class—an implementation of the javax.sql.DataSource interface—that interacts with the middle-tier server’s transaction infrastructure.
The transaction infrastructure includes a transaction manager, such asan implementation of the Java Transaction Service API, and a JDBCdriver that supports the JDBC 2.0 API. You can retrieve instances of this data source class from JNDI using application code executing inthe middle tier that obtains a database connection in the usual manner.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 232/339
6
6-24 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Distributed Transactions
Implementation
Note – Distributed transactions do not impact application codesignificantly. However, there are coding differences of which youshould be aware. There are differences because the JDBC API assumesthat distributed transaction boundaries are controlled by either themiddle-tier server or another API, such as the user transaction portionof the Java Transaction API.
Distributed transactions are intended to be used by component-basedtransactional applications that operate in a modern application serverenvironment, such as an Enterprise JavaBeans server, in whichdeclarative transactions are used.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 233/339
6
JDBC 2.0 Standard Extensions 6-25Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Distributed Transactions
Implementation
Transaction boundaries are controlled by the middle-tier server, so theapplication code must not call the Connection.commit orConnection.rollback methods. These methods throw aSQLException if they are called.
In addition, the Connection object that is returned by a DataSourcewhen distributed transactions are being done has autocommit modeturned off by default. If you attempt to enable autocommit mode by
calling Connection.setAutoCommit with a value of true, aSQLException is thrown.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 234/339
6
6-26 Database Application Programming With Java TechnologyCopyright2000Sun 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 retrievedfrom 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 addssupport to the JDBC API for the JavaBeans component model. TheRowSet interface inherits from the ResultSet interface.
The RowSet object provides a way to represent the rows so that theycan be used with the JavaBeans component model; a RowSet object is a
JavaBean that can be combined with other components in anapplication. You can create row sets at design time and use them inconjunction 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 orupdatable result sets when the underlying JDBC driver does notsupport them.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 235/339
6
JDBC 2.0 Standard Extensions 6-27Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Row Sets
Overview
You can serialize a row set implementation.
A row set might maintain an open database connection. When a rowset is disconnected from its data source, updates performed on the rowset are propagated to the underlying database using an optimisticconcurrency control algorithm.
Unlike statements and result sets, row sets are not tied to a specificconnection. A row set is affiliated with a connection only for theduration of its use with a particular query.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 236/339
6
6-28 Database Application Programming With Java TechnologyCopyright2000Sun 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 differentneeds. There are two categories: row sets that are connected and thosethat are disconnected.
Disconnected Row Sets
A disconnected row set obtains a connection to a data source to get orchange data in the data source, but most of the time it does not have aconnection open. While it is disconnected, it does not need a JDBCdriver or the full JDBC API, so its footprint is small. A row set is anideal format for sending data over a network to a thin client.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 237/339
6
JDBC 2.0 Standard Extensions 6-29Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Row Sets
Types of Row Set Implementations
Disconnected Row Sets
Because it is not continually connected to its data source, adisconnected row set stores its data in memory. It needs to maintainmetadata about the columns it contains and information about itsinternal state. It also needs a way to make connections, for executingcommands, 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 longas the row set is in use.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 238/339
6
6-30 Database Application Programming With Java TechnologyCopyright2000Sun 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 allowyou to configure a RowSet instance to connect to a data source andretrieve a set of rows, as shown in the following example.
1 rset = new RowSet();
2 rset.setDataSourceName("jdbc/SomeDataSourceName");3 rset.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
4 rset.setCommand("SELECT NAME, BREED, AGE FROM CANINE");
This example uses a variable rset of type RowSet, and sets threeRowSet properties: data source name, transaction isolation, andcommand. The data source name property is used by a RowSet to lookup a JDBC DataSource object in a JNDI naming service. (JDBC datasources are the most common type of data source used by row sets.)
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 239/339
6
JDBC 2.0 Standard Extensions 6-31Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Row Sets
Row Sets at Design Time
Properties
The DataSource object is used internally to create a connection to theunderlying data source. The transaction isolation property specifiesthat only data that was produced by committed transactions can beread by the row set. Lastly, the command property specifies acommand that is executed to retrieve a set of rows. In this case the
NAME, BREED, and AGE columns for all rows in the CANINE tableare retrieved.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 240/339
6
6-32 Database Application Programming With Java TechnologyCopyright2000Sun 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 animportant event on a row set occurs. A component that wishes toregister for RowSet events must implement the RowSetListenerinterface. Event listeners are registered with a row set by calling the
addRowSetListenermethod, as shown in the following example. Anynumber of listeners can be registered with an individual RowSetobject.
RowSetListener listener ...;
rset.addRowSetListener(listener);
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 241/339
6
JDBC 2.0 Standard Extensions 6-33Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Row Sets
Row Sets at Design Time
Events
Row sets can generate three different types of events.
Cursor movement events indicate that the row set’s cursor hasmoved.
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 setchanged. For example, this can happen when RowSet.execute iscalled.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 242/339
6
6-34 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Row Sets
Row Sets at Design Time
Events
When an event occurs, an appropriate listener method is called tonotify 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, whichidentifies the source of the event when an event occurs.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 243/339
6
JDBC 2.0 Standard Extensions 6-35Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 SQLcommand that takes no input parameters was used. However, a rowset 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 inputparameter. The RowSet.setString method is used to pass the inputparameter value to the RowSet. Typically, the command property isspecified at design time, while parameters are not set until runtimewhen their values are known.
rset.setCommand("SELECT NAME, BREED, AGE FROM CANINE WHERE NAME = ?");
rset.setString(1, "spot");
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 244/339
6
6-36 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Row Sets
Row Sets at RuntimeTraversing a Row Set
The javax.sql.RowSet interface extends the java.sql.ResultSetinterface, so in many ways a row set behaves just like a result set. Infact, most components that make use of a RowSet component willlikely 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 rowset; it is the same process that would be used for a result set.
1 // iterate forward through the row set
2 rset.beforeFirst();
3 while (rset.next()) {
4 System.out.println(rset.getString(1) + " " + rset.getFloat(2));
5 }
You iterate backward through the row set, positioning the cursor to aspecific row, and so on in the same way as a result set.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 245/339
6
JDBC 2.0 Standard Extensions 6-37Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 exactproperties 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 toconnect to a JDBC data source.
The current contents of the row set, if any, are lost when an executemethod is called.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 246/339
6
6-38 Database Application Programming With Java TechnologyCopyright2000Sun 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 animplementation easier, the Java Software division of Sun Microsystemsplans to provide reference implementations for three different styles of row sets in the future.
A CachedRowSet class – Currently available fromhttp://java.sun.com/products/jdbc. It is a disconnected rowset 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 athin wrapper around a ResultSet object to make a JDBC driverlook like a JavaBeans component.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 247/339
6
JDBC 2.0 Standard Extensions 6-39Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Overview of Row Set Implementation
A WebRowSet class – A connected row set that uses the HTTPprotocol internally to talk to a Java technology servlet thatprovides data access. This is used to make it possible for thin Webclients 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 togive a preview of the types of row set implementations that will likely
be available in the future.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 248/339
6
6-40 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Check Your Progress
Before continuing on to the next module, check that you are able toaccomplish or answer the following:
List the features in the JDBC 2.0 Standard Extension API
Understand how to use Java Naming and Directory Interfacefunctionality to reduce the dependence of a JDBC program on aparticular driver
Describe how connection pooling is used to connect an applicationto a database
Understand how distributed transactions work
Explain how to use row sets to encapsulate rows for use with the JavaBeans component model
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 249/339
6
JDBC 2.0 Standard Extensions 6-41Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Think Beyond
What elements might be necessary in an implementation of theCachedRowSet class?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 250/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 251/339
7-1Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
RowSetImplementation 7
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 CachedRowSetimplementation
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 252/339
7
7-2 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Relevance
Discussion – How would you modify your application to retrieve datafrom a different source of data, such as a spreadsheet?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 253/339
7
Row Set Implementation 7-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
CachedRowSetClass Overview
The CachedRowSet class is similar to row set implementations thatprovide a disconnected, serializable, scrollable container for tabulardata. 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 iscached in memory, CachedRowSets are not appropriate for extremelylarge data sets.
Note – The CachedRowSet implementation is available athttp://java.sun.com/products/jdbc
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 254/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 255/339
7
Row Set Implementation 7-5Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
CachedRowSetClass Overview
CachedRowSets can also provide scrolling and updating forResultSets that do not provide these capabilities themselves. Youcan use a CachedRowSet to augment the capabilities of a JDBCdriver that does not have full support for scrolling and updating.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 256/339
7
7-6 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Creating aCachedRowSet
A CachedRowSet is a JavaBean, so CachedRowSet instances are oftencreated by a visual Beans development tool when an application isassembled. Applications can also create instances at runtime using anypublic constructor that the CachedRowSet class provides.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 257/339
7
Row Set Implementation 7-7Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Retrieving Data
A CachedRowSet object can contain data retrieved using a JDBC driveror data from some other source, such as a file. CachedRowSet objectsusually contain data that was fetched from a SQL database using
JDBC. One way to get data into a CachedRowSet is to call theCachedRowSet.populate method (defined on the CachedRowSetclass), as shown in the following example.
1 ResultSet rs = stmt.executeQuery
("SELECT NAME, SALARY FROM EMPLOYEE");
2 CachedRowSet crset = new CachedRowSet();
3 crset.populate(rs);
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 258/339
7
7-8 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Retrieving Data
The example uses a variable stmt of type Statement. The populatemethod takes a parameter that is a ResultSet containing some data.The populate method reads the contents of the ResultSet, andcaches the contents in the CachedRowSet object.
You can use the term disconnected to describe a CachedRowSet.Disconnected means that a CachedRowSet object caches its dataoutside of a data source. Once the populate method returns, theCachedRowSet object does not maintain a connection to theunderlying 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/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 259/339
7
Row Set Implementation 7-9Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Retrieving Data
Another way to get data into a CachedRowSet object is to call theexecutemethod. There are two forms of execute: one method takes aConnection object as a parameter and the other that does not.
If a Connection is passed to execute, then there is no need to setproperties ahead of time to enable data source connectivity. However,execute always requires that a command be specified using thecommand property. The CachedRowSet only makes use of the JDBCconnection briefly while data is being read from the database and usedto populate it with rows. To use the execute method, you should callit once you have set the appropriate properties.
1 // There is already a connection associated
2 // with the CachedRowSet
3 CachedRowSet crset = new CachedRowSet();
4 crset.setCommand(
"SELECT year, model FROM car WHERE manufacturer = FORD");
5 crset.execute();
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 260/339
7
7-10 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Retrieving Data
In this case, because a Connection is not passed to the executemethod, the CachedRowSet must create a Connection internally anduse it to retrieve a set of rows. (This approach is based on theassumption that a JDBC data source is being accessed.)
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 261/339
7
Row Set Implementation 7-11Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Accessing Data
The contents of a CachedRowSet are accessed using methods inheritedfrom the ResultSet interface. A CachedRowSet is always scrollable,and its type is ResultSet.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 262/339
7
7-12 Database Application Programming With Java TechnologyCopyright2000Sun 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 itscurrent value. The original value is set by methodsCachedRowSet.execute and populate. For example, when execute
is called, the original value is typically assigned the set of rowsreturned by executing the row set’s command. After calling execute
(or populate) the original value and the current value are the same.
The CachedRowSet.updateXXX methods (which are inherited fromResultSet) can be called to update the current value of aCachedRowSet. Calling an updateXXX method does not affect theoriginal value, or the values stored in the underlying data source. Onlythe current value of the CachedRowSet, which is cached in memory, ischanged.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 263/339
7
Row Set Implementation 7-13Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Modifying Data
The following example illustrates these concepts.
When CachedRowSet.execute is called in the first line of theexample, the original and current values of the CachedRowSet, whichare maintained in main memory, are initialized. The cursor is thenpositioned at the first and second rows, in turn, and the updateStringand updateFloat methods are called to modify the current value of the first two rows in the row set, which contain an employee name andsalary.
Call the updateRow method to signal the completion of each rowupdate. 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 theunderlying values in the data source. Deleting and inserting rows isdone 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 propagateany updates, inserts, and deletes back to the underlying data source.The acceptChanges method invokes a writer component internally toactually update the data source. Typically, a writer compares theoriginal value of each updated row with the values stored in thedatabase to be sure that the underlying data has not been changed bysomeone else. If nothing has been changed, the row set’s updates arewritten to the database. The original value is set to the current value
before acceptChanges returns.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 264/339
7
7-14 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Modifying Data
Alternatively, an application can call the method restoreOriginal if it discards the updates that it has made on a CachedRowSet. CallingrestoreOriginal simply replaces the current value of the row setwith the original value—there is no interaction with the underlyingdata source.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 265/339
7
Row Set Implementation 7-15Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 theoriginal.
In contrast the CachedRowSet.createShared method creates a rowset that shares its state with the original row set; that is, both the newand the original row set share the same physical, in-memory copy of their original and current values. Updates made by calling anupdateXXX method on one shared row set are reflected in the other.The createShared method, in effect, allows an application to createmultiple cursors over a single set of rows.
CachedRowSets also provide methods for easy conversion to a Javatechnology collection. The crs.toCollection method allows ajava.util.Connection object to be created from a CachedRowSet.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 266/339
7
7-16 Database Application Programming With Java TechnologyCopyright2000Sun 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 facilitythat allows you to customize data retrieval and updating, for complexor specialized situations.The CachedRowSet class uses this facility.
Custom readers and writers are useful because they can enable aRowSet to read its data from a regular file data source or from someother non-SQL data source, such as a spreadsheet.
This approach separates where you get data from, and what you dowith it.
You can make a CachedRowSet style implementation that has beenconfigured with a custom reader/writer available as a normal
JavaBeans component. Therefore, developers writing applications cangenerally ignore the details of the customization process and focus onmore important aspects of using row sets.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 267/339
7
Row Set Implementation 7-17Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 theRowSetReader interface internally to handle the task of readingdata 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 typeRowSetInternal to the RowSetReader.The RowSetInternalinterface contains some additional methods that are needed by theRowSetReader to do its work.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 268/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 269/339
7
Row Set Implementation 7-19Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Reading and Writing Data
Overview
Figure 7-2 outlines how readers and writers interact with a data sourceand the CachedRowSet.
Figure 7-2 RowSetReader and RowSetWriter Interaction
CachedRowSet
RowSetReader RowSetWriter
Data source*
*A database, spreadsheet, or other source of data
data in data out
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 270/339
7
7-20 Database Application Programming With Java TechnologyCopyright2000Sun 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 namejdbc20stdext.pdf), included in the specifications directory in yourlab files for this course, for an example of a RowSetReader
implementation.
The example in the appendix uses JDBC to read data from a SQLdatabase. 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 set’s properties tocreate a Connection to a data source. A PreparedStatement iscreated using the command property and the PreparedStatement ispassed any properties that were set on the row set.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 271/339
7
Row Set Implementation 7-21Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Reading and Writing Data
RowSetReader
The example is designed to be used with the CachedRowSet row setimplementation. You use the CachedRowSet.populate method toread the rows from a ResultSet object into the row set. The exampleassumes the caller is of type CachedRowSet. A SQLException isthrown if anything goes wrong.
An alternative reader implementation could read data directly from aregular 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 theoriginal value of the row set when invoked by a reader. TheRowSetMeta interface can also be used by such a reader tocommunicate the format of the data being read to the row setimplementation.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 272/339
7
7-22 Database Application Programming With Java TechnologyCopyright2000Sun 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 namejdbc20stdext.pdf), included in the specifications directory in yourlab files for this course, for an example of a RowSetWriter
implementation.
This writer works in conjunction with the reader shown in theprevious section. The writer enforces an optimistic concurrency control
policy that requires a row in the database to be unchanged for it to beupdated. For simplicity, some details are not shown.
The writer calls the reader to create a Connection, and to find out if itneeds to reset itself. This might be necessary if new data has been readsince the command used to read the data might have changed. Thewriter iterates through each row of the row set and updates theunderlying database when necessary.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 273/339
7
Row Set Implementation 7-23Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Exercise: Row Set Implementations
Exercise objective – Practice the concepts and tasks you have learnedin this module.
Tasks
Go to the SL330 directory on your computer and change to the lab filesdirectory. Open the directory for this module, then the directory forthis exercise, and read the readme file. Follow the instructions in thatfile to complete this exercise.
If additional instructions or materials are required, your instructor willprovide them.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 274/339
7
7-24 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Exercise: Row Set Implementations
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,or discoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 275/339
7
Row Set Implementation 7-25Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Check Your Progress
Before continuing on to the next module, check that you are able toaccomplish or answer the following:
Explain how to use the CachedRowSet implementation
Modify a RowSetReader or RowSetWriter
Understand the benefit provided by using the CachedRowSetimplementation
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 276/339
7
7-26 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Think Beyond
What considerations should you take into account when designing thearchitecture of your Java application?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 277/339
8-1Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
JDBC and Application Architecture 8
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-tierapplication
Explain where JDBC components should be installed in a multi-tier application
Describe when to use a two-tier application architecture in adatabase 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 databaseapplication design and JDBC.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 278/339
8
8-2 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Relevance
Discussion – N -tier architectures allow better flexibility andmaintenance of a software subsystem. The most common is the three-tier architecture. How do the components of a three-tier systeminteract with each other?
What is the deciding factor for these divisions?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 279/339
8
JDBC and Application Architecture 8-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
References
Additional resources – The following reference can provide additionaldetails 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 ProgrammingTechniques. Wiley.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 280/339
8
8-4 Database Application Programming With Java TechnologyCopyright2000Sun 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 fora full application. A tier can be, but is not always, a standaloneprogram, and resides on a separate machine from other tiers or on thesame machine.
The advantage of dividing parts of a full application into separate tiersis so that you can change one aspect of the application, such as thepresentation, with minimal impact on other parts, such as how thedata is stored or the business rules.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 281/339
8
JDBC and Application Architecture 8-5Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Tiered Application Architecture Overview
In addition, as shown in Figure 8-1, you can use tiers as a way tocoordinate the efforts of multiple clients.
Figure 8-1 Coordinating Clients Using a Middle Tier
The JDBC API supports multi-tier architectures for database access.
Middletier
Client
Client
Client
DBMS
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 282/339
8
8-6 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Tiers and Components
Distributed applications are frequently characterized in terms of threelogical components, sometimes called layers. Each part of theapplication provides certain services and fulfills certain responsibilitieswithin the architecture.
The following components make up both the two-tier and three-tierdesigns, shown in the diagrams in the next section.
Presentation – This component receives the data and dataprocessing requests. It is the graphical user interface (GUI) orcharacter-based interface, and is typically in the first tier, the client.
Business logic – This component implements business rules, suchas 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 atwo-tier model, or in the second tier in a three-tier model.
Data – This component stores and allows access to the data, and istypically in the third tier, the server.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 283/339
8
JDBC and Application Architecture 8-7Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,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 applicationor applet functioning as the presentation communicates directly withthe database. A user’s actions are translated in JDBC-based SQLcommands and are delivered to the database. The results of thosestatements are sent back to the user.
You can store the database on another machine to which the user isconnected using a network. The network can be an intranet or theInternet. This architecture enables the data to reside locally orremotely.
If other users need a different presentation to the same data, you needto develop only a new interface on the front end.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 284/339
8
8-8 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Two-Tier Architecture
Figure 8-2 shows a two-tier application design.
Figure 8-2 Two-Tier Database Design
Note – In the examples shown in this course, tiers are often shown onseparate machines; however, you can store tiers on the same machine.
You can support caching results of database queries by introducing thecaching functionality into the front-end presentation on the clientmachine, or into the database on the server machine.
The first tier is responsible for making connections to any additionaldatabase servers.
DBMS
protocol
Applet or
JDBC driver
DBMS
Client machine
Databaseserver machine
Presentationcomponent
Business logiccomponent*
Datacomponent
*You can store business logic on either tier or both tiers
application
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 285/339
8
JDBC and Application Architecture 8-9Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Three-Tier Architecture
In a three-tier architecture, the first tier (client) sends commands to amiddle tier, which then sends SQL statements to the database on thethird tier (server). The database processes the SQL statements andsends the results back to the middle tier, which then sends them to theuser.
This middle tier enables you to develop the following functionalityseparately: secure socket classes, cache data, or business rules. Javaapplications 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/Internetprotocol
UDP – User datagram protocol
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 286/339
8
8-10 Database Application Programming With Java TechnologyCopyright2000Sun 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:
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 JDBCcode or driver, only the capability of using HTTP 1.0.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 287/339
8
JDBC and Application Architecture 8-11Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Three-Tier Architecture
A well-implemented three-tier architecture makes changing any aspectof the application easier, because the different components areseparated logically. For example, information systems departments,using a three-tier model, can maintain control over access and updatesto corporate data by controlling the middle tier. In many cases, thethree-tier architecture also can provide performance advantages.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 288/339
8
8-12 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Three-Tier Architecture
You can implement all data validation, including business rules, in themiddle tier. The middle tier also can take over responsibility formaking connections to additional database servers.
Figure 8-3 shows a three-tier application design.
Figure 8-3 Three-Tier Database Design
For greater security, do not include SQL and the business logic on theclient.
Application server
DBMSprotocol
(Java technology)
Java applet orHTML browser
RMI/CORBA,HTTP
JDBC driver
DBMS
Client machine
Server machine
Databaseserver machine
Presentationcomponent
Business logiccomponent
Datacomponent
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 289/339
8
JDBC and Application Architecture 8-13Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
N-Tier Architecture
N-tier architectures extend the two-tier and three-tier architectures byfurther breaking out functional modules into tiers.
You can create an n-tier architecture by partitioning the applicationvertically or horizontally.
Vertically – Adds tiers between client and server to furthersubdivide 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 thetiers is sufficiently well planned, you can add new functionalitywith a minimum amount of rework.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 290/339
8
8-14 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
N-Tier Architecture
For example, a three-tier application that needs to support agreatly increased number of end users could manage the increasedwork load by adding a local or regional “cache tier” to provide astore of objects, and reduce the number of transactions that usershad to perform directly on the database. This is shown inFigure 8-4.
Figure 8-4 Vertical N-Tier Architecture
Application server
Client
DBMS
Caching control
First tier
Third tier
Second tier
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 291/339
8
JDBC and Application Architecture 8-15Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
N-Tier Architecture
Horizontally – Creates additional parts of client functionality thatcan be managed by a server or servers, and breaks these out intoadditional tiers. An example, shown in Figure 8-5, is a client thatrequests a different service from a different server, such as a printserver.
Figure 8-5 Horizontal N-Tier Architecture
Application server
Client
DBMS
Print server
First tier
Third tier
Second tier
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 292/339
8
8-16 Database Application Programming With Java TechnologyCopyright2000Sun 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 onthe application and other considerations. Use this section to learn howto determine how to choose the architecture that works best for yourrequirements.
Two-Tier Architecture
Two-tier architecture is simple, straightforward, and typically suitablefor small applications. It is easier to implement if developmentresources are significantly limited.
A limitation of the two-tier model is that the GUI and application logicare tightly coupled, so the client program is responsible for all errorchecking and all data is exposed on the network, which is not secure.In addition, if database table schema changes on the server, you mustrestructure the client code.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 293/339
8
JDBC and Application Architecture 8-17Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Choosing an Architecture
Two-Tier Architecture
Installing drivers requires more work.
For two-tier solutions, this means that you must install drivers onevery client machine, which is a potentially time-consuming taskfor systems with many clients.
In a three-tier or n-tier application, you would need to install thedriver 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 losethe platform- and DBMS-independence of JDBC.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 294/339
8
8-18 Database Application Programming With Java TechnologyCopyright2000Sun 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 atwo-tier architecture addresses without the associated limitations.
The client might be much thinner than on the two-tier model andconsists essentially of the presentation, as well as control logic andcode that communicates with the middle tier. This might allow you touse less powerful client machines. It also makes it easier to support
client machines of multiple platforms, because there is less code oneach.
You can customize the middle tier to your application’s requirements.Enforcing the business rules in the middle tier, between the client anddatabase, enables you to create the rules once and keep them in asingle, easily maintained location.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 295/339
8
JDBC and Application Architecture 8-19Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 aretypically flexible enough to accommodate added middle-tier ordatabase systems to handle the increased load.
The disadvantage of using a three-tier or n-tier architecture is that itincreases the number of possible failure points. A two-tier architecturehas 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 issimplified.
Despite these disadvantages, the three-tier or n-tier model is thepreferred architecture for database applications. The added level of abstraction eases development and maintenance of the wholeapplication. Furthermore, it is easier to integrate several databases or
even legacy systems in an application.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 296/339
8
8-20 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Check Your Progress
Before continuing on to the next module, check that you are able toaccomplish or answer the following:
Define the components in a multi-tier application
Explain which components belong to each tier in a multi-tierapplication
Explain where JDBC components should be installed in a multi-tier application
Describe when to use a two-tier application architecture in adatabase application
Describe when to use a three-tier application architecture
Describe when to use an n-tier application architecture
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 297/339
8
JDBC and Application Architecture 8-21Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Think Beyond
Based on this course, can you begin implementing JDBC in yourwork? What other information would be useful to help you getstarted?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 298/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 299/339
A-1Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
DatabaseBasics A
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 commonlyused database management systems, and presents characteristics of relational database management systems. Use these concepts whenwriting SQL queries, and when designing databases for your Java
application.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 300/339
A
A-2 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
References
Additional resources – The following reference can provide additionaldetails on the topics discussed in this appendix:
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. SanFrancisco: 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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 301/339
A
Database Basics A-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Database Overview
A database is a shared collection of logically related data and adescription of the data that has been developed to meet theinformation requirements of an organization.
A database management system, or DBMS, is normally used tomaintain a database. A DBMS is a software system specially designedto 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, threeconditions must be met:
The data must have a format that the DBMS and computer systemunderstands.
The data should be stored, retrieved, and changed only by theDBMS.
The data should be under transaction control—that is, a formal setof rules should be enforced to ensure the integrity of the data.
For example, when money is transferred from one bank account toanother, it is common to subtract the transfer amount from oneaccount and add it to the other. If the operation is interrupted afterthe subtraction but before the addition, the money would not be ineither account. A DBMS can prevent this from happening byapplying rules to the operations.
Database management systems are categorized according to theapproach they use for storing and managing their data. Mostapplications developed today use one of three main kinds of databasemanagement systems:
Relational Database Management System (RDBMS)
Object-Oriented Database Management System (ODBMS)
Object/Relational Database Management System (ORDBMS)
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 302/339
A
A-4 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
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 itsphysical 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 tointeract with RDBMS data sources.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 303/339
A
Database Basics A-5Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Relational Database Structure
In relational databases, data is represented in tables. A table is madeup of columns and rows.
Each database column (also called a field) provides information abouta particular element to be stored in the database. This informationincludes its name, data type and any special characteristics itpossesses.
A database row (also called a record) contains the values for a specificset of data stored in the database.
Table A-1 shows an example table named Customers with six columnsand three rows.
Table A-1 Example Table
In most cases, a column is used in a table to hold values to uniquelyidentify records. In this case, the column is referred to as the primarykey for the table.
Additionally, a database record sometimes references one or morerecords in other tables. In this case, there must be a column thatcontains a value that can be used to reference the other record(s). Thistype of column is referred to as a foreign key, because it can be used toreference records in a different table of the database.
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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 304/339
A
A-6 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Data Independence
A relational database allows data to be managed independently fromthe way in which it is stored.
The physical model of data storage for a relational database can bedetermined by the RDBMS. From the user’s perspective, it is notimportant to know how data is stored for the system. The user workswith a logical model of the data (tables, rows, and columns) thatrepresents the user’s “window” on the stored data.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 305/339
A
Database Basics A-7Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Transactions
In database manipulation, a transaction is a logical group of workconsisting of one or more instructions. For example, the instructionsmight be to enter a customer record, create a new order record, add aline item to an order, and so on. For a transaction to executesuccessfully, all of its instructions must be successfully executed for thedatabase. If there is an error any time during transaction execution, theprevious operations must be reversed. This is referred to as backingout or performing a rollback on a transaction. Use transactions topartition work to minimize the chances of data corruption.
A transaction starts with a begin work command, and contains alldatabase data manipulation information; the transaction either iscompleted successfully with a commit work command or fails with arollback. The begin work command tells the database to start loggingall database data manipulation actions. The commit work commandtells the database that the transaction has completed successfully andto stop logging. The rollback command tells the database to stoplogging and to reverse any data manipulation that had occurred.
The business rules of your application have a major impact on howyou should partition tasks into transactions. If your applicationrequires that users enter a certain set of valid information before theyenter associated information, the first set should be a transaction.
Partitioning transactions is an art, not a science. There are advantagesand disadvantages to most of the ways you partition tasks intotransactions; it depends on the types of risks and advantages anddisadvantages 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. Howwould you partition the entry of the information to limit thecustomer’s chances of lost data entry from an error?
Ask the following questions in this situation, to determine how topartition 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?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 306/339
A
A-8 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Transactions
Discussion – One way to partition this example would be to have allwork done by the customer as one transaction. What problems mightthis cause?
Another way to partition this example is to have the customerinformation as one transaction, the order as another transaction, andthe payment as another. What problems might this cause?
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 307/339
A
Database Basics A-9Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Transactions
Figure A-1 shows a Customer table, followed by a begin workcommand and various inserts, updates, and deletes, followed by acommit work and the effect on the Customer table.
Figure A-1 Begin Work and Commit Work
BEGIN WORK
INSERT into CUSTOMER ("C8007", "Michael Wang","PO Box 42","Willmar", "MN", "56273"
COMMIT WORK
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"
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 Bran Andrews 678 Zinc Spur Netcong NJ 10022
C8014 Agata Omole 99 W Slade Kalispell MT 59901
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 80022C7842 Bran Andrews 678 Zinc Spur Netcong NJ 10022
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 308/339
A
A-10 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Transactions
Figure A-2 shows how, if one part of a transaction fails, the entiretransaction is reversed, or rolled back. The same beginning Customertable is used.
Figure A-2 Begin Work and Rollback
BEGIN WORK
INSERT into CUSTOMER ("C8007", "Michael Wang","PO Box 42","Willmar", "MN", "56273"
ROLLBACK
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"
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 80022C7842 Bran Andrews 678 Zinc Spur Netcong NJ 10022
DELETE FAILS
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 678 Zinc Spur Netcong NJ 10022
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 309/339
A
Database Basics A-11Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Locking
Locking the database is necessary to allow only one person access to aparticular column or row at a time. The idea of allowing multipleusers access to the same row in a database is called concurrency.Relational databases use two basic row locking strategies, pessimisticand optimistic, to deal with concurrency.
Pessimistic locking locks a row for the entire time the row is inmemory. This concurrency approach ensures that the row cannot beupdated by someone else at the same time you are updating. Inessence, there is no concurrency, because you are given exclusive
control of updating the row.
Pessimistic locking is best for batch processing, when multiple tablesare being updated and must be consistent. Batch processing iscommon in accounting applications.
Optimistic locking locks a row only for the time that it is beingaccessed in the database. When you read the row from the database, itis locked during the read but released as soon as it is in memory. Therow is then locked again when you perform your update or delete.
This approach allows multiple people to work with the same rowsimultaneously, but can cause people to overwrite each other’supdates. Consider the following example.
User A opens a customer information window and selects arecord, so the row from the database is read by the program. WhenUser A opens the record, the Preferred Customer checkbox to set itto yes.
User B then opens the same record.
Next, User A unmarks the checkbox so that it is set to no, and thedatabase row is updated.
At the same time User B is updating different fields and leaves thePreferred Customer checkbox as yes.
When User B saves the changes and updates the row, it overwritesthe update from User A and sets the Preferred Customer checkbox
back to yes.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 310/339
A
A-12 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Locking
To resolve this shortcoming in the optimistic locking strategy, youcould use a timestamp on each row, which is updated with eachupdate.
Read the timestamp on the row when it is opened.
Before updating the row, reread the row and compare thetimestamp to the one in memory for that row.
At that point, you can include programming that will warn the userthat 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 yourchanges?” Depending on the response, you would refresh the data orperform your update.
Optimistic locking is best for online processing, such as updating amaster record for a customer.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 311/339
A
Database Basics A-13Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
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 syntaxfor the retrieval and modification of data, as well as commands for theadministration of tables. Each SQL statement is issued to the databasesystem and parsed.
There are five main categories of SQL; most statements fall into thesecond category, Data Manipulation Language (DML):
Data Definition Language (DDL) – Used to create and alter thestructure of a database.
Data Manipulation Language (DML) – Used for operations, suchas 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 performcommit and rollback actions on a sequence of Data ManipulationLanguage commands.
Session control language – Used for operations on clients in aclient/server environment.
System control language – Used for operations on the server in aclient/server environment.
You can read the syntax of SQL clauses like English commands. Forexample, a SQL command could be to “get me all of the fields in thetable named Employee Data, where the employee ID is 10223.” If theEmployee Data table contained fields that held a name, employee ID,date of hire, social security number, and current salary, you wouldexpect to receive a single employee record with these values.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 312/339
A
A-14 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
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 itwere an integer or a real number, you would not need the singlequotes.
SQL statements are not case sensitive, but the examples shownhighlight the keywords with capital letters.
SELECTStatement
Overview
The SELECT statement is the primary command used for data retrieval
from a SQL database. It supports the following:
Joins
DISTINCT row selection
ORDER BY clauses
Regular expression matching
Column-to-column comparisons in WHERE clauses
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 313/339
A
Database Basics A-15Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
SQL Basics
SELECTStatement
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 bylast_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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 314/339
A
A-16 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
SQL Basics
SELECTStatement
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 nameconsists of a letter followed by “ughes,” such as “Hughes,” the querycould 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 havetwo tables defined—one containing staff details and another listing theprojects being worked on by each staff member—and each staff member has been assigned an employee number that is unique to thatperson, you can generate a sorted list of who was working on whatproject 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 containinginformation related to an employee ID in some manner. You canextract data from each of those tables, though slowly, by a singlequery.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 315/339
A
Database Basics A-17Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
SQL Basics
SELECTStatement
Joins
Note – You must qualify all column names with a table name. SQLdoes not support the concept of uniquely named columns spanningmultiple tables. You must qualify every column name as soon as youaccess more than one table in a single SELECT.
INSERTStatement
Note – Unlike ANSI SQL, you cannot nest a SELECT statement withinan INSERT statement. That is, you cannot insert the data returned by aSELECT 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 doesnot 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 ismatched with an INSERT value.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 316/339
A
A-18 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
SQL Basics
DELETEStatement
The DELETE statement removes records from a SQL table. The syntaxfor 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'
UPDATEStatement
The UPDATE statement is the SQL mechanism for changing the contentsof a SQL record. To change a particular record, you must identify whatrecord from the table you want to change. The UPDATE statementcannot use a column name as a value. You can use only literal valuesas 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'
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 317/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 318/339
B
B-2 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
References
Additional resources – The following resource can provide additionaldetail on the topics presented in this module:
SQLJ Group resources. [Online.] Available:http://www.sqlj.org
Database Programming in SQLJ: The ANSI Standard for EmbeddedSQL 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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 319/339
B
Using SQLJ B-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
SQLJ Overview
SQL is used for defining and manipulating data in a relationaldatabase; embedded SQL is SQL written directly in the source file of aprogram. Most applications written in C and C++ that interact with arelational database use embedded SQL.
Oracle Corporation, in conjunction with other leading databasevendors, wanted to be able to embed SQL in the Java programminglanguage. This group created SQLJ . SQLJ is a language for embeddingstatic SQL in the Java programming language. It is an alternativemethod, 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 staticor dynamic SQ:; you can use both in your programs. SQLJ uses JDBCcalls, so you can combine the two in the same program. You caninitialize a JDBC connection with a SQLJ connection context, or a SQLJconnection 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 aresmaller and it does compile-time type checking. You can verify queriesagainst the database before actually running the application.
SQLJ code can be smaller, more compact, and more self-explanatorythan JDBC code.
You also can create a JDBC ResultSet from a SQLJ iterator, coveredlater in this module in the ‘‘Executing the Query and Reviewing theResult Set Using Iterator Objects.” section. Therefore, the dynamic SQL
API for SQLJ is the JDBC API.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 320/339
B
B-4 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
SQLJ Architecture
Figure B-1 shows that the architecture of a database application usingSQLJ is similar to one that uses the JDBC API.
Figure B-1 SQLJ Architecture
The SQLJ Runtime is a thin layer of 100% Pure Java™ code that islocated above the JDBC driver and is used to communicate with yourprogram. 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.
SQLJ Runtime
JDBC-NetDriver
JDBC-ODBCBridge driver
ODBC andDB drivers
Driver A Driver B
Java application*
JDBC driver manager
. . .
JDBC API
* Contains SQLJ program files
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 321/339
B
Using SQLJ B-5Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
How SQLJ Works
SQLJ program files contain the static SQL calls to connect to therelational database, and are indicated with a .sqlj extension.
SQLJ uses a translator, a preprocessor, to replace the embedded staticSQL in the SQLJ program with calls to the JDBC API. The SQLJTranslator is run against the .sqlj file, using the compile commandsqlj filename, and produces one or more .java source files thatyou can compile with any standard Java programming languagecompiler.
Figure B-2 shows the series of compilation steps.
Figure B-2 Compiling a SQLJ Program
The SQLJ Translator performs two important functions. It replaces thestatic 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 anerror, if executed against the same database.
.sqlj file SQLJ Translator
.java file javac compiler .class file(s)
Step 1
Step 2
.java file(s)
sqlj filename.sqlj
javac filename.java
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 322/339
B
B-6 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
How SQLJ Works
Note – If a program is compiled pointing to database A, then run ondatabase B with tables that are not in sync with the tables in databaseA, there can be errors at runtime.
Code Example
To see how the .sqlj file looks before and after compiling, open thelab files directory for this course. Locate the directory for SQLJ, and
open the files named SqljDemo.sqlj and SqljDemo.java.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 323/339
B
Using SQLJ B-7Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Using SQLJ
The steps for using SQLJ to connect to and review data from adatabase 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 driverStep 2 – Establishing a connection tothe database
These two steps are completed usingthe SQLJ database connectionmanagement feature.
Step 3 – Creating a statement Use the SQLJ clauses and host
variables features to complete thisstep.
Step 4 – Executing the SQLStep 5 – Processing the results
You can use iterator objects tocomplete these two steps.
Step 6 – Shutting down objects Complete this step in the same wayyou would for a JDBC application.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 324/339
B
B-8 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Registering and Connecting to the Database Using DatabaseConnection Management
SQLJ defines a default database connection that is global to the SQLJprogram; you do not have to explicitly define the connection.
You also can use SQLJ programs to manipulate multiple databaseconnections. You can explicitly create a connection context at any pointthat a Java programming language class declaration is permitted. Aconnection context manages a set of SQL operations performed duringa session with a specific database. SQLJ comes with aDefaultContext 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.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 325/339
B
Using SQLJ B-9Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Registering and Connecting to the Database Using DatabaseConnection Management
Example
The following is a sample generic Connection class that returns aConnection or DefaultContext. The sample was created by OracleCorporation and is included as part of the SQLJ implementation.
1 /* Copyright (c) 1997 Oracle Corporation */
2 import java.sql.*;
3 import sqlj.runtime.ref.DefaultContext;
45 /**
6 This is a utility class for establishing SQLJ connections.
7 **/
8 public class ConnectionManager {
9
10 private static String uid = "system" ;
11 private static String pwd = "manager" ;
12 private static String dburl =
"jdbc:oracle:thin:@java1.com:1521:stock1";
13 private static String driver = "oracle.jdbc.driver.OracleDriver";
1415 /**
16 Creates and returns a new JDBC Connection object.
17 If an error occurs, an error message is printed to System.err
18 and the programs exits.
19 **/
20 static public Connection newConnection() {
21 Connection conn = null;
22
23 //Verify that the access parameters are defined.
24 if (uid== null || pwd==null || dburl==null ) {
25 System.err.println
("Please set DBURL, UID, and PWD, and try again." ) ;
26 System.exit(1) ;
27 }
28
29 try {
30 Class driverClass = Class.forName(driver);
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 326/339
B
B-10 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Registering and Connecting to the Database Using DatabaseConnection Management
31 DriverManager.registerDriver((Driver)driverClass.newInstance());
32 conn = DriverManager.getConnection (dburl, uid, pwd);
33 } catch (Exception e) {
34 System.err.println( "Could not establish the JDBC connection:") ;
35 System.err.println(e); System.exit(1);
36 }
37 return conn;
38 }
39
40 /**41 Returns the currently installed SQLJ default context.
42 If the current default context is null, a new default context
43 instance is set up using a connection obtained from
44 <code>getConnection()</code>.
45 **/
46 static public DefaultContext initContext()
47 {
48 DefaultContext ctx = DefaultContext.getDefaultContext();
49 if (ctx == null) {
50 try {
51 ctx = new DefaultContext(newConnection());52 } catch (SQLException e) {
53 System.out.println("Error: could not get a default context");
54 System.err.println(e) ; System.exit(1);
55 }
56 DefaultContext.setDefaultContext(ctx);
57 }
58 return ctx;
59 }
60 }
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 327/339
B
Using SQLJ B-11Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Registering and Connecting to the Database Using DatabaseConnection 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 DemoCtxcontext 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 }
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 328/339
B
B-12 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
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 isenclosed in curly braces. A SQLJ clause can be any place in theprogram that a Java programming language statement might appear.
Syntax
#sql {SQLString };
Example
The following SQLJ clause selects the first and last name from theCustomer table for a given customer ID:
1 String firstName;
2 String lastName;
3 int customerID;
4 #sql{SELECT fname, lname INTO :firstName, :lastName FROM Customer
WHERE custID = :customerID};
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 329/339
B
Using SQLJ B-13Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Creating a Statement Using SQLJ Clauses and Host Variables
Host Variables
Host variables are used to pass the input and output of SQLstatements. A host variable is a Java programming language variable,parameter, or field that is embedded in a SQL statement prefixed by acolon.
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
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 330/339
B
B-14 Database Application Programming With Java TechnologyCopyright2000Sun Microsystems, Inc.All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Executing the Query and Reviewing the Result Set UsingIterator Objects
In a SQLJ program, a result set returned by a SQL query is accessed bymeans of an iterator object, which iterates through the rows in the resultset. You can define an iterator class with the #sql token and thekeyword iterator. The clause that defines a named iterator lists thenames and types of columns in a row returned in the result set. Youcan 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 );
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 331/339
B
Using SQLJ B-15Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Executing the Query and Reviewing the Result Set UsingIterator Objects
Using an Iterator Class
Syntax
tableName iteratorRefVar ;
#sql iterator = {SQL_statement};
Example
1 SalesRecs sales;
2 #sql sales = { SELECT item_number,item_name,sales_date,cost,
3 sales_rep_number,sales_rep_name FROM sales };
4 while( sales.next() )
5 {
6 System.out.println( "ITEM ID: " + sales.item_number() );
7 System.out.println( "ITEM NAME: " + sales.item_name() );
8 System.out.println( "COST: " + sales.cost() );
9 System.out.println( "SALES DATE: " + sales.sales_date() );
10 System.out.println( "SALES REP ID: " + sales.sales_rep_number() );
11 System.out.println( "SALES REP NAME: " + sales.sales_rep_name() );
12 System.out.println();
13 }
14 sales.close() ;
15 }
16 }
Note – At this time, SQLJ supports only moving forward within aresult set, like the JDBC 1.0 ResultSet.
To see a complete .sqlj file and the resulting .java file usingiterators, open the lab files directory for this course. Locate thedirectory for SQLJ, and open the files named IterDemo1.sqlj andIterDemo1.java.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 332/339
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 333/339
Glossary-1Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Glossary
ANSI
American National Standards Institute.
Business rules
Rules governing what operations are permitted on applicationdata and what constraints apply to those operations. Theserules 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 theuser to interact with the system and the server provides theability to store and manipulate application data or resources.Client/server architectures tend to be very flexible, allowingone 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, andconsists of the element’s name, data type, and special attributes,such as being a non-null field.
Commit
The act of finalizing a transaction (set of operations) on adatabase.
Concurrency
In databases, the attempt by several users to access the samedatabase structure. In relational databases, this means accessingthe same table.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 334/339
Glossary-2 DatabaseApplication Programming With JavaTechnologyCopyright2000Sun 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, andmaintain databases and the data stored within. A DMBS alsoprovides controlled access to a database.
Dynamic SQL
An approach to generating SQL queries where the SQLcommand is first stored in a local variable, then is passed to thedatabase for execution. This provides the application with theflexibility to change the SQL instruction and execute thecommand on the fly. In the Java programming language, JDBCprovides support for dynamic SQL.
Embedded SQL
Hard-coded SQL instructions directly written into a program. Inthe Java programming language, SQLJ provides this capability.
Foreign key
In relational databases, a column that matches database rows inone table to zero or more rows within another table. This isused to represent a one-to-many relationship for tables indatabases.
ISO
International Standards Organization.
Java 2 SDK
The latest release of a set of program modules, applications, andclass 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 applicationswith a unified interface to multiple naming and directoryservices in an enterprise environment.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 335/339
Glossary Glossary-3Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Java Runtime Environment (JRE)
The set of program modules needed to run Java technology on acomputer. 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 SQLstatements on it. Although JDBC is not an acronym, it is oftenreferred to as “Java Database Connectivity.” JDBC has been apart 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 beyondthe physical storage within the relational database. SQL definestwo kinds of joins: outer joins and inner joins. For an inner join,records that do not match the join criteria are not included inthe result table. An outer join includes records that do notmatch join criteria, filling in subsequent fields in the table withnull 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 databaseresource. Relational databases typically support row-levellocking, 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 tablesand columns in the database.
n-Tier
An architecture for client/server systems. N-tier architecturesextend the concept of three-tier systems, allowing multiplefunctional “servers” to be defined for different functions withinthe application. See also two-tier and three-tier.
Object ID (OID)
A way to uniquely identify an object within a database that isnot tied to business meaning.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 336/339
Glossary-4 DatabaseApplication Programming With JavaTechnologyCopyright2000Sun 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 andmaintenance of a persistent and sharable collection of objects.
Object Relational Database Management System (ORDBMS)
A hybrid between an RDBMS and an OODBMS. An objectrelational database management system is a relational databasemanagement system that provides extended support for objectstorage and retrieval. The SQL3 standard defines the extensionsto SQL required to support this model.
Optimistic Locking
A locking strategy, where transactions are allowed to run untilcompletion. At commit time, a check is made to see if a conflict
occurred. In the case of conflict, the transaction that caused theconflict is rolled back and restarted.
Pessimistic Locking
A locking strategy where one or more rows in a database tableare locked (unavailable) for the duration of a specifictransaction. During this time, other transactions cannot performoperations 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 intables consisting of rows and columns. A column represents onedata type within the table. A row is a database record, a set of values for the given table. RDBMS systems allow data to befreely organized between the storage tables, providing a flexible
strategy for dynamically relating data elements based on theneeds of an application. Most RDBMS systems define someform of SQL to provide the capability for clients to performoperations on the relational database.
Rollback
In a transaction, the act of reversing the previous operations torestore a database to its previous state. This is also called
backing out of a transaction.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 337/339
Glossary Glossary-5Copyright2000Sun Microsystems, Inc.All Rights Reserved. EnterpriseServices,October 1999, Revision A.1
Row
A single set of associated values stored within a table of arelational 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 withdatabases 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 byISO and ANSI committees. The three standards are commonlyreferred to as SQL/89, SQL92 (also called SQL2) and SQL3.
SQLJ (Java)
A standard for embedding static SQL statements and constructsin 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 withinthe table. A row is a database record, a set of values for thegiven table.
Three-tier
An architecture for client/server systems, consisting of three
logical layers, or tiers. The first tier (sometimes called the frontend or presentation tier) is generally located on a user’smachine; it displays data and allows a user to interact with theapplication. The front end communicates with a middle tier(also known as the business logic tier), which coordinates clientrequests and commands and is often used to implement
business rules for the application. The middle tier passes clientrequests to the third tier. (also called the back end or data tier)The third tier provides data management and storage servicesto the client(s) through one or more middle tiers.
TierA part of an application architecture responsible for fulfillingsome function. A tier might not be an independent codemodule. More than one tier can reside on the same machine.Tiers are sometimes referred to as layers.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 338/339
Glossary-6 DatabaseApplication Programming With JavaTechnologyCopyright2000Sun 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 executedfor the database. If there is an error any time during transactionexecution, the previous operations must be reversed. This isreferred to as backing out or performing a rollback on atransaction.
Two-tier
An architecture for client/server systems. Normally, a clientinterface, located on a user’s computer system, interacts with adatabase management system on another machine. Thedatabase management system generally services requests from
many clients.
7/18/2019 Sun Press - Sl-330 - Database Application Programming With Java Technology
http://slidepdf.com/reader/full/sun-press-sl-330-database-application-programming-with-java-technology 339/339
Please
Recycle
Copyright 2000 Sun Microsystems Inc., 901 San Antonio Road, Palo Alto, California 94303, Etats-Unis. Tous droitsréservés.
Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, lacopie, la distribution, et la décompilation. Aucune partie de ce produit ou document ne peut être reproduite sous aucune
forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de licence, s’il y en a.
Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par uncopyright et licencié par des fournisseurs de Sun.
Des parties de ce produit pourront être dérivées du systèmes Berkeley 4.3 BSD licenciés par l’Université de Californie.UNIX est une marque déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivementpar 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 desmarques déposées de Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays.
Toutes les marques SPARC sont utilisées sous licence sont des marques de fabrique ou des marques déposées de SPARCInternational, Inc. aux Etats-Unis et dans d’autres pays.
Les produits portant les marques SPARC sont basés sur une architecture développée par Sun Microsystems, Inc.
L’interfaces d’utilisation graphique OPEN LOOK et Sun™ a été développée par Sun Microsystems, Inc. pour sesutilisateurs et licenciés. Sun reconnaît les efforts de pionniers de Xerox pour larecherche et le développement du conceptdes interfaces d’utilisation visuelleou graphique pour l’industrie de l’informatique. Sun détient une licence non exclusivede Xerox sur l’interface d’utilisation graphique Xerox, cette licence couvrant également les licenciés de Sun qui mettenten place l’interface d’utilisation graphique OPEN LOOK et qui en outre se conforment aux licences écrites de Sun.
L’accord du gouvernement américain est requis avant l’exportation du produit.
Le système X Window est un produit de X Consortium, Inc.
LA DOCUMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ETGARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LALOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITEMARCHANDE, A L’APTITUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.