40
Sun Microsystems, Inc. 4150 Network Circle Santa Clara, CA 95054 U.S.A. 650-960-1300 Send comments about this document to: [email protected] Using Java DataBase Connectivity Sun ONE Studio 5 Programming Series Part No. 817-2332-10 June 2003, Revision A

Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

  • Upload
    others

  • View
    21

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

Sun Microsystems, Inc.4150 Network CircleSanta Clara, CA 95054 U.S.A.650-960-1300

Send comments about this document to: [email protected]

Using Java™ DataBaseConnectivity

Sun™ ONE Studio 5 Programming Series

Part No. 817-2332-10June 2003, Revision A

Page 2: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

PleaseRecycle

Copyright © 2003 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.

Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. Inparticular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed athttp://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S. and in other countries.

This document and the product to which it pertains are distributed under licenses restricting their use, copying, distribution, anddecompilation. No part of the product or of this document may be reproduced in any form by any means without prior written authorization ofSun and its licensors, if any.

Third-party software, including font technology, is copyrighted and licensed from Sun suppliers.

Sun, Sun Microsystems, the Sun logo, Forte, Java, NetBeans, iPlanet, docs.sun.com, and Solaris are trademarks or registered trademarks of SunMicrosystems, Inc. in the U.S. and other countries.

All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the U.S. and othercountries. Products bearing SPARC trademarks are based upon architecture developed by Sun Microsystems, Inc.

UNIX is a registered trademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd.

Federal Acquisitions: Commercial Software - Government Users Subject to Standard License Terms and Conditions.

DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT,ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

Copyright © 2003 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, Etats-Unis. Tous droits réservés.

Sun Microsystems, Inc. a les droits de propriété intellectuels relatants à la technologie incorporée dans le produit qui est décrit dans cedocument. En particulier, et sans la limitation, ces droits de propriété intellectuels peuvent inclure un ou plus des brevets américains énumérésà http://www.sun.com/patents et un ou les brevets plus supplémentaires ou les applications de brevet en attente dans les Etats - Unis etdans les autres pays.

Ce produit est un document protege par un copyright et distribue avec des licenses qui est en restreignent l’utilisation, la copie, la distribution etla décompilation. Aucune partie de ce produit ou document ne peut être reproduite sous aucune forme, parquelque moyen que ce soit, sansl’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 un copyright et licencié par desfournisseurs de Sun.

Sun, Sun Microsystems, le logo Sun, Forte, Java, NetBeans, iPlanet, docs.sun.com, et Solaris sont des marques de fabrique ou des marquesdéposées de Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays.

Toutes les marques SPARC sont utilisées sous licence et sont des marques de fabrique ou des marques déposées de SPARC International, Inc.aux Etats-Unis et dans d’autres pays. Les produits protant les marques SPARC sont basés sur une architecture développée par SunMicrosystems, Inc.

UNIX est une marque enregistree aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company Ltd.

LA DOCUMENTATION EST FOURNIE “EN L’ÉTAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRESSESOU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENTTOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE, A L’APTITUDE A UNE UTILISATION PARTICULIERE OU AL’ABSENCE DE CONTREFAÇON.

Page 3: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

3

Contents

Before You Begin 9

1. Using Java DataBase Connectivity 15

Programming JDBC 15

General Programming Steps 15

JDBC Reference Materials 16

Using the Database Explorer 17

Using JDBC Components 18

The JDBC Tab 19

Programming With JDBC Components 24

Using the JDBC Form Wizard 28

Establishing a Connection 29

Selecting Columns to Display 33

Selecting a Secondary RowSet 35

Previewing and Generating an Application 36

Running Your JDBC Application 37

Index 39

Page 4: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

4 Using Java DataBase Connectivity • June 2003

Page 5: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

5

Figures

FIGURE 1 JDBC Form Wizard, Opening 29

FIGURE 2 JDBC Form Wizard, Database Connection 30

FIGURE 3 JDBC Form Wizard, Select a Table 32

FIGURE 4 JDBC Form Wizard, Select Columns 34

FIGURE 5 JDBC Form Wizard, Select Secondary RowSet 36

FIGURE 6 JDBC Form Wizard, Finish the Wizard 37

Page 6: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

6 Using Java DataBase Connectivity • June 2003

Page 7: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

7

Tables

TABLE 1 RowSet Properties 21

TABLE 2 RowSet Other Properties Tab Properties 21

TABLE 3 RowSet Event Tab Properties 22

TABLE 4 Code Generation Tab Properties 22

TABLE 5 Data Navigator Properties 23

TABLE 6 Stored Procedure Properties 24

TABLE 7 Transaction Isolation Levels 33

Page 8: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

8 Using Java DataBase Connectivity • June 2003

Page 9: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

9

Before You Begin

Welcome to the Using Java DataBase Connectivity book of the Sun ONE Studio 5Programming Series. This book focuses on programming with persistentdata—data stored in a database or other data store that is external to yourapplications. The book discusses the different persistence programming modelssupported by Sun ONE Studio 5. It focuses on the Transparent Persistencetechnology provided by the Sun ONE Studio 5 integrated development environment(IDE).

This book is written for programmers who want to learn how to use the persistenceprogramming models supported by Sun ONE Studio 5. The book assumes a generalknowledge of Java and database access technology. Before reading it, you should befamiliar with the following subjects:

■ Java programming language■ Relational database concepts (such as tables and keys)■ How to use the chosen database

You can create the examples in this book in the environments listed in the releasenotes on the following web site:

http://forte.sun.com/ffj/documentation/index.html

Screen shots vary slightly from one platform to another. You should have no troubletranslating the slight differences to your platform. Although almost all proceduresuse the Sun™ ONE Studio 5 user interface, occasionally you might be instructed toenter a command at the command line. Here too, there are slight differences fromone platform to another. For example, a Microsoft Windows command might looklike this:

c:\>cd MyWorkDir\MyPackage

Page 10: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

10 Using Java DataBase Connectivity • June 2003

A UNIX command might look like this:

Before You Read This BookThis book is written for programmers who want to learn how to use the persistenceprogramming models supported by Sun ONE Studio 5. The book assumes a generalknowledge of Java and database access technology. Before reading it, you should befamiliar with the following subjects:

■ Java programming language■ Relational database concepts (such as tables and keys)■ How to use the chosen database

Note – Sun is not responsible for the availability of third-party web sites mentionedin this document and does not endorse and is not responsible or liable for anycontent, advertising, products, or other materials on or available from such sites orresources. Sun will not be responsible or liable for any damage or loss caused oralleged to be caused by or in connection with use of or reliance on any such content,goods, or services available on or through any such sites or resources.

How This Book Is OrganizedThis book describes JDBC™ productivity enhancement tools provided by Sun ONEStudio 5. These automate many JDBC programming tasks in building clientcomponents or applications that interact with a database.

% cd MyWorkDir/MyPackage

Page 11: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

Before You Begin 11

Typographic Conventions

Related DocumentationSun ONE Studio 5 documentation includes books delivered in Acrobat Reader (PDF)format, release notes, online help, readme files for example applications, andJavadoc™ documentation.

Documentation Available OnlineThe documents described in this section are available from the docs.sun.comSM

web site and from the documentation page of the Sun ONE Studio DeveloperResources portal (http://forte.sun.com/ffj/documentation).

The docs.sun.com web site (http://docs.sun.com) enables you to read, print,and buy Sun Microsystems manuals through the Internet. If you cannot find amanual, see the documentation index installed with the product on your localsystem or network.

Typeface Meaning Examples

AaBbCc123 The names of commands, files,and directories; on-screencomputer output

Edit your.login file.Use ls -a to list all files.% You have mail.

AaBbCc123 What you type, when contrastedwith on-screen computer output

% su

Password:

AaBbCc123 Book titles, new words or terms,words to be emphasized

Read Chapter 6 in the User’s Guide.These are called class options.You must be superuser to do this.

AaBbCc123 Command-line variable; replacewith a real name or value

To delete a file, type rm filename.

Page 12: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

12 Using Java DataBase Connectivity • June 2003

■ Release notes (HTML format)

Available for each Sun ONE Studio 5 edition. Describe last-minute releasechanges and technical notes.

■ Sun ONE Studio 5, Standard Edition Release Notes - part no. 817-2337-10

■ Getting Started guides (PDF format)

Describe how to install the Sun ONE Studio 5 integrated developmentenvironment (IDE) on each supported platform and include other pertinentinformation, such as system requirements, upgrade instructions, applicationserver information, command-line switches, installed subdirectories, databaseintegration, and information on how to use the Update Center.

■ Sun ONE Studio 5, Standard Edition Getting Started Guide - part no. 817-2318-10

■ Sun ONE Studio 4, Mobile Edition Getting Started Guide - part no. 817-1145-10

■ Sun ONE Studio 5 Programming series (PDF format)

This series provides in-depth information on how to use various Sun ONE Studio5 features to develop well-formed J2EE applications.

■ Building Web Components - part no. 817-2334-10

Describes how to build a web application as a J2EE web module using JSPpages, servlets, tag libraries, and supporting classes and files.

■ Building J2EE Applications - part no. 817-2327-10

Describes how to assemble EJB modules and web modules into a J2EEapplication, and how to deploy and run a J2EE application.

■ Building Enterprise JavaBeans Components - part no. 817-2330-10

Describes how to build EJB components (session beans, message-driven beans,and entity beans with container-managed or bean-managed persistence) usingthe Sun ONE Studio 5 EJB Builder wizard and other components of the IDE.

■ Building Web Services - part no. 817-2334-10

Describes how to use the Sun ONE Studio 5 IDE to build web services, to makeweb services available to others through a UDDI registry, and to generate webservice clients from a local web service or a UDDI registry.

■ Using Java DataBase Connectivity - part no. 817-2332-10

Describes how to use the JDBC productivity enhancement tools of the SunONE Studio 5 IDE, including how to use them to create a JDBC application.

■ Sun ONE Studio 5 tutorials (PDF format)

These tutorials demonstrate how to use the major features of each Sun ONEStudio 4 edition.

■ Sun ONE Studio 5 Web Application Tutorial - part no. 817-2320-10

Provides step-by-step instructions for building a simple J2EE web application.

Page 13: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

Before You Begin 13

■ Sun ONE Studio 5 J2EE Application Tutorial - part no. 817-2322-10

Provides step-by-step instructions for building an application using EJBcomponents and Web Services technology.

■ Sun ONE Studio 4, Mobile Edition Tutorial - part no. 816-7873-10

Provides step-by-step instructions for building a simple application for awireless device, such as a cellular phone or personal digital assistant (PDA).The application will be compliant with the Java 2 Platform, Micro Edition(J2ME™ platform) and conform to the Mobile Information Device Profile(MIDP) and Connected, Limited Device Configuration (CLDC).

You can also find the completed tutorial applications at:http://forte.sun.com/ffj/documentation/tutorialsandexamples.html

Online HelpOnline help is available in the Sun ONE Studio 5 IDE. You can open help by pressingthe help key (F1 in Microsoft Windows and Linux environments, Help key in theSolaris environment), or by choosing Help → Contents. Either action displays a listof help topics and a search facility.

ExamplesYou can download examples that illustrate a particular Sun ONE Studio 5 feature, aswell as completed tutorial applications, from the Sun ONE Studio DeveloperResources portal at:

http://forte.sun.com/ffj/documentation/tutorialsandexamples.html

The site includes the applications that are used in this document.

Javadoc DocumentationJavadoc documentation is available within the IDE for many Sun ONE Studio 5modules. Refer to the release notes for instructions on installing this documentation.When you start the IDE, you can access this Javadoc documentation within theJavadoc pane of the Explorer.

Page 14: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

14 Using Java DataBase Connectivity • June 2003

Sun Welcomes Your CommentsSun is interested in improving its documentation and welcomes your comments andsuggestions. Email your comments to Sun at this address:

[email protected]

Please include the part number (817-2332-10) of your document in the subject line ofyour email.

Page 15: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

15

Using Java DataBase Connectivity

Sun ONE Studio 5 provides a JDBC (Java Database Connectivity) module thatautomates many programming tasks that you use when building client componentsor applications that interact with a database.

The goal of the Sun ONE Studio 5 JDBC module is to increase your productivitywhen programming visual forms that contain Swing (Java Foundation Class)components that use JDBC to retrieve and update database tables. You can use thismodule to assist you in generating simple, two-tiered application architectures.

This chapter describes the following JDBC productivity enhancement tools providedby Sun ONE Studio 5, and begins with a brief description of the steps you follow increating a JDBC application. The tools include:

■ Database Explorer■ JDBC JavaBeans components■ JDBC Form Wizard

Programming JDBCThis section provides a brief introduction to JDBC programming tasks.

General Programming StepsWhen you perform JDBC programming, you follow these general programmingsteps:

1. Import relevant classes within your code.

2. Load a JDBC driver.

Page 16: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

16 Using Java DataBase Connectivity • June 2003

3. Establish a connection with a database.

4. Create a Main method.

5. Create try and catch blocks and retrieve exceptions and warnings.

6. Set up and use database tables.

a. Create a table.

b. Create JDBC statements.

c. Execute Statements to perform persistence operations.

i. Enter data into a table.

ii. Obtain data from a table.

iii. Create an updatable result set (RowSet).

iv. Insert and delete rows programmatically.

d. View changes in a ResultSet by managing the Transaction Isolation Level.

Sun ONE Studio 5 simplifies most of these tasks, generating JDBC code eitherthrough your editing of the Sun ONE Studio 5 JDBC JavaBeans componentproperties or through your use of the JDBC Form Wizard.

JDBC Reference MaterialsWhile this chapter provides a discussion of JDBC programming in the context of theSun ONE Studio 5 IDE, it assumes familiarity with the basics of the JDBCprogramming model. For additional information about JDBC, you can review thefollowing reference materials, grouped by function.

Learning JDBC Programming

The Java Developer Connection provides an excellent tutorial on JDBC:

http://developer.java.sun.com/developer/onlineTraining/new2java/programming/learn/jdbc.html

In addition, the Java Developer Connection supplies a JDBC Short Course:

http://developer.java.sun.com/developer/onlineTraining/Database/JDBCShortCourse/index.html

Page 17: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

17

Technical Articles

Sun has produced a document entitled:

“Duke’s Bakery – A JDBC Order Entry Prototype – Part I”:

http://developer.java.sun.com/developer/technicalArticles/Database/dukesbakery/

Getting Started With JDBC

The following index is a reference when starting to program using JDBC:

http://developer.java.sun.com/developer/technicalArticles/Interviews/StartJDBC/index.html

Another document is “Of Java, Databases, and Really Cool Dead Guys”:

http://developer.java.sun.com/developer/technicalArticles/Interviews/Databases/index.html

JDBC Basics

You can find additional information on JDBC within the Sun tutorial:

http://java.sun.com/docs/books/tutorial/index.html

This tutorial also provides some references:

http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html

Using the Database ExplorerBefore you begin the process of writing JDBC code, you need to understand thedatabase that your application will use. To obtain database information, you can usethe Sun ONE Studio 5 Database Explorer.

Using the Sun ONE Studio 5 Database Explorer, you can perform the followingtasks:

■ Browse database structures

■ Examine all tables present in the database, including column and indexinformation

Page 18: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

18 Using Java DataBase Connectivity • June 2003

■ Examine SQL views related to the database

■ Examine all stored procedures defined in the database

■ View database data

■ Create tables

■ Create views

■ Take “snapshots” of database structures

■ Monitor SQL commands sent to the database

■ Connect to a database

To learn how to perform these tasks, refer to the Database Explorer Help within theSun ONE Studio 5 IDE.

Using JDBC ComponentsSun ONE Studio 5 provides database connectivity and JDBC code generation toolsfor visual forms and components, specifically providing two basic types ofcomponents that you can use with your JDBC application:

■ Visual Components—Swing components let you display tabular databaseinformation. Within Sun ONE Studio 5, use Swing visual components to createforms that relay database data to the user; swing components provide the meansto let you manipulate row data and display columns. Sun ONE Studio 5 generatesthe appropriate Swing code for you. Another type of visual component is a DataNavigator–a JDBC component that you add to a form to manipulate the displayof data to the user.

■ Non-visual components—JavaBeans components that do not have visualrepresentation, but can be used to manipulate data from a database. One type ofnon-visual component is a RowSet, which is a type of row group that containsinformation from the database. To understand how to use JDBC JavaBeancomponents, you need to:

■ Understand the JDBC tab

■ Understand how to program applications with JDBC components by:

■ Creating a Visual Form with Sun ONE Studio 5

■ Using the Sun ONE Studio 5 Component Inspector with JDBC JavaBeanscomponents

Page 19: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

19

The JDBC TabThe JDBC tab in the component palette contains icons for a number of JDBCJavaBeans components that you can use to facilitate the interaction of Java Swingcomponents with a database. These components have properties that you customizeusing the Sun ONE Studio 5 Component Inspector.

The components include:

■ Connection Source■ Pooled Connection Source■ NB Cached RowSet■ NB JDBC RowSet■ NB Web RowSet■ Stored Procedure■ Data Navigator

Connection Source

A Connection source is a non-visual component that provides a connection to aJDBC compliant database. When you configure the Connection Source, you set:

■ database URL■ JDBC driver name■ user name■ password

Pooled Connection Source

A Pooled Connection Source component is similar to a Connection Source.However, when you specify the use of a Pooled Connection Source with yourapplication, database connections that are established during application runtimeare not closed when the application ceases to use the connection.

Instead, Sun ONE Studio 5 retains the connection in a pool for subsequent usewithin the runtime application. You can use a Pooled Connection Source whenyour application performs frequent open and close requests against a database towhich it is connected.

Understanding RowSets

A RowSet component represents rows fetched from the database. You can use thesecomponents to configure data models for several Swing components.

Page 20: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

20 Using Java DataBase Connectivity • June 2003

RowSet Background

A RowSet object contains a set of rows from a JDBC result set or another source oftabular data, such as a file or spreadsheet.

Depending on how you implement them in your code, RowSets can be serializableor extensible to non-tabular sources of data.

Because a RowSet object follows the JavaBeans model for properties and eventnotification, it is a JavaBeans component that can be combined with othercomponents in an application.

RowSets can be either connected or disconnected, depending on theirimplementation. A disconnected RowSet obtains a connection to a data source to fillitself with data or to propagate changes in data back to the data source, but most ofthe time it does not have a connection open.

Even when it is disconnected, a RowSet does not require the use of a JDBC driver orthe full JDBC API, so its size is small. A disconnected RowSet is an ideal format forsending data over a network to a thin client.

Types of RowSets:

The JDBC Tab makes three different types of row sets available:

■ NB Cached RowSet

The NBCachedRowSet is a disconnected RowSet that caches its data in memory.This special type of RowSet is suitable for smaller sets of data. You can use it tocreate JDBC applications that provide code to operate on thin Java clients, such asPersonal Digital Assistants (or PDAs).

When a RowSet is disconnected from its data source, any updates thatapplication writes on the RowSet are propagated to the underlying database.

■ NB JDBC RowSet

The NBJDBCRowSet represents a JavaBeans™ wrapping of a connected ResultSetobject to be used in models of Swing components. It can be used to readextremely long tables more efficiently than a cached RowSet, which stores all datain an internal cache.

■ NB Web RowSet

The NBWebRowSet represents a set of fetched rows in a cache to be used inmodels of Swing components. It provides all cached RowSet functionality, andenables the rows to be imported and exported in XML format. The file can then besent over the internet using HTTP/XML protocols.

Page 21: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

21

You can customize a JDBC RowSet by setting the following properties under theproperties tab in the Properties Editor:

Other Properties, Event, and Code Generation Tabs for aRowSet

The Other Properties Tab for a RowSet enables you to inspect and modify additionalproperties.

TABLE 1 RowSet Properties

Property Definition

Command SQL query to populate this RowSet. The query can be anysyntactically-correct SQL Select Query.

Connection provider The configured connection source; a drop-down list provideschoices.

Read-only If True, this RowSet is read-only. Data from the RowSet cannotbe written out to the database.

Rowcount The number of rows.

Status Status of a read against a RowSet

Transaction isolation determines how the RowSet handles data under transactions.For detail, see Java documentation for java.sql.Connection.

XML output directory(WebRowSet only)

Identifies the directory where data from the WebRowSet will besent.

XML Output File(WebRowSet only)

Determines the name of the file that will contain the XML outputfrom a WebRowSet.

TABLE 2 RowSet Other Properties Tab Properties

Property Definition

Database URL The location of the database where records will be updated. In mostcases, it is the same URL as listed in the Database URL property ofConnection Source.

Default ColumnValues

The values to be inserted into a new row. You can press FetchColumns to retrieve a list of columns in the RowSet.

Execute on load If true, the NB RowSet can be executed on load. You can specify aparameter with the Execute on Load from a Form Connection, andyou can generate initialization code.

Page 22: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

22 Using Java DataBase Connectivity • June 2003

The Event Tab for a RowSet enables you to inspect and modify events associatedwith RowSets.

The Code Generation Tab enables you to specify pre- and post-processing coderelated to a rowset.

Password A password the user must supply to gain access to the table thatcontains this NB RowSet.

Table Name The name of a database table where records will be updated.

User Name The name of a user updating records.

TABLE 3 RowSet Event Tab Properties

Property Definition

cursorMoved Specifies event handlers for the cursorMoved event. This method iscalled when an NBCachedRowSet’s cursor is moved.

rowChanged Specifies event handlers for the rowChanged event. This method iscalled when a row in a RowSet is changed.

rowInserted Specifies event handlers for the rowInserted event. This method iscalled when a row in a RowSet is inserted.

rowSetChanged Specifies event handlers for the rowSetChanged event. Thismethod is called when an RowSet is changed.

rowCompleted Specifies event handlers for the rowCompleted event. This methodis called after an inserted row is committed to the database.

TABLE 4 Code Generation Tab Properties

Property Definition

Code Generation Choose between generating standard or serialization code for thecomponent.

Custom CreationCode

Enter your own creation code for the component, not including thevariable name and equal sign (=). This creation code is called in theinitComponents() method. If this property is left blank, the IDEgenerates a default creation code for the component.

Post-Creation Code,Post-Init Code, Pre-Creation Code, andPre-Init Code

Write custom code that you want the IDE to place before and after acomponent’s creation code and before and after its initializationcode. The IDE always places creation code before initialization codein initComponents().

TABLE 2 RowSet Other Properties Tab Properties (Continued)

Property Definition

Page 23: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

23

Data Navigator

The JDBC module provides a visual component that provides direct navigation of aRowSet with a pre-built GUI. This component is useful when you need to createprototypical applications and when you want to create data entry applications.

You can customize a Data Navigator by setting the following properties under theproperties tab in the Properties Editor of a Data Navigator.

Stored Procedures

Stored procedures are a group of SQL statements that form a logical unit andperform a specific task. Stored procedures encapsulate operations or queries thatexecute on a database server. Such procedures, of course, vary in their natureaccording to the database management system (DBMS) on whose server theyexecute.

Serialize To Set the name of the file for the component to be serialized to, if it isserialized.

Use DefaultModifiers

Set to True if you want the component’s variable modifiers (public,private, and so on) to be generated using the default modifiers. Thedefault modifiers are specified in the Variables Modifier property ofthe Form Objects node in the Options window. (Choose Tools →Options to view the window.) Set to False if you want the VariablesModifier property to appear on the component’s property sheet,enabling you to override the default modifiers.

Variable Name Modify the component’s variable name.

TABLE 5 Data Navigator Properties

Property Definition

AutoAccept Automatically accept changes in the database. When you specifythis property, changes you make through the Navigator are eitherimmediately propagated to the database, or added to the RowSetand propagated to the database when you request it.

Bound RowSet The RowSet to be controlled by the Data Navigator.

Layout of buttons Determines whether buttons are displayed in one or two rows.

Modification buttons Enables or disables the display of buttons for modification.

TABLE 4 Code Generation Tab Properties (Continued)

Property Definition

Page 24: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

24 Using Java DataBase Connectivity • June 2003

Within the Sun ONE Studio 5 IDE, a stored procedure is a non-visual componentthat represents a database stored procedure in your JDBC application. You can call astored procedure in response to an event initiated by a user within an applicationGUI (such as a button click).

The syntax for a stored procedure is different for each database management systemthat Sun ONE Studio 5 supports. For example, one database management systemmight use begin, end, or additional keywords to indicate the beginning and endingof the procedure definition, while a second DBMS might use other keywords toindicate the same parts of the procedure definition.

The JDBC Tutorial provides information on some of the stored procedures you cancreate for different databases, in addition to information on calling a storedprocedure from your JDBC application.

You can customize a stored procedure by setting the following properties under theproperties tab in the Properties Editor of a stored procedure. Once you havespecified these properties in the property sheet, you can connect stored proceduresto any user action.

Programming With JDBC ComponentsUse the visual and non-visual components provided in the JDBC module inconjunction with Swing components to create forms that you use to retrieve andmanipulate database data.

For example, a number of Swing components (JList, JTable, JComboBox,JButton, JToggleButton, JRadioButton, and JCheckbox) are associated withdata models for the data they display. Within the IDE, you use Property Editors andthe Component Inspector to customize the data model for these Swing components

TABLE 6 Stored Procedure Properties

Property Definition

Arguments Represents database data that you want used by the storedprocedure when called from the application.

Bound RowSet Enables you to select a RowSet from a drop-down list that isrefreshed from the database after the stored procedure is called.

Call format Format in which your stored procedure is called. For example, itmight include Name and Arguments that are substitution codes forthe properties with those names on this property sheet.

Connection provider A configured connection source in whose context the storedprocedure is to be called from the application.

Name The name of your called stored procedure.

Page 25: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

25

by specifying the JDBC components with which they interact to access a database.After you have completed specifying the JDBC components, Sun ONE Studio 5generates the corresponding JDBC code.

Setting Data Models for Components

The following Swing components have associated data models.:

■ JList■ JTable■ JComboBox■ JButton■ JToggleButton■ JRadioButton■ JCheckbox

You can configure these data models to use data from the database.

The most common component to display database tables is JTable. The model canbe configured in the property sheet of each Swing component (under the modelproperty).

Selecting Database Columns

Components that can display multiple rows, such as JTable or JList, also havethe selectionModel property.

JList and JComboBox also have a special kind of model. This model consists ofusing one column from one RowSet to work with another column from anotherRowSet to display data, using a SQL join. See below for details.

Text components which have the document property (such as JTextField,JTextArea, JPasswordField, JTextPane, and JEditorPane) can set up thisproperty to use data from the database.

▼ To Configure the Data Model for JTable

1. For the model property in the JTable’s property sheet, open the custom propertyeditor by clicking on the value of the property and then clicking the ellipsis (…)button that appears.

2. Choose the TableEditor mode.

3. In the RowSet field, choose the RowSet to be displayed in the table.

4. Use Fetch columns to load column names into the list.

Page 26: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

26 Using Java DataBase Connectivity • June 2003

5. Use the Add, Remove, Edit, Move Up, and Move Down buttons to set the namesand order of the columns in the table.

6. Click OK to preserve the changes and close the custom property editor.

▼ To Configure the Selection Model for JTable and JList

1. For the selectionModel property in the component’s property sheet, open thecustom property editor by clicking on the value of the property and then clickingthe ellipsis button (…) that appears.

2. In the RowSet field, choose the RowSet to be displayed in the table or list.

3. Click OK to preserve the changes and close the custom property editor.

▼ To Configure the Data Model for JList and JComboBox

1. For the model property in the component’s property sheet, open the customproperty editor (by clicking on the value of the property and then clicking theellipsis button (…) that appears).

2. For the Primary RowSet fields, choose the RowSet for the data model to retrieverows from, and then select one column from the Column drop-down list.

3. If you want, in the Secondary RowSet field, choose the RowSet to display datafrom (according to a SQL join). Corresponding columns from the primary andsecondary RowSet must have the same data type.

4. If the Join check box is checked, a corresponding component displays the result ofa database join. If it is unchecked, a corresponding component is used as a codemap to set values in the primary rowset.

5. Choose a Data column (join column) and Display column (visible data). Click OKto preserve the changes and close the custom property editor.

▼ To Configure the Data Model for JCheckbox,JRadioButton, and JToggleButton

1. For the model property in the component’s property sheet, open the customproperty editor (by clicking on the value of the property and then clicking theellipsis (…) button that appears).

2. Choose the RowSet from which the data is to be fetched.

3. Choose a column; data from this column will be used to decide if the componentshould be selected.

4. Enter the database value corresponding to a selected component into the Selectfield and the value of an unselected component into the Unselect field.

Page 27: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

27

5. Click OK to preserve the changes and close the custom property editor.

▼ To Configure the Document Model for Text Components

1. For the document property in the component’s property sheet, open the customproperty editor by clicking on the value of the property and then clicking theellipsis button (…) that appears.

2. Choose the RowSet from which the data is to be fetched.

3. Choose a column in which to display the text component.

4. Click OK to preserve the changes and close the custom property editor.

Creating a Visual Form

After you have used the Property Editor to customize Swing components in yourapplication, Sun ONE Studio 5 enables you to create a visual form associated withthe Swing components that interacts with the database.

▼ To Create a Visual Form With Swing Components ThatInteract With a Database

1. Create a Swing component form using a template provided in the Sun ONEStudio 5 IDE.

2. Add any needed Connection Source (or Pooled Connection Source),RowSet, or Stored Procedure nonvisual components to your form from theComponent Palettes.

3. Using the corresponding Property Editor, customize these components for thedatabase entities they represent.

4. Add any visual components you need, including the Data Navigator.

5. Use the corresponding Property Editor to customize the visual componentsappropriately, referencing the RowSet components you need.

As you specify the Swing components to use with your JDBC application, Sun ONEStudio 5 automatically creates the correct Swing classes to use in your application.

6. Use the Properties Editor for the specified form to indicate exceptions that shouldbe caught during runtime and run the form.

Page 28: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

28 Using Java DataBase Connectivity • June 2003

Using the Component Inspector With JDBC Components

You can use the Sun ONE Studio 5 Component Inspector to modify properties forcomponents you use in your JDBC application. The following components can befound under Non-visual Components in the Component Inspector:

■ NB Cached RowSet■ NB JDBC RowSet■ NB Web RowSet■ Connection Source■ Pooled Connection Source■ Stored Procedure

The Data Navigator component and other Swing components are shownaccording to their position in the container hierarchy.

Using the JDBC Form WizardThe JDBC Form Wizard guides you through the creation of a form that can interactwith database tables. It provides a substitute for the explicit editing of propertiesthat you would otherwise perform if you used the approach outlined in “UsingJDBC Components” on page 18. When you finish running the wizard, you will havea generated application, a file name for the application, and a package.

The following sections illustrate the JDBC Form Wizard, using the sample PointBaseServer Database that comes included with the Sun ONE Studio 5 IDE.

▼ To Open the JDBC Wizard● Select Tools → JDBC Form Wizard

Page 29: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

29

FIGURE 1 JDBC Form Wizard, Opening

Establishing a ConnectionWhen you use the JDBC Form Wizard or when you use the JDBC tab to create aJDBC client application, one of the first tasks you must perform is to establish aconnection with the database management system that you want to use.

Typically, the JDBC Form Wizard or Sun ONE Studio 5 connection generates thecode that you can use in your JDBC application when you use the Visual FormEditor or the JDBC Form Wizard to create a form. The application uses the form topopulate information that it obtains from a database management system.

Page 30: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

30 Using Java DataBase Connectivity • June 2003

FIGURE 2 JDBC Form Wizard, Database Connection

The second panel of the JDBC Form Wizard lets you establish a connection with adatabase. You can specify the use of a pooled connection for a DataSource in thispanel.

When you need a new connection, you must supply:

■ The name of your database. For example, PointBase Network Server.

■ The JDBC driver name for the database. For example,com.pointbase.jdbc.jdbcUniversalDriver.

■ The Database URL where the database is located. For example,jdbc.pointbase://localhost:9092/sample.

■ User Name

■ Password

■ Select the Use Pooled Connection Source check box to specify an optional pooledconnection.

■ Optionally select the Advanced tab to specify a schema to get tables.

Sun ONE Studio 5 provides these parameters to the JDBC application code that itgenerates.

Page 31: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

31

You can select an existing connection by clicking the Use Existing Connection radiobutton, and selecting the connection from the drop-down list.

When you select the Next button, Sun ONE Studio 5 calls a method that creates adatabase connection based on parameters you enter. You use this connection to thedatabase in the same way that you use the wizard to write JDBC application code.

Selecting Database Tables or Views

The third panel of the JDBC Form Wizard lets you:

■ Select a table or view in the database to which you are connected.

■ Specify that you want only read access to a specific table for your generated JDBCapplication. This means that the application cannot alter data in the database.

■ Add a rowInserted event handler to a table. This event handler handles thelistening for events associated with the application’s insertion of rows into thetables you select.

■ Set the Transaction Isolation level for a table. See “Transaction Isolation Levels”on page 32.

■ Provide a SQL command to run against the tables you specify.

The JDBC Form Wizard lets you execute SQL statements against tables you specifyin the Wizard. You use the data from the SQL output to populate visual forms. Youcan specify SQL statements which, when applied to a specific form, generate theappropriate SQL code. In FIGURE 3, Sun ONE Studio 5 provides a default SQLcommand to use with the table you have selected.

Page 32: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

32 Using Java DataBase Connectivity • June 2003

FIGURE 3 JDBC Form Wizard, Select a Table

Transaction Isolation Levels

To avoid conflicts during a transaction, a database management system uses locks.Locks are operative until the application commits the transaction or rolls it backfrom the database.

Locks are set according to a transaction isolation level. Locks apply to the entireResultSet that is returned to the application or committed from the application tothe database.

Each database management system provides its own default transaction isolationlevel. Sun ONE Studio 5 lets you choose between the transaction isolation levelswithin the second panel of the JDBC Form Wizard.

Page 33: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

33

Note – The driver and the data base management system must support thetransaction isolation level you use.

Selecting Columns to DisplayThe fourth panel of the JDBC Form Wizard lets you select columns from thedatabase tables to include in the form that is displayed. In this panel, you canspecify:

■ Columns you want displayed in the application you generate■ The order of the columns you want displayed■ Column parameters:

■ Column title■ Column editability■ Default column value■ A Swing component to display the table in the application

TABLE 7 Transaction Isolation Levels

Property Definition

TRANSACTION_READ_COMMITTED Prohibits a transaction from reading a row that hasuncommitted changes in it.

SERIALIZABLE Includes the prohibitions inTRANSACTION_REPEATABLE_READ. It prohibits thesituation where one transaction reads all rows thatsatisfy a WHERE condition, a second transactioninserts a row that satisfies that WHERE condition, andthe first transaction rereads for the same condition,retrieving the additional “phantom” row in thesecond read.

TRANSACTION_NONE Transactions are not supported.

TRANSACTION_REPEATABLE_READ Prohibits a transaction from reading a row withuncommitted changes in it. It also prohibits thesituation where one transaction reads a row, asecond transaction alters the row, and the firsttransaction rereads the row, getting different valuesthe second time (that is, a non-repeatable read).

TRANSACTION_READ_UNCOMMITTED A row changed by one transaction can be read byanother transaction before changes in that row arecommitted to the database. If changes aresubsequently rolled back, the second transactionretrieves an invalid row.

Page 34: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

34 Using Java DataBase Connectivity • June 2003

In the example provided, JTable (the most common Swing form) is used. TheJTable form displays more than one column of data in the application.

Other Swing component choices include:

■ Jlist: displays a column in a list■ JComboBox: displays one column in a combo box■ JTextField: displays one or more columns in a text field

In FIGURE 4, the first Column is selected. It can be removed or moved in position.

FIGURE 4 JDBC Form Wizard, Select Columns

If you choose JList or JComboBox, only one column can be displayed, and you canchoose a column to display from the Name property:

1. Select a value in the Name column.

2. Select a column name from the built-in combo box.

▼ To Edit Column Titles

1. Click on the Title field you want to edit. An edit window appears with two tabs.

2. Select the String Value tab to enter the new name as a simple string value.

Page 35: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

35

3. Select Resource Bundle to enter the name using a resource bundle. Enter the nameof the bundle into Bundle Field, and select any related keys from the Keys combobox.

4. Select OK to close the edit window.

Selecting a Secondary RowSet

This panel displays a list of all available tables according to the database connectioncreated on the Connection panel and is enabled only if a view supporting twoRowSets (JList of JCheckbox) is selected.

You can use this panel to populate the secondary RowSet of the generatedapplication.

▼ To Select a Secondary RowSet

1. Check Use Secondary Rowset.

If you check this rowset, the secondary rowset is used in the generated application.

2. Select either the Tables or Views radio button.

3. Select a type of rowset from the RowSet type combo box.

4. Select a table or view from the list.

5. Check Read-only if you want the corresponding rowset to be read-only.

6. Check Add rowInserted event handler to add a rowInserted event handler to thesource code of the generated application.

The handler is called when a new row is inserted and enables the creation of defaultcolumn values dynamically.

7. Choose a transaction isolation level for the rowset using one of the values in theTransaction isolation combo box.

The default transaction level is READ_COMMITTED.

8. Use the SQL_command text field to prepare SQL to populate the rowset.

By default, Sun ONE Studio 5 generates the text select * from table-name.

9. Select a data column to use with a database join.

Selecting this column will display a different field other than the primary columnretrieved; however, it must be of the same data type as the primary column.

Page 36: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

36 Using Java DataBase Connectivity • June 2003

FIGURE 5 JDBC Form Wizard, Select Secondary RowSet

Previewing and Generating an ApplicationThe last panel shows a preview of a generated application. Use this panel tocomplete your generated application. In addition, you can select a package and a filename to create a completed application.

Provide the name of the package under Package and the target file under Target.

You can view the component layout and the layout from the view of the DataNavigator. What you view depends on the Swing form you have chosen to containthe data that is manipulated in your application.

Page 37: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

37

FIGURE 6 JDBC Form Wizard, Finish the Wizard

Running Your JDBC ApplicationYou can compile, run, and debug JDBC applications as if they were any other form.If you need special JDBC drivers, ensure they are in the Sun ONE Studio 5CLASSPATH, so they will, by default, be available for external compiling, executing,and debugging of JDBC-based forms.

You can run your application external to the IDE by adding paths to these packagesinto your CLASSPATH:

■ modules/ext/sql.jar■ modules/ext/rowset.jar■ lib/ext/jdbc20x.zip■ A corresponding JDBC driver. JDBC drivers are typically stored in lib/ext.

If a WebRowSet is used in your JDBC application, two more JAR files are required:■ lib/ext/parser.jar■ lib/ext/xerces.jar

Page 38: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

38 Using Java DataBase Connectivity • June 2003

Page 39: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

39

Index

CCLASSPATH, 37Component Inspector, using, 28Connection source, 19, 28

database URL, 19JDBC driver name, 19user name, 19

DData models, 24

setting for components, 25Data Navigator, 19, 23, 28Database Explorer, using with JDBC, 17

Eestablishing connections, 29establishing new connections

Advanced tab, 30database name, 30database URL, 30driver name, 30password, 30Pooled Connection Source, 30User Name, 30

example applicationswhere to download, 13

JJAR files, 37Java Database Connectivity, 15Javadoc, using in the IDE, 13JDBC

JButton, 24JCheckbox, 24JComboBox, 24, 34JList, 24Jlist, 34JRadioButton, 24JTable, 24JTextField, 34JToggleButton, 24programming, 15reference materials, 16Selecting Database Columns, 25visual and non-visual components, 24

JDBC Form Wizardpreviewing and generating an application, 36selecting database tables, 31

JDBC tab in component palette, 19JDBC visual form, creating, 27

NNBCachedRowSet, 19, 28

as a type of RowSet, 20NBJDBCRowSet, 19, 28

as a type of RowSet, 20

Page 40: Using Java DataBase Connectivity · 1. Using Java DataBase Connectivity 15 Programming JDBC 15 General Programming Steps 15 JDBC Reference Materials 16 Using the Database Explorer

40 Using Java DataBase Connectivity • June 2003

NBWebRowSet, 19, 28as a type of RowSet, 20

Non-visual components, 18

PPassword, 19Pooled Connection Source, 19, 28Previewing and generating an application, 36Properties Editor, 23

RRowSet object, 20RowSet, Other Properties and Event tabs, 21Running Your JDBC Application, 37

SSelecting a secondary rowset, 35Selecting columns to display, 33Selecting database tables, 31Stored Procedure, 19, 28Stored procedure, 24

TTransaction isolation levels, 32

VVisual Components, 18