oracle

Click here to load reader

Upload: api-3745771

Post on 14-Nov-2014

26 views

Category:

Documents


0 download

TRANSCRIPT

Oracle9i: Access the Database with Java and JDBCInstructor Guide

D11678GC31 Edition 3.1 August 2002 D37106

Authors Michael Curtis Patrice Daux Lynn Munsinger

Copyright Oracle Corporation, 2002. All rights reserved.This documentation contains proprietary information of Oracle Corporation. It is provided under a license agreement containing restrictions on use and disclosure and is also protected by copyright law. Reverse engineering of the software is prohibited.

If this documentation is delivered to a U.S. Government Agency of the Department ofDefense, then it is delivered with Restricted Rights and the following legend is

applicable:

Technical Contributors and Reviewers Edward Dowgiallo Christian.Dugas Kuassi Mensah Ekkehard Rohwedder Glenn Stokol

Restricted Rights LegendUse, duplication or disclosure by the Government is subject to restrictions for commercial computer software and shall be deemed to be Restricted Rights software under Federal law, as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in Technical Data and Computer Software (October 1988).

This material or any portion of it may not be copied in any form or by any meanswithout the express prior written permission of Oracle Corporation. Any other copying is a violation of copyright law and may result in civil and/or criminal penalties.

If this documentation is delivered to a U.S. Government Agency not within the Department of Defense, then it is delivered with Restricted Rights, as defined in FAR 52.227-14, Rights in Data-General, including Alternate III (June 1987).

Publisher Michael Sebastian

The information in this document is subject to change without notice. If you find any problems in the documentation, please report them in writing to Education Products,

Oracle Corporation, 500 Oracle Parkway, Box SB-6, Redwood Shores, CA 94065.Oracle Corporation does not warrant that this document is error-free. Oracle and all references to Oracle products are trademarks or registered trademarks

of Oracle Corporation.All other products or company names are used for identification purposes only, and may be trademarks of their respective owners.

Contents

Preface Introduction Objectives I-2 Course Overview I-3 Java Developer Courses I-4 Course Environment I-5 About the Course Applications I-6 The Order Entry Database Schema I-7 1 Introduction to Database Programming with Java Objectives 1-2 Java, J2EE, and Oracle9i 1-3 How Java Connects to a Database 1-4 JDBC 1-5 SQLJ 1-6 Java Stored Procedures 1-7 Integrated Development Environment 1-8 Exploring the JDeveloper Environment 1-9 Examining Workspaces 1-10 What Are Projects? 1-11 Creating JDeveloper Items 1-12 Summary 1-13 Practice 1-1 Overview 1-14 Practice 1 -1 1-15 2 Performing Basic SQL Statements to Access the Database Objectives 2-2 JDBC 2-3 Preparing JDBC use 2-4 Steps for Using JDBC to Execute SQL Statements 2-5 Stage 1: Registering the Driver 2-6 Stage 2: Getting a Database Connection 2-7 Stage 3: Creating a Statement 2-8 Stage 4: Executing a SQL Statement 2-9 Executing a Query 2-10 The ResultSet Object 2-11 Processing the Query Results 2-12 Stage 5: Closing Unneeded objects 2-13 A Basic Query Example 2-14 Submitting DML Statements 2-15 Submitting DDL Statements 2-16 Handling an Unknown SQL Statement 2-17

iii

Handling Exceptions 2-18 Managing Transactions 2-19 Summary 2-20 Practice 2-1 Overview 2-21 Practice 2 -1 2-22 3 More About JDBC Objectives 3-2 More on the Connect Stage 3-3 Connecting to the Database 3-4 Oracle JDBC Drivers: Thin Client Driver 3-5 Oracle JDBC Drivers: OCI Client Drivers 3-6 Oracle JDBC Drivers: KPRB Server-Side Driver 3-7 Oracle JDBC Drivers: Thin Server-Side Driver 3-8 Other JDBC Drivers 3-9 Choosing the Right Driver 3-10 About JDBC URLs 3-11 JDBC URLs with Oracle Drivers 3-12 Stage 4: More on Processing Result for the Select 3-13 How to Process the Results 3-14 Mapping Database Types to Java Types 3-15 How to Handle SQL Null Values 3-17 Advanced Data Types 3-18 Working with Large Objects 3-19 Reading BLOBs 3-20 Writing BLOBs 3-21 Reading CLOBs 3-22 Writing CLOBs 3-23 Populating LOBs in a New Table from Files 3-24 Working with BFILEs 3-26 Reading BFILEs 3-27 Working with Oracle Objects 3-28 STRUCT Object and Descriptor 3-30 Working with Oracle Object References 3-32 Working with Oracle Collections 3-33 Working with ARRAYS 3-34 Manipulating ARRAYS 3-35 The DatabaseMetaData Object 3-36 How to Obtain Database Metadata 3-37 The ResultSetMetaData Object For Dynamic SQL 3-38 How to Obtain Result Set Metadata 3-39 Summary of JDBC Classes and Interfaces 3-40

iv

Summary 3-41 Practice 3: Part I Overview 3-42 Practice 3-1 3-44 Practice 3: Part II Overview 3-45 Practice 3-2 Overview 3-46 Practice 3-2 3-47 4 JDBC Advanced Topics and Performance Extensions Objectives 4-2 Navigating in the Result Set 4-3 Result Set Navigation 4-4 Result Set Implementation 4-5 Setting Navigation for Result Set 4-6 Positioning in the Result Set 4-7 Updating the Result Set 4-9 Inserting in the Result Set 4-10 Scrollable and Updateable Restrictions with Result Sets 4-11 The PreparedStatement Object 4-13 How to Create a PreparedStatement 4-14 How to Execute a PreparedStatement 4-15 The CallableStatement Object 4-16 CallableStatement for a Procedure Call(1) 4-18 CallableStatement for a Procedure Call(2) 4-19 REF CURSOR 4-20 Prefetching Rows in a Query 4-22 Prefetching Rows: Example 4-23 Prespecifying Column Types 4-24 Prespecifying Types: Example 4-25 Objectives of Update Batching 4-26 Batched Updates of Prepared Statements 4-27 Managing Batch Execution 4-30 The ROWID Pseudocolumn 4-31 Example: Using ROWID for In-Place Updates 4-32 Summary 4-33 Practice 4-1 Overview 4-34 5 JDBC Optional Package and JDBC in Web Applications Objectives 5-2 J2EE/JDBC 2.0 Features 5-3 Database Connection Flexibility 5-4 Java Naming Directory Interface 5-5

v

Using JNDI 5-6 Creating a Data Source 5-7 Registering the Data Source 5-8 Using the Data Source 5-9 Connection Pooling 5-10 Connection Cache 5-12 Using a Connection Cache 5-13 Connection Cache Properties 5-14 Distributed Transactions Overview 5-15 Using Distributed Connections 5-16 Performing a Distributed Transaction 5-18 Distributed Transaction Branch Testing 5-19 Statement Caching 5-21 Implicit Statement Caching 5-22 Explicit Statement Caching 5-23 Implicit Statement Caching Use 5-24 Explicit Caching Code Example 5-25 Client Security with JDBC 5-26 Authentication Encryption and Integrity 5-27 Setting Encryption and Integrity Parameters for Thin 5-28 JDBC in Applets 5-29 Connecting to the Database Through an Applet 5-30 Connection Manager 5-31 Applet Connection String 5-32 Applets and Firewalls 5-33 Applet Using Thin Driver and Firewall 5-34 Packaging Applets 5-35 Summary 5-36 Practice 5 Overview 5-37 Practice 5-1 5-38 Practice 5-2 5-43 6 Developing and Deploying Stored Procedures Objectives 6-2 Overview 6-3 What Is a Java Stored Procedure? 6-4 Why Use Java Stored Procedures? 6-5 How Do You Use Java Stored Procedures? 6-7 The Oracle9i Database 6-8 The Oracle9i JVM 6-9 Overview of Creating and Running a Stored Procedure 6-11 Step 1: Develop the Stored Procedure 6-12 Writing a Java Class for Deployment as Stored Procedures 6-13 The Database Server Default Connection 6-14 Internal Connection to the Database 6-16vi

Example: Rentals.beginOrder() 6-17 Step 2: Load the Stored Procedure 6-18 Loading Java in the Database 6-19 Loading Java Code in the Server 6-20 Step 3: Publish the Stored Procedure 6-22 Publishing a Java Procedure 6-23 Writing a Call Spec 6-24 Deploying a Java Stored Procedure with JDeveloper 6-25 Steps for Deployment 6-26 Deployment Profile 6-27 Selecting the Methods to Publish 6-28 Publishing the Methods 6-29 Deploying in the Database 6-30 Database Browsing 6-31 How to Delete a Java Stored Procedure 6-32 Step 4: Call the Stored Procedure 6-33 Calling a Stored Procedure Using JDBC(1) 6-34 Calling a Stored Procedure Using JDBC(2) 6-36 Calling a Stored Procedure Using SQLJ 6-37 Calling a Stored Function Using SQLJ 6-38 Calling Java from SQL*Plus 6-39 Calling Java from a Database Trigger 6-40 How to Develop a Trigger in Java 6-41 Developing a Trigger in Java 6-42 Calling Java from SQL DML 6-43 Calling Java from PL/SQL 6-44 Access Control 6-45 Summary 6-46 Practice 6 Overview 6-47 Practice 6 6-48 7 Embedding SQL Statements in Java Code with SQLJ Objectives 7-2 SQLJ 7-3 Advantages of SQLJ Compared to JDBC 7-4 The SQLJ Translator 7-5 Preparing SQLJ Use 7-6 Running SQLJ in Command Line 7-8 SQL Statement with SQLJ 7-9 Selecting a Single Row with SQLJ 7-10 Overview of Querying a Database with SQLJ 7-11 Register the Driver and Connect Using Oracle.connect 7-12 How to Manually Register the Driver and Connect 7-13 Register Manually the Driver and Connect 7-14

vii

What Is a Connection Context? 7-15 Connection Code Example 7-16 How to Query a Database with SQLJ 7-17 Exception Handling 7-18 How to Handle SQL Null Values 7-19 Guided Practice 7-1: Writing SQLJ Statements 7-20Guided Practice 7-2: Writing SQLJ Statements 7-21

What Is an Iterator? 7-22 How to Execute a Multirow Query by Using a Named Iterator 7-23 Selecting a Calculated Field or Function Call into a Named Iterator 7-25 How to Execute a Query by Using a Positional Iterator 7-26 Named Iterator Versus Positional Iterator 7-28 Embedding PL/SQL with SQLJ 7-30 Calling a Procedure with SQLJ 7-31 Calling a Function with SQLJ 7-32 How to Add a New SQLJ File to a JDeveloper Project 7-33 Deploying SQLJ Code in JDeveloper 7-35 Configuring SQLJ Translator Options in JDeveloper 7-36 SQLJ Translator Options: Translator Warnings 7-37 SQLJ Translator Options: Online SQL Checking 7-38 Summary 7-39 Practice 7 Overview 7-40 Practice 7 7-41 Appendix A Appendix B Appendix C

viii

Preface

Oracle9i: Access the Database with Java and JDBC - Preface - 2

Profile Before You Begin This Course Before you begin this course, you should have the following qualifications: Thorough knowledge of Java and SQL languages Working experience with a Java development tool

Prerequisites Required SQL1 (AKA Introduction to Oracle) or equivalent experience in SQL programming Java Programming or Equivalent experience with Java

Suggested Familiarity with the JDeveloper IDE, as provided by the Oracle Java Programming course, or through self-study courses such as " Oracle9i JDeveloper: Introduction for J2EE Developers" How This Course Is Organized Oracle9i: Access the Database with Java and JDBC is an instructor-led course featuring lecture and hands-on exercises. Online demonstrations and written practice sessions reinforce the concepts and skills introduced.

Oracle9i: Access the Database with Java and JDBC - Preface - 3

Related Publications Oracle Publications Title Oracle9i SQLJ Developers Guide and Reference Oracle9i JDBC Developers Guide and Reference Oracle9i JPublisher Users Guide Oracle9i Java Stored Procedures Developers Guide Oracle9i Enterprise JavaBeans Developers Guide and Reference

Part Number A90212-01 A90211-01 A90214-01 A90210-01 A90188-01

Additional Publications System release bulletins Installation and users guides read.me files International Oracle Users Group (IOUG) articles Oracle Magazine

Oracle9i: Access the Database with Java and JDBC - Preface - 4

Typographic Conventions Typographic Conventions in Text

Convention Bold italic Caps and lowercase

Element Glossary term (if there is a glossary) Buttons, check boxes, triggers, windows Code output, directory names, filenames, passwords, pathnames, URLs, user input, usernames Graphics labels (unless the term is a proper noun) Emphasized words and phrases, titles of books and courses, variables

Example The algorithm inserts the new key. Click the Executable button. Select the Cant Delete Card check box. Assign a When-Validate-Item trigger to the ORD block. Open the Master Schedule window. Code output: debug.set (I, 300); Directory: bin (DOS), $FMHOME (UNIX) Filename: Locate the init.ora file. Password: User tiger as your password. Pathname: Open c:\my_docs\projects URL: Go to http://www.oracle.com User input: Enter 300 Username: Log on as scott Customer address (but Oracle Payables)

Courier new, case sensitive (default is lowercase)

Initial cap

Italic

Do not save changes to the database. For further information, see Oracle7 Server SQL Language Reference Manual. Enter [email protected], where user_id is the name of the user. Select Include a reusable module component and click Finish. This subject is covered in Unit II, Lesson 3, Working with Objects. Use the SELECT command to view information stored in the LAST_NAME column of the EMP table.

Quotation marks

Interface elements with long names that have only initial caps; lesson and chapter titles in cross-references SQL column names, commands, functions, schemas, table names

Uppercase

Oracle9i: Access the Database with Java and JDBC - Preface - 5

Convention Arrow Brackets Commas Plus signs

Element Menu paths Key names Key sequences Key combinations

Example Select File> Save. Press [Enter]. Press and release keys one at a time: [Alternate], [F], [D] Press and hold these keys simultaneously: [Ctrl]+[Alt]+[Del]

Typographic Conventions in Code Convention Caps and lowercase Lowercase Element Oracle Forms triggers Column names, table names Passwords PL/SQL objects Example When-Validate-Item SELECT last_name FROM s_emp; DROP USER scott IDENTIFIED BY tiger; OG_ACTIVATE_LAYER (OG_GET_LAYER (prod_pie_layer)) CREATE ROLE role SELECT userid FROM emp;

Lowercase italic Uppercase

Syntax variables SQL commands and functions

Typographic Conventions in Navigation Paths This course uses simplified navigation paths, such as the following example, to direct you through Oracle Applications. (N) Invoice>Entry>Invoice Batches Summary (M) Query>Find (B) Approve This simplified path translates to the following: 1. (N) From the Navigator window, select Invoice>Entry>Invoice Batches Summary. 2. (M) From the menu, select Query>Find. 3. (B) Click the Approve button. N = Navigator, M = Menu, B = Button

Oracle9i: Access the Database with Java and JDBC - Preface - 6

Introduction

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 20 minutes 20 minutes

Topic Lecture Total

ObjectivesAfter completing this course, you should be able to do the following: Use JDBC to connect to a database and execute SQL statements in a Java application Deploy Java stored procedures in an Oracle9i database Use SQLJ to embed SQL statements in Java code

I-2

Copyright Oracle Corporation, 2002. All rights reserved.

Additional Information Additional information on the course topics can be found at the following URLs: http://otn.oracle.com/docs/tech/java/sqlj_jdbc/content.html http://developer.java.sun.com/developer/Books/JDBCTutorial/

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

Oracle9i: Access the Database with Java and JDBC I-2

Course Overview Lesson 1 introduces database programming in Java and reviews Oracle9i JDeveloper. Lessons 2, 3, 4, and 5 teach you how to access a database using JDBC and how to use Oracle JDBC extensions with J2EE. Lesson 6 shows you how to develop Java stored procedures and use JDeveloper to deploy them in an Oracle9i database. Lesson 7 teach you how to use SQLJ to embed SQL statements in Java code.

I-3

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i: Access the Database with Java and JDBC I-3

Java Developer CoursesJava Programming Oracle9i: Access the Database with Java and JDBC Oracle9i: Introduction for J2EE Developers Oracle9i JDeveloper: Develop Applications with BC4J Oracle9i: Create Servlets and JavaServer Pages (Related subjects) Oracle9i: Develop Enterprise JavaBeans Oracle9i JDeveloper: Class Modeling Activity Modeling Oracle9i JDeveloper: Create Swing Clients for BC4J BC4J Class Modeling

Oracle9i JDeveloper: Create Product Extensions

I-4

Copyright Oracle Corporation, 2002. All rights reserved.

Java Developer: Curriculum Map The diagram shows major courses in the Oracle9i Java curriculum. This should help you to understand the position of the course that you are currently attending. inClass Courses Note that certain inClass (classroom) courses may become available in some training regions later than others. Please check with Oracle University for specific availability. BC4J Courses Business Components for Java (BC4J) courses are highlighted in the diagram. These are specific to the BC4J developer track, for developers who are using the framework. Oracle University Online Learning (OUOL) The self-paced titles shown on this diagram are indicated by monitor icons. Instructor Note The scope of your coverage for this page will naturally depend upon student interest. We suggest that you at least indicate its presence in the book, and point out that its main purpose is to help students understand where this course fits in the larger curriculum. It is not intended as a heavy marketing exercise.

Oracle9i: Access the Database with Java and JDBC I-4

Course Environment The development tool is Oracle9i JDeveloper The database is Oracle9i (Release, 9.0.1)

I-5

Copyright Oracle Corporation, 2002. All rights reserved.

Course Environment Oracle provides a server-side Java engine for the Oracle9i database. It consists of the following components: Java Virtual Machine Server JDBC driver SQLJ run time

Oracle9i: Access the Database with Java and JDBC I-5

About the Course Applications The course uses applications that support the Order Entry system. The applications access the common schema database. In the practices, you will write applications that access the database and manipulates the database objects.

I-6

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i: Access the Database with Java and JDBC I-6

The Order Entry Schema

From Product Media Schema

I-7

Copyright Oracle Corporation, 2002. All rights reserved.

The Order Entry Database Schema All of the courses use a common database schema. The schema used for this course uses the Order Entry subset of this common schema. The common schema is packaged with the Oracle9i database. CREATE TABLE customers CREATE TABLE order_items CREATE TABLE orders CREATE TABLE inventories CREATE TABLE product_information CREATE TABLE product_descriptions Additionally, two other objects are created: CREATE TYPE cust_address_typ AS OBJECT CREATE TYPE phone_list_typ AS VARRAY(5) OF VARCHAR2(25); Note: Appendix A contains a detailed description of each table.

Oracle9i: Access the Database with Java and JDBC I-7

Introduction to Database Programming with Java

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 20 minutes 15 minutes 35 minutes

Topic Lecture Practice Total

ObjectivesAfter completing this lesson, you should be able to do the following: Describe how Java applications connect to the database Describe how Java database functionality is supported by Oracle9i Identify the main components in JDeveloper

1-2

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson introduces you to the different types of database applications that can be written in Java in a J2EE environment, including: Client applets and applications Servlets and JSPs Java stored procedures It also presents how JDBC and SQLJ are used to connect to the database. Finally, a brief overview of Oracle9i JDeveloper Integrated Development Environment (JDeveloper IDE) is covered to describe the organization of the tool.

Oracle9i: Access the Database with Java and JDBC 1-2

Java, J2EE, and Oracle9iClient Web server Presentation Application server Business logic Data

OC4J

OC4J Oracle Database

Oracle9i Application Server J2EE Certified Environment

1-3

Copyright Oracle Corporation, 2002. All rights reserved.

Java and Oracle9i Oracle provides a complete and integrated platform called Oracle9i, which supports all of the server-side requirements for Java applications. Oracle9i consists of the following: Oracle database In addition to its database management features, the Oracle database (currently Oracle9i) provides support for a variety of Java-based structures, including Java components and Java stored procedures. These Java structures are executed in the database by its built-in Java Virtual Machine, called the Oracle Java Virtual Machine (Oracle JVM). Oracle9i Application Server Oracle9i Application Server maintains and executes all of your application logic, including Enterprise JavaBeans, through its own built-in JVM, the Enterprise Java Engine. Oracle9i Application Server uses the Apache Web server to execute servlets and JSPs. J2EE Architecture J2EE is a standard technology which provides a set of APIs and a run time infrastructure for hosting and managing applications. It specifies roles and interfaces for applications and the run time onto which applications could be deployed. And hence the application developers just need to focus on the application logic and related services, while leveraging the run time for all infrastructure related services. Instructor Note For more architectural information on Oracle 9i Application Server, direct participants to the various eClasses available from Oracle Learning Network.Oracle9i: Access the Database with Java and JDBC 1-3

How Java Connects to a DatabaseClient applications, applets, and servlets use JDBC

JDBC Client application or applet

1-4

Copyright Oracle Corporation, 2002. All rights reserved.

How Java Connects to a Database To query an Oracle database, any Java application must have a way to connect to the database. This is performed by using JDBC. Java Database Connectivity (JDBC) is a standard application programming interface (API) that is used for connecting a Java application to relational databases. The networking protocol used depends on which JDBC driver you are using; for example, the Oracle thin JDBC driver uses Oracle Net. Running SQL from a Server-side Application Applications that run inside the database use JDBC to execute their SQL queries. This includes Java stored procedures.

Oracle9i: Access the Database with Java and JDBC 1-4

JDBC JDBC is a standard interface for accessing relational databases from Java. The JDBC class library is part of the Java 2, Standard Edition (J2SE). JDBC is used by client applications, applets, servlets, and Java stored procedures.JDBC calls Driver Database commands Database

1-5

Copyright Oracle Corporation, 2002. All rights reserved.

About Java Database Connectivity (JDBC) The java.sql package contains a set of interfaces that specify the JDBC API. This package is part of the Java 2, Standard Edition. Database vendors implement these interfaces in different ways, but the JDBC API itself is standard. Using JDBC, you can write code that: Connects to one or more data servers Executes any SQL statement Obtains a result set so that you can navigate through query results Obtains metadata from the data server Each database vendor provides one or more JDBC drivers. A JDBC driver implements the interfaces in the java.sql package, providing the code to connect to and query a specific database.

Oracle9i: Access the Database with Java and JDBC 1-5

SQLJ SQLJ is Java with embedded SQL. SQLJ is passed through a translator. It can check SQL against the database. It generates Java code with JDBC calls.SQLJ Translator Java compiler

SQLJ code Oracle

Java code with JDBC calls

Java class

1-6

Copyright Oracle Corporation, 2002. All rights reserved.

About SQLJ SQLJ provides a way to embed SQL statements and constructs in Java programs. SQLJ statements are embedded directly in a Java program. When the program is compiled, the SQLJ translator first translates the SQLJ statements into JDBC calls. You can write a program that contains a mixture of JDBC calls and SQLJ statements. That way, you get all of the benefits of static SQL compilation and query checking offered by SQLJ, plus the run-time flexibility of JDBC if you need it. Advantages of SQLJ Compared to JDBC SQLJ is less intricate than JDBC, because you write SQL statements to interact with the database. SQLJ provides more concise and less error-prone static SQL constructs than JDBC. SQLJ provides stronger typing than JDBC code, because the SQL code is checked at compile time rather than run time. A server connection is used to check your embedded SQL code to verify that it is syntactically and semantically correct. Note: You can think of SQLJ translator within the SQLJ technology as a precompiler in the PRO* environment.

Oracle9i: Access the Database with Java and JDBC 1-6

Java Stored Procedures Procedures that are compiled, verified, and stored in Oracle9i Fast, because they run in DBMS memory space Portable within the Java environment, because they are written in Java

1-7

Copyright Oracle Corporation, 2002. All rights reserved.

Java Stored Procedures and Triggers Java stored procedures are Java methods that reside and run in an Oracle9i database. To publish Java methods, you write call statements, that map Java method names, parameter types, and return types to their SQL counterparts. You can call a Java stored procedure from a Java class, from SQL, or from PL/SQL. A Java stored procedure executes several SQL statements with a single call from the client application. This minimizes network traffic. Also, because the procedure is stored on the server, it runs faster than a client process. As with PL/SQL stored procedures, a stored procedures executable code is cached and shared among users, that reduces memory requirements. A database trigger is a stored procedure associated with a specific table or view. Oracle9i invokes the trigger automatically whenever the table or view is modified. Deploying Stored Procedures from JDeveloper The JDeveloper Deployment Wizard loads your stored procedures into the database and automatically generates the SQL call specifications for your procedures.

Oracle9i: Access the Database with Java and JDBC 1-7

Integrated Development Environment

Development UML Multi-tier

Debug Exchange Database

XML SCM

Synchronized changes

HTML Deployment

1-8

Copyright Oracle Corporation, 2002. All rights reserved.

Integrated Development Environment The IDE's addin architecture means that the tool is extensible and all the components (for example, navigator, editor, modeler) share memory models and event systems. In this way, an update in one tool is notified to another tool so that it can refresh its image or take other appropriate actions. In Release 9i, the JDeveloper IDE has been completely redeveloped in pure Java. Customizable Environment You can customize the JDeveloper Integrated Development Environment, and arrange its look, to better suit your project needs and programming style. To suit the IDE to your individual taste. You can: Change the look and feel of the IDE Create and manipulate custom navigators Customize the Component Palette Customize the IDE environment Select JDeveloper's internal Web server Arrange the windows in the IDE Instructor Note SCM stands for Source Control Management. Exchange is provided through XMI files allowing you to import UML definitions coming from third party tools like Rational, TogetherJ etc.

Oracle9i: Access the Database with Java and JDBC 1-8

Exploring the JDeveloper Environment

Command Area

Viewer

Project Navigator

Inspector

1-9

Copyright Oracle Corporation, 2002. All rights reserved.

The Oracle9i JDeveloper Environment JDeveloper contains four major user interface components. These components are what you use to edit code, design and manage the user interface, and navigate around your program. The Command Area The Command Area in JDeveloper is the control center, that contains the main menu and a toolbar with shortcuts to commonly used menu items. The Command Area also holds the Component Palette, which contains components such as buttons, grids, and so on. The Project Navigator Window The Project Navigator window is made of two components. The navigator pane shows a list of files or classes in a project. The files may be Java source files, .class files, graphics files, HTML, XML documents, and so on. The structure pane lists all the methods, attributes, and graphical user interface (GUI) components in a selected class. Viewers Viewers are where most of the work takes place; this is where you write code and design user interfaces. Open a viewer by double-clicking the item that you want to edit or view. Each open viewer has sections or tabs specific to the type of item being viewed (Source, Design, Bean, and Doc.). Property Inspector The Property Inspector is the pane that shows the properties and events that are associated with a selected component in the design section of a viewer.

Oracle9i: Access the Database with Java and JDBC 1-9

Examining Workspaces Contain multiple projects Views onto currently used objectsWorkspace

Navigator window Structure window

1-10

Copyright Oracle Corporation, 2002. All rights reserved.

Project Organization Oracle9i JDeveloper uses a well-defined structure to manage Java programming projects. The structure is hierarchical and supports workspaces, projects, applications, images, .html files, and more. Workspaces The workspace is the highest level in the control structure. It is a view of all the objects you currently need, while working. A workspace keeps track of the projects and the environment settings that you use, while you are developing your Java program. When you open JDeveloper, the last workspace used is opened by default, so you can pick up where you left off. Workspaces are stored in files with the extension .jws. You do not edit a workspace filedirectly. Whenever you save your workspace, you are prompted to save all of the current open

files. Saving the workspace does not save the open files, but only the current environment configuration. To save the open and modified files, select the Save or Save All option from the File menu. Note: You can view the content of a workspace file by using any text editor. Determining Workareas Consider workareas to be a view onto the objects currently used. You may choose to create workareas that include projects that were created in different workarea. Workarea object groupings could be based around a business area (AP,GL,AR), the phase in a life cycle (analysis, design, deploy) or the structure of the application (UI, business logic, data structure).Oracle9i: Access the Database with Java and JDBC 1-10

What Are Projects? Contain related files Manage project and environment settings Manage compiler and debug optionsProject

Project files

1-11

Copyright Oracle Corporation, 2002. All rights reserved.

Projects

JDeveloper projects organize file elements used to create your program. A project file has the file extension .jpr and keeps track of the source files, packages, classes, images, and other elements that might be needed for your program. You can add multiple projects to your workspace to easily access, modify, and reuse your source code. You can view the content of a project file using any text editor. Projects also manage environment variables such as the source and output paths used for compiling and running your program. Projects also maintain compiler, run time, and debugging options so you can customize the behavior of those tools per project. In the System Navigator window, projects show as the second level in the hierarchy under the workspace. When you select a .java or .html file in the navigation window, the structure window displays the elements of the file in a tree format. For example, when you select a .java source file, the classes, interfaces, methods, and variables are displayed. To edit source code, double-click the file in the navigation window to display the contents in the appropriate viewer. The structure window can be used to quickly locate specific areas of code in your Java source files and browse the class hierarchy. When you are working with the visual designer, the structure window displays the components of your user interface and their associated event handling methods in a hierarchical tree format. Note: The italic font is used to indicate the file names that havent been saved yet.Oracle9i: Access the Database with Java and JDBC 1-11

Creating JDeveloper Items Invoked in the Menu with File | New Categorized by type Create any JDeveloper element

1-12

Copyright Oracle Corporation, 2002. All rights reserved.

New Elements You can create any JDeveloper item from this window. The context for creating the item must be correct. You must have the correct element selected in the Category column, in order to create the appropriate Item. The JDK used for development can be any version, but must be compatible with the intended deployment run-time environment. While creating the workspace your can define the paths used for the files stored. All the files are stored using the following convention: workspace\project\package

Oracle9i: Access the Database with Java and JDBC 1-12

Summary JDBC provides database connectivity for various Java constructs, including servlets and client applications JDBC is a standard Java interface and part of the J2SE SQLJ is a precompiler facility that generates Java code with embedded JDBC calls Stored procedures are for data-intensive processing in the database Java is supported in the Oracle database by the Oracle Java Virtual Machine (Oracle JVM)

1-13

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i: Access the Database with Java and JDBC 1-13

Practice 1 OverviewThis practice covers: Starting Oracle9i JDeveloper Creating a workspace and a project Loading a .java file and compiling it Invoking the online help

1-14

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i: Access the Database with Java and JDBC 1-14

Practice 1 Goal The goal of this practice is to review JDeveloper IDE and refresh your understanding of some basic operations in order to feel comfortable with the tool. Your Assignment You launch JDeveloper, and create a workspace and a project. You then upload a .java file in your project, you compile it and run it. Finally you invoke the online help and do some research on Class documentation. Start Oracle9i JDeveloper Click the JDeveloper icon on the desktop Create a new workspace and a project Use the File | New menu option In the New Gallery select Projects in the Categories pane and double-click the Workspace object in the Items pane In the directory name, leave the path and replace the Workspace name by Lesson01 Change the File Name to Lesson01.jws and click OK In the New Project dialog box, leave the indicated path , for the Directory Name, and replace the Project name by Intro Change the File Name to Intro.jws and click OK Load a .java file Load a .Java file into your current project Use the File | Open menu option In the Location, specify the C:\ labs\ directory Select the HelloWorld.java file and click OK On the Add Project Source Path question, answer Yes to update the project source path HelloWorld.java appears in the System Navigator Run a .java file Run a .Java file into your current project Read the HelloWorld.java file in the Editor window Right-click HelloWorld.java entry in the System Navigator Select the Run HelloWorld option in the menu Does the file compile? What is displayed in the Log window? Hello World should appear. Use the Online Help Searching for Java classes info Select Help in the menu In the Contents tab open the Reference node

Oracle9i: Access the Database with Java and JDBC 1-15

Practice 1 (continued) Locate the Oracle JDBC entry Select the oracle.jdbc.driver package How many classes does this package contain? There are 11 classes in this package Locate the OracleConnection class and scroll through the documentation to see class details Use the Back icon Click the left arrow Select the Oracle.jdbc package OracleConnection exists in this package as an interface Select the OracleConnection hyperlink to view the details Since which version of the database is this interface available? The interface is available since 8.1.7 Select the Tree hyperlink in the Menu Items Scroll through the Package/Class/Interface hierarchy How many references to OracleResultSet do you find?

Oracle9i: Access the Database with Java and JDBC 1-16

Performing Basic SQL Statements to Access the Database

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 40 minutes 60 minutes 100 minutes

Topic Lecture Practice Total

ObjectivesAfter completing this lesson, you should be able to do the following: Set PATH and CLASSPATH variables in order to use JDBC drivers Load and register a JDBC driver Connect to an Oracle database Execute the steps to perform a SELECT statement Map simple Oracle database types to Java types Execute a simple a DML and a DDL statement Control Transactions

2-2

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim The Java Database Connectivity (JDBC) API contains Java classes and interfaces that provide low-level access to databases. In this lesson, you learn how to use the JDBC API to access data in a database.

Oracle9i: Access the Database with Java and JDBC 2-2

JDBC JDBC is a standard interface for connecting to relational databases from Java. The JDBC Core API package in java.sql. JDBC 2.0 Optional Package API in javax.sql JDBC 3.0 API includes the Core API and Optional Package API

Include the vendor JDBC driver archive in the CLASSPATH. Use the classes12.jar file for Oracle JDBC drivers2-3Copyright Oracle Corporation, 2002. All rights reserved.

About Java Database Connectivity (JDBC) The java.sql package contains a set of interfaces, which specifies the JDBC API . This package is part of Java 1.1.8 and Java 2, and is supported by JDeveloper. Database vendors implement these interfaces in different ways, but the JDBC API itself is standard. Instructor Note JDBC 1.22 is part of JDK 1.1; JDBC 2.0 is part of Java 2.

Oracle9i: Access the Database with Java and JDBC 2-3

Preparing JDBC Use Setting the PATH[Oracle Home]\bin

Setting the CLASSPATH[Oracle Home]\jdbc\lib\classes12.jar

Importing JDBC packages// Standard packages import java.sql.*; import java.math.*; // optional // Oracle extension to JDBC packages import oracle.jdbc.*; import oracle.sql.*;

2-4

Copyright Oracle Corporation, 2002. All rights reserved.

Requirements for Using Oracle JDBC This section describes the environment variables that must be set for the JDBC OCI driver and the JDBC Thin driver, focusing on the Sun Microsystems Solaris and Microsoft Windows NT platforms. You must set the CLASSPATH for your installed JDBC OCI or Thin driver. Depending on whether you are using the SDK 1.2.x versions or JDK 1.1.x versions, you must set one of these values for the CLASSPATH: [Oracle Home]/jdbc/lib/classes12.jar (and optionally [Oracle Home]/jdbc/lib/nls_charset12.jar) for full NLS character support) OR [Oracle Home]/jdbc/lib/classes111.jar (and optionally [Oracle Home]/jdbc/lib/nls_charset11.jar) for full NLS character support) Ensure that there is only one classes*.zip file version and one nls_charset*.zip file version in your CLASSPATH. JDBC OCI driver If you are installing the JDBC OCI driver, you must also set the following value for the library path environment variable [Oracle Home]/lib The JDBC package Your Java class must import java.sql.* to be able to use the JDBC classes, and include the JDBC driver classes from your database vendor in the CLASSPATH. For more information about required path and classpath settings for Oracle JDBC, refer to the Oracle9i JDBC Developers Guide and Reference.Oracle9i: Access the Database with Java and JDBC 2-4

Steps for Using JDBC to Execute SQL StatementsLoad/Register JDBC Driver Connect SQL statement DML/ DDL statement SELECT statement Process results

Close

2-5

Copyright Oracle Corporation, 2002. All rights reserved.

Steps to Execute an SQL Statement with JDBC The following are the key steps: Load and register the driver (Use the java.sql.DriverManager class) Obtain a Connection object (Use java.sql.DriverManager to do this) Create a Statement object (Use the Connection object) Execute a query, DML, or DDL (Use the Statement object) While executing a query if you obtain a ResultSet object, then iterate through the ResultSet to process the data for each row that satisfies the query. Close the ResultSet, Statement, and Connectionobject when finished Dealing with Exceptions When using JDBC, all of the methods that access the database throw SQLExceptionif anything goes wrong. You should always deal with this exception in your JDBC code. SQLExceptionhas a number of methods that you can call to get information about the exception, including: getMessage(): Returns a string that describes the error getErrorCode(): Retrieves the vendor-specific exception code getSQLState(): Retrieves the SQL state value Class.forName(): Throws a ClassNotFoundExceptionif the specified class cannot be found.

Oracle9i: Access the Database with Java and JDBC 2-5

Stage 1: Registering the Driver Register the driver in the code:

DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); Class.forName ("oracle.jdbc.OracleDriver"); java -Djdbc.drivers = oracle.jdbc.OracleDriver ;

Register the driver when launching the class:

2-6

Copyright Oracle Corporation, 2002. All rights reserved.

Loading the Driver JDBC drivers must register themselves with the driver manager. There are two ways to perform this: 1. Use the registerDriver() method of DriverManager. 2. Use the forName() method of the java.lang.Class class to load the JDBC drivers directly, as follows: try { Class.forName("oracle.jdbc.driver.OracleDriver");}

catch (ClassNotFoundException e) {} Using the Class.forName() method calls the static initializer of the driver class. The driver class does not need to be present at compile time. However, this method is valid only for JDK-compliant Java virtual machines. You can register the driver at execution time. In this case, the registering statements that may exist in your Java class is ignored. Example of use with Djdbc option in command line: C:>java -Djdbc.drivers=oracle.jdbc.OracleDriver MyClass Instructor Note oracle.jdbc.OracleDriver package provides new interfaces and classes that can be used in place of the previous oracle.jdbc.driver.OracleDriver classes.

Oracle9i: Access the Database with Java and JDBC 2-6

Stage 2: Getting a Database ConnectionIn JDBC 1.0 use the DriverManager class Provides overloaded getConnection() methods All require a JDBC URL to specify the connection details

Example:Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@myhost:1521:ORCL", "scott","tiger");

Vendors can provide different types of JDBC drivers2-7Copyright Oracle Corporation, 2002. All rights reserved.

Getting a Connection to the Database Use the DriverManager to create a connection by calling the getConnection() method. The getConnection() method is overloaded, for example: getConnection(String url) getConnection(String url, Properties props), where properties must include at least a value for the following key names: user and password. getConnection(String url, String user, String password) In each case you must supply a URL like string that identifies the registered JDBC driver to use, and the database connection string and security credentials, if required. Note: JDBC 2.0 and later versions provide other ways of obtaining a connection object such as by using JNDI instead of a database URL.

Oracle9i: Access the Database with Java and JDBC 2-7

Stage 3: Creating a StatementJDBC Statement objects are created from the Connection instance: Use the createStatement() method Provides a context for executing an SQL statement

Example:Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@myhost:1521:ORCL", "scott","tiger"); Statement stmt = conn.createStatement();

2-8

Copyright Oracle Corporation, 2002. All rights reserved.

Statement Objects in JDBC The slide lists the three methods that you can call to execute a SQL statement. The following slides describe how to call each method. The execute() method is useful for dynamically executing an unknown SQL string. JDBC provides two other statement objects: PreparedStatement, for precompiled SQL statements CallableStatement, for statements that execute stored procedures Objects and Interfaces java.sql.Statement is an interface, not an object. When you declare a Statement object and initialize it using the createStatement() method, you are creating the implementation of the Statement interface supplied by the Oracle driver that you are using.

Oracle9i: Access the Database with Java and JDBC 2-8

Stage 4: Executing a SQL StatementThe Statement interface provides three methods to execute SQL statements: Use executeQuery(String sql)for SELECT statements Returns a ResultSet object for processing rows.

Use executeUpdate(String sql) for DML/DDL Returns an int

Use execute(String) for any SQL statement Returns a boolean value

2-9

Copyright Oracle Corporation, 2002. All rights reserved.

Statement Objects in JDBC (continued) Use executeQuery(String sql) for SELECT statements Returns a ResultSet object for processing rows Use executeUpdate(String sql) for DML/DDL Returns an int value indicating number of rows affected by the DML, otherwise it is 0 for DDL Use execute(String) for any SQL statement Returns boolean value of true if the statement returns a ResultSet(like queries), otherwise it returns a false

Oracle9i: Access the Database with Java and JDBC 2-9

Executing a QueryProvide SQL query string, without semicolon, as argument to executeQuery() method Returns a ResultSet objectStatement stmt = null; ResultSet rset = null; stmt = conn.createStatement(); rset = stmt.executeQuery ("SELECT ename FROM emp");

2-10

Copyright Oracle Corporation, 2002. All rights reserved.

Execute a Query and Return a Result Set Object To query the database, use the executeQuery() method of your Statement object. This method takes a SQL statement as input and returns a JDBC ResultSet object. This statement follows standard SQL syntax.

Oracle9i: Access the Database with Java and JDBC 2-10

The ResultSet Object The JDBC driver returns the results of a query in a ResultSet object. A ResultSet object maintains a cursor pointing to its current row of data. Provides methods to retrieve column values.

2-11

Copyright Oracle Corporation, 2002. All rights reserved.

The ResultSet Object The ResultSet object is a table of data representing a database result set, which is generated by executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. A default ResultSet object is not updateable and has a cursor that moves forward only. Thus, it is possible to iterate through it only once and only from the first row to the last row. New methods in the JDBC 2.0 API make it possible to produce ResultSet objects that are scrollable and updateable.

Oracle9i: Access the Database with Java and JDBC 2-11

Processing the Query ResultsThe executeQuery() method returns a ResultSet Use the next() method in loop to iterate through rows. Use getXXX() methods to obtain column values by column position in query, or column name.stmt = conn.createStatement(); rset = stmt.executeQuery( "SELECT ename FROM emp"); while (rset.next()) { System.out.println (rset.getString("ename")); }

2-12

Copyright Oracle Corporation, 2002. All rights reserved.

The getXXX() Methods The ResultSet class has several methods that retrieve column values for the current row. Each of these getXXX() methods attempts to convert the column value to the specified Java type and return a suitable Java value. For example, getInt() gets the column value as an integer, getString() gets the column value as a string, and getDate() returns the column value as a date. The next() method return true if a row was found, otherwise it returns false. Use it to check if a row is available, and to step through subsequent rows. Many getXXX() methods to get the column values, where XXX is a Java data type, for example: getString(pos) returns column in pos as a String getInt(idx)returns column in posas an int. And so on

Oracle9i: Access the Database with Java and JDBC 2-12

Stage 5: Closing Unneeded objectsExplicitly close a Connection, Statement, and ResultSet to release resources that are no longer needed. Call their respective close() methodsConnection conn = ...; Statement stmt = ...; ResultSet rset = stmt.executeQuery( "SELECT ename FROM emp"); ... // clean up rset.close(); stmt.close(); conn.close(); ...2-13Copyright Oracle Corporation, 2002. All rights reserved.

Closing the ResultSet, Statement, and Connection Objects You must explicitly close all ResultSet and Statement objects after you finish using them. The close() methods clean up memory and release database cursors, so if you do not explicitly close your ResultSet and Statement objects, serious memory leaks may occur, and you may run out of cursors in the database. You then need to close the connection. The server-side driver runs within a default session. You are already connected, and you cannot close the default connection made by the driver. Calling close() on the connection does nothing.

Oracle9i: Access the Database with Java and JDBC 2-13

A Basic Query Exampleimport java.sql.*; class TestJdbc { public static void main (String args [ ]) throws SQLException { DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@myHost:1521:ORCL","scott", "tiger"); Statement stmt = conn.createStatement (); ResultSet rset = stmt.executeQuery ("SELECT ename FROM emp"); while (rset.next ()) System.out.println (rset.getString ("ename")); rset.close(); stmt.close(); conn.close();} }

2-14

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i: Access the Database with Java and JDBC 2-14

Submitting DML Statements1. Create an empty statement object.Statement stmt = conn.createStatement();

2. Use executeUpdate to execute the statement.int count = stmt.executeUpdate(SQLDMLstatement);

Example:Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("DELETE FROM order_items WHERE order_id = 2354");

2-15

Copyright Oracle Corporation, 2002. All rights reserved.

How to Update a Table in the Database The slide shows the syntax for the methods that execute a database update using a DML statement. executeUpdate() returns an int containing the row count, for an INSERT, UPDATE, or DELETEstatement.

Oracle9i: Access the Database with Java and JDBC 2-15

Submitting DDL Statements1. Create an empty statement object.Statement stmt = conn.createStatement();

2. Use executeUpdate to execute the statement.int count = stmt.executeUpdate(SQLDDLstatement);

Example:Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("CREATE TABLE temp (col1 NUMBER(5,2), col2 VARCHAR2(30)");

2-16

Copyright Oracle Corporation, 2002. All rights reserved.

How to Create DDL Statements The slide shows the syntax for the methods that execute a DDL statement. executeUpdate() returns an int containing 0, for a statement with no return value, such as a SQL DDL statement.

Oracle9i: Access the Database with Java and JDBC 2-16

Handling an Unknown SQL Statement1. Create an empty statement object.Statement stmt = conn.createStatement();

2. Use execute to execute the statement.boolean result = stmt.execute(SQLstatement);

3. Process the statement accordingly.if (result) { // was a query - process results ResultSet r = stmt.getResultSet(); ... } else { // was an update or DDL - process result int count = stmt.getUpdateCount(); ... }

2-17

Copyright Oracle Corporation, 2002. All rights reserved.

Dynamically Executing an Unknown SQL Statement An application may not know whether a given statement will return a result set until the statement has been executed. In addition, some stored procedures may return several different result sets and update counts. JDBC provides a mechanism so that an application can execute a statement and then process an arbitrary collection of result sets and update counts. The mechanism is based on the use of a general execute() method and then calls to three other methods: getResultSet, getUpdateCount, and getMoreResults. These methods enable an application to explore the statement results one at a time and to determine whether a given result is a result set or an update count. execute() returns true if the result of the statement is a result set; it returns false if the result of the statement is an update count. You can then call either getResultSet() or getUpdateCount() on the statement. The following example uses execute() to dynamically execute an unknown statement: public void executeStmt (String statement) throws SQLException{

Statement stmt = conn.createStatement();// Execute the statement boolean result = stmt.execute(statement); if (result) { // statement was a query Process the results ... } else { // statement was an update or DDL int updateCount = stmt.getUpdateCount(); // Process the results ... }Oracle9i: Access the Database with Java and JDBC 2-17

Handling Exceptions SQL statements can throw a java.sql.SQLException. Use standard Java error handling methods.try { rset = stmt.executeQuery("SELECT empno, ename FROM emp"); } catch (java.sql.SQLException e) { ... /* handle SQL errors */ }

... finally { // clean up try { if (rset != null) rset.close(); } catch (Exception e) { ... /* handle closing errors */ } ...

2-18

Copyright Oracle Corporation, 2002. All rights reserved.

Handling Exceptions You can use the try-catch-finally block structure for closing resources. Code Example

Connection conn = null; Statement stmt = null; ResultSet rset = null; // initialize stmt = conn.createStatement(); try { rset = stmt.executeQuery("SELECT empno, ename FROM emp"); catch (java.sql.SQLException e) { ... /* handle errors */ } ... // Clean up resources finally { try { if (rset != null) rset.close(); } catch (Exception e) {}try { if (stmt != null) stmt.close(); } catch (Exception e) {} try { if (conn != null) conn.close(); } catch (Exception e) {}}

}

Oracle9i: Access the Database with Java and JDBC 2-18

Managing Transactions By default connections are in auto commit mode Use conn.setAutoCommit(false) to turn autocommit off To control transactions when you are not in autocommit mode, use: conn.commit(): Commit a transaction conn.rollback(): Rollback a transaction

Closing a connection commits the transaction even with the autocommit off option

2-19

Copyright Oracle Corporation, 2002. All rights reserved.

Transactions with JDBC After you perform an UPDATE or INSERT operation in a result set, you propagate the changes to the database in a separate step that you can skip if you want to cancel the changes. With JDBC, database transactions are managed by the Connection object. When you create a Connection object, it is in autocommit mode, meaning that each statement is committed after it is executed. You can change the connections autocommit mode at any time by calling setAutoCommit(). The following is a full description of autocommit mode: If a connection is in autocommit mode, all of its SQL statements will be executed and committed as individual transactions. If a statement returns a result set, the statement finishes when the last row of the result set has been retrieved or the result set has been closed. If autocommit mode has been disabled, its SQL statements are grouped into transactions, which must be terminated by calling either commit() or rollback(). commit() makes permanent all changes since the previous commit or rollback and releases any database locks held by the connection. rollback()drops all changes since the previous commit or rollback and releases any database locks. commit()and rollback()should be called only when you are not in autocommit mode. Note: The server-side driver does not support autocommit mode. You must control transactions explicitly.Oracle9i: Access the Database with Java and JDBC 2-19

Summary

PATH and CLASSPATH variables determine which

components are used The steps for using SQL statements in Java are Register, Connect, Submit, and Close You can use three methods to execute SQL Statements depending on the nature of the statement SQL statements can throw exceptions Control default transactions behavior

2-20

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i: Access the Database with Java and JDBC 2-20

Practice 2 OverviewThis practice covers: Setting up the Java environment Writing and Running a simple Java application that access to a database

2-21

Copyright Oracle Corporation, 2002. All rights reserved.

Instructor Note In the following practices, the SQL statements need to be typed on a single line, or divided in smaller chunks concatenated together using the + sign. Otherwise there will be an error at compile time. There is a solution file that can be used for students that have problems writing the class. It is important that at the end of this lesson students have their own pictures table created, since it is required for practices in the following lessons.

Oracle9i: Access the Database with Java and JDBC 2-21

Practice 2-1 Goal The goal of this practice is to create a simple java class that provides access to the database and run it in the MS-DOS window. You will have to set up the environment variables to be able to compile and run a simple Java class that interacts with the Oracle database. During this practice you perform DDL, DML, and Query statements. Your assignment You create the Practice2 class. In this class, you specify the code to connect to the database, to query a single column from a table, and to disable the autocommit option. You then, create a new table and populate this table with some values. You commit the changes, display the values that were populated and insert again the same set of values. After displaying all the rows, you roll back your last changes and display the final result. Modify the PATH environment variable Open Notepad 1. Type in the CLASS variable: set PATH=\jdk\bin\; \bin\; \jdev\bin\;%PATH%; 2. Type in the CLASSPATH variable set CLASSPATH=. set CLASSPATH=%CLASSPATH%; \jdbc\lib\classes12.jar Save the file with the name E:\myjdbc.bat Setting up the environment Open an MS-DOS window Click Start on the TaskBar Select the Start MS/DOS option Run the myjdbc.bat file Move to the E:\labs directory Create the java class Open Notepad to enter the java code 3. Specify the packages to import import java.sql.*; import java.sql.SQLException.*; import oracle.jdbc.driver.*; 4. Specify the following statements public class Practice2{

public static void main (String args []) throws Exception{

} }

Oracle9i: Access the Database with Java and JDBC 2-22

Practice 2-1 (continued) 5. Register the Oracle JDBC driver // Register the Oracle JDBC driver DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); 6. Connect to the database using the connection, username, and password that your instructor provides you with. // Connect to the database // You can put a database name after the @ sign Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@hostname:1521:dbname", "username","password"); Edit and run your Java application Save the file in the E:\labs directory with the name Practice2.java, using File|Save menu option, but keep Notepad running, you will need it again. Compile the Practice2.javafile (filename capitalization is important) a. In the Dos window, ensure the current directory is E:\labs b. Check if the Java source file is saved to disk. c. Compile the file using command: javac Practice2.java d. What file is created if you successfully compile the code? File Practice2.class now exists Run the Practice2application. (again capitalization is important) a. Run the file using command: java Practice2 b. What is displayed in the DOS window? The DOS prompt displays with no message Create a query statement in the java class 7. Add a statement to disable the autocommit mode for the connection conn.setAutoCommit(false); 8. Create a statement object and add a SELECTstatement using the executeQuerymethod to query the region_idcolumn of the table regions. Statementstmt=conn.createStatement(); ResultSetrset=stmt.executeQuery ("SELECTregion_idFROMregions"); 9. Add a loop that displays each region_id using the getInt()method. while(rset.next()){

System.out.println(rset.getInt(1));}

rest.close(); Note: At this point you should be able to compile and run your .javafile

Oracle9i: Access the Database with Java and JDBC 2-23

Practice 2-1 (continued) Create a DDL statement in the java class 10. Drop the table PICTURES using the execute() method. Use the try catchblock structure to catch the exception when running the class the first time. try{

stmt.execute("DROPTABLEpictures");}

catch(SQLExceptione){

//Anexceptioncouldberaisedhereifthetable //didnotexistalready.}

11. Create a new table using the execute()method, with the following definition: CREATETABLEpictures(idnumber(8),name stmt.execute("CREATETABLEpictures(idNUMBER(8), nameVARCHAR2(20),pictureblobBLOB,picturebfile BFILE)"); Create a DML statement in the java class 12. Using the executeUpdate()method, populate the PICTUREStable with the region_id from the regionstable. System.out.println("TableInsert"); stmt.executeUpdate("INSERTINTOpictures(id) SELECTregion_idFROMregions"); 13. Add a SELECTstatement using the executeQuerymethod to query the IDcolumn of the table PICTURES. System.out.println("StartofTablequery"); ResultSetrseta=stmt.executeQuery ("SELECTidFROMpictures"); 14. Add a loop that displays each region_id using the getInt()method while(rseta.next()){

varchar2(20), pictureblob blob, picturebfile bfile)

System.out.println(rseta.getInt(1));}

rseta.close(); 15. CommittheINSERT //commitsetup conn.commit(); System.out.println("endofcommittedvalues");

Oracle9i: Access the Database with Java and JDBC 2-24

Practice 2-1 (continued) 16. Using the executeUpdate() method, populate a second time the PICTURES table with the region_id from the regionstable. //secondsetofinserts stmt.executeUpdate("INSERTINTOpictures(id) SELECTregion_idFROMregions"); System.out.println("committedanduncommitted values"); 17. Add a SELECTstatement using the executeQuerymethod to query the id column of the table PICTURES. ResultSetrsetb=stmt.executeQuery ("SELECTidFROMpictures"); 18. Add a loop that displays each region_id using the getInt()method. while(rsetb.next()){

System.out.println(rsetb.getInt(1));}

rsetb.close(); 19. Uncommitthechanges //uncommit conn.rollback(); 20. Add a SELECTstatement using the executeQuerymethod to query the IDcolumn of the table PICTURES. System.out.println("finalcommittedrows"); System.out.println("StartofTablequery"); ResultSetrsetc=stmt.executeQuery ("SELECTidFROMpictures"); 21. Add a loop that displays each region_id using the getInt()method while(rsetc.next()){

System.out.println(rsetc.getInt(1));}

rsetc.close(); Closing resources 22. Close the statement object stmt.close(); 23. Close the connection. conn.close(); Edit and run your Java Application Save the file, using File > Save menu option, but keep the Notepad running, in case compilation errors occur requiring you to edit the source to make corrections. Compile the Practice2.javafile (filename capitalization is important) Run the Practice2application. (again capitalization is important)Oracle9i: Access the Database with Java and JDBC 2-25

Practice 2-2 (if you have time) Changing methods 1. You can replace the use of executeQuery(), and executeUpdate() methods by the execute() method. 2. Test the Boolean value returned by the execute statement and display a message indicating the type of statement performed accordingly.

Oracle9i: Access the Database with Java and JDBC 2-26

More About JDBC

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 80 minutes 70 minutes 150 minutes

Topic Lecture Practice Total

ObjectivesAfter completing this lesson, you should be able to do the following: Define and describe the use of Oracle JDBC drivers Explore details about the ResultSet class and methods Map database types and Java types Handle Database NULL values Manage Oracle Large Objects and Objects type Obtain database metadata and result set metadata Execute dynamic SQL statement

3-2

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson covers in a more detailed way the different steps that were described in the previous lesson. You discover different types of drivers, and how to connect using each driver. You then, review the mapping between Oracle data types and Java types when performing a

query. You see how to work with large objects and other non relational objects stored in a database. Finally, you see how database metadata can be used to perform dynamic SQL.

Oracle9i: Access the Database with Java and JDBC 3-2

More on the Connect StageLoad/Register JDBC Driver Connect SQL statement SELECT statement Process results

Close

3-3

Copyright Oracle Corporation, 2002. All rights reserved.

More on the Connect Stage In the previous lesson, you have seen a basic example of how you can connect to the database. Other available techniques are described in this lesson.

Oracle9i: Access the Database with Java and JDBC 3-3

Connecting to the DatabaseUsing the package oracle.jdbc.driver, Oracle provides different drivers to establish a connection to the database.OracleDriver JDBC calls Thin client OCI Server Based Database commands Database

3-4

Copyright Oracle Corporation, 2002. All rights reserved.

About JDBC Drivers A JDBC driver implements the interfaces in the java.sql package, providing the code to connect to and query a specific database. A JDBC driver can also provide a vendors own extensions to the standard; Oracle drivers provide extensions to support special Oracle data types. Oracle provides three drivers: Thin client driver OCI-based driver Server-based driver The Oracle JDBC driver is located in the file classes111.zip for JDBC 1.0 or in the file classes12.zip for JDBC 2.0. These archive files contain supporting classes for both the thin and OCI JDBC drivers. Supported JDK and JDBC versions Oracle has two versions of the thin driver and the OCI driverone that is compatible with SDK 1.2 and one that is compatible with JDK 1.1.x. The J2SE versions support standard JDBC 2.0. The JDK 1.1.x versions support most JDBC 2.0 features, but must do so through Oracle extensions because JDBC 2.0 features are not available in JDK 1.1.x versions. Notes The server-side internal driver supports J2SE. JDK 1.0.2 is no longer supported in the current drivers.

Oracle9i: Access the Database with Java and JDBC 3-4

Oracle JDBC Drivers: Thin Client Driver Written entirely in Java Must be used by applets

Applet JDBC Thin driver Oracle 9i

Client

Server

3-5

Copyright Oracle Corporation, 2002. All rights reserved.

Thin Client Driver This driver can connect to an Oracle9i database but also to either an Oracle7 database or an Oracle8 database. You should use this driver if you are developing a client application that can connect to different versions of an Oracle database, to provide maximum portability. To communicate with the database, the thin client driver uses a lightweight version of SQL*Net or Net8 over TCP/IP that can be downloaded at run time to the client. The Oracle JDBC Thin driver is a 100% pure Java, Type IV driver. It is targeted for Oracle JDBC applets but can be used for applications as well. Because it is written entirely in Java, this driver is platform-independent. It does not require any additional Oracle software on the client side. The thin driver communicates with the server using Two Task Common (TTC), a protocol developed by Oracle to access the Oracle Relational Database management System (RDBMS). The JDBC Thin driver allows a direct connection to the database by providing an implementation of TCP/IP that emulates Oracle Net and TTC (the wire protocol used by OCI) on top of Java sockets. Both of these protocols are lightweight implementation versions of their counterparts on the server. The Oracle Net protocol runs over TCP/IP only. Note: When the JDBC Thin driver is used with an applet, the client browser must have the capability to support Java sockets.

Oracle9i: Access the Database with Java and JDBC 3-5

Oracle JDBC Drivers: OCI Client Drivers Written in C and Java Must be installed on the clientApplication JDBC OCI driver ocixxx.dll Client Oracle 9i

Server

3-6

Copyright Oracle Corporation, 2002. All rights reserved.

OCI Client Drivers You should choose an OCI driver if you are developing an application and need maximum performance. The JDBC OCI driver is a Type II driver for use with client-server Java applications. This driver requires an Oracle client installation, and therefore is Oracle platform-specific and not suitable for applets. The JDBC OCI driver provides OCI connection pooling functionality, which can either be part of the JDBC client or a JDBC stored procedure. The OCI driver supports Oracle7, Oracle8/8i, and Oracle9i with the highest compatibility. It also supports all installed Oracle Net adapters, including IPC, named pipes, TCP/IP, and IPX/SPX. The OCI driver, written in a combination of Java and C, converts JDBC invocations to calls to the Oracle Call Interface (OCI), using native methods to call C-entry points. These calls are then sent over Oracle Net to the Oracle database server. The OCI driver communicate with the server using the Oracle-developed TTC protocol. The OCI driver uses the OCI libraries, C-entry points, Oracle Net, CORE libraries, and

other necessary files on the client machine on which it is installed. Instructor Note In Oracle9i, the OCI driver is a single OCI driver for use with all database versions. It replaces the distinct OCI8 and OCI7 drivers of previous releases. While the OCI8 and OCI7 drivers are deprecated for Oracle9i, they are still supported for backward compatibility.

Oracle9i: Access the Database with Java and JDBC 3-6

Oracle JDBC Drivers: KPRB Server-Side Driver KPRB driver Runs inside the database Must be used by Java stored proceduresOracle9i Java EngineServer Side Thin Driver JDBC Server-side Internal driver

Stored procedure SQL engine

C library

3-7

Copyright Oracle Corporation, 2002. All rights reserved.

Server-Side Internal Driver The Oracle JDBC server-side internal driver is a type II driver. It supports any Java code that runs inside an Oracle database, such as in a Java stored procedure or Enterprise JavaBean, and must access the same database. This driver allows the Java virtual machine (JVM) to communicate directly with the SQL engine. The server-side internal driver, the JVM, the database, KPRB, C library, and the SQL engine all run within the same address space, so the issue of network round trips is irrelevant. The programs access the SQL engine by using function calls. The server-side internal driver is fully consistent with the client-side drivers and supports the same features and extensions. Note: The server-side internal driver supports only SDK 1.2.x., whereas in Oracle9i, release 2 it will support JDK 1.3.1 Instructor Note KPRB stands for Kernel PRogrammatic interface Bundled operations.

Oracle9i: Access the Database with Java and JDBC 3-7

Oracle JDBC Drivers: Thin Server-Side Driver Runs inside the database Used to access a remote databaseOracle9i Java Engine Server Side Thin Driver JDBC Server-side Internal driver C library Oracle 9i SQL engine

3-8

Copyright Oracle Corporation, 2002. All rights reserved.

JDBC Server-Side Thin Driver The Oracle JDBC server-side Thin driver offers the same functionality as the client-side Thin driver, but runs inside an Oracle database and accesses a remote database. This is especially useful in two situations: To access a remote Oracle server from an Oracle server acting as a middle tier More generally, to access one Oracle server from inside another, such as from any Java stored procedure or Enterprise JavaBean There is no difference in your code between using the Thin driver from a client application or from inside a server. About Permission for the Server-Side Thin driver The thin driver opens a socket to use for its connection. Because the Oracle server is enforcing the Java security model, this means that a check is performed for a SocketPermission object. To use the JDBC server-side Thin driver, the connecting user must be granted with the appropriate permission. This is an example of how the permission can be granted to a user. create role jdbcthin; call dbms_java.grant_permission(JDBCTHIN,java.net.SocketPermission, *, connect ); grant jdbcthin to user; Note that JDBCTHIN in the grant_permission call must be in upper case. The '*' is a pattern. It is possible to limit the permission to allow connecting to specific machines or ports.

Oracle9i: Access the Database with Java and JDBC 3-8

Other JDBC Drivers JDBC-ODBC bridge: Translates JDBC to open database connectivity (ODBC) calls Allows communication with existing ODBC drivers when no JDBC driver is available

Oracle Lite driver: For communication with an Oracle Lite database

3-9

Copyright Oracle Corporation, 2002. All rights reserved.

JDBC-ODBC Bridge The JDBC-ODBC bridge is a JDBC driver supplied by JavaSoft. It enables Java programs to use JDBC with existing ODBC drivers. JavaSoft no longer supports this driver now that pure Java drivers are available for all major databases. Open Database Connectivity (ODBC) is a standardized API for connecting to SQL databases. It was designed to enable development of database-independent applications. Oracle Lite driver The Oracle Lite driver is supplied with the Oracle Lite database. You must use this driver when connecting to an Oracle Lite database. The name of the JDBC driver to connect to Oracle9i Lite database is Driver Name: oracle.lite.poljdbc.POLJDBCDriver (OLite 4.0).

Oracle9i: Access the Database with Java and JDBC 3-9

Choosing the Right Driver

Type of Program Applet Client application EJB, servlet (on the middle tier) Thin

Driver Thin OCI Thin OCI Server side

Stored procedure

3-10

Copyright Oracle Corporation, 2002. All rights reserved.

Choosing the Appropriate Driver Consider the following when choosing a JDBC driver to use for your application or applet: If you are writing an applet, you must use the JDBC Thin driver. JDBC OCI-based driver classes will not work inside a Web browser, because they call native (C language) methods. If you want maximum portability and performance under Oracle9i and earlier, then use the JDBC Thin driver. You can connect to an Oracle server from either an application or an applet using the JDBC Thin driver. If you are writing a client application for an Oracle client environment and need maximum performance, then choose the JDBC OCI driver. For code that runs in an Oracle server acting as a middle tier, use the server-side Thin driver. If performance is critical to your application, you want maximum scalability of the Oracle server, or you need the enhanced availability features like Transparent Application Failover (TAF) or the enhanced proxy features like middle-tier authentication, then choose the OCI driver.

Oracle9i: Access the Database with Java and JDBC 3-10

About JDBC URLs JDBC uses a URL like string. The URL identifies The JDBC driver to use for the connection Database connection details, which varies depending on the driver used.

jdbc::Protocol Database Identification

jdbc:oracle::@ Example using Oracle Thin JDBC driver: jdbc:oracle:thin:@myhost:1521:ORCL

3-11

Copyright Oracle Corporation, 2002. All rights reserved.

JDBC URLs JDBC uses a URL to identify the database connection. A JDBC URL looks different from an HTTP or FTP URL, but like any URL it is a locator for a particular resource, in this case a database. The structure of a JDBC URL is flexible, allowing the driver writer to specify what to include in the URL. End users need to learn what structure their vendor uses. The slide shows the general syntax for a JDBC URL and the syntax that Oracle uses for connecting with an Oracle driver. The general syntax of a JDBC URL is as follows: jdbc:: jdbcis the protocol. All URLs start with their protocol. is the name of a driver or database connectivity mechanism. Driver developers register their subprotocols with JavaSoft to make sure that no one else uses the same subprotocol name. For all Oracle JDBC drivers, the subprotocol is oracle. identifies the database. The structure and contents of this string are determined by the driver developer. For Oracle JDBC drivers, the subname is :@, where: is the driver provides database connectivity information The following slides describe the syntax of an Oracle JDBC URL in for the different JDBC drivers for client-side Java application code.

Oracle9i: Access the Database with Java and JDBC 3-11

JDBC URLs with Oracle Drivers Oracle Thin driverSyntax: jdbc:oracle:thin:@:: Example: "jdbc:oracle:thin:@myhost:1521:orcl"

Oracle OCI driverSyntax: jdbc:oracle:oci:@ Example: "jdbc:oracle:oci:@ORCL"

3-12

Copyright Oracle Corporation, 2002. All rights reserved.

JDBC URLs with Oracle Drivers The basic structure of the JDBC URL for connecting to a database using one of the Oracle JDBC drivers is jdbc:::. Oracle Thin driver is thin. is a string of the form ::. That is, it is the host name, TCP/IP port, and Oracle SID of the database to which you want to connect. For example: jdbc:oracle:thin:@eduhost:1521:ORCL Oracle OCI driver is oci, oci8 or oci7, depending on which OCI driver you are using. is a TNSNAMES entry from the tnsnames.ora file. For example: jdbc:oracle:oci:@eduhost Bridge ODBC-JDBC driver Use the following syntax: jdbc:odbc: Note: For the thin and OCI drivers, can also use the SQL name-value pair syntax. For example: (DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST= )(PORT=)))(CONNECT_DATA=(SID=)) The server side driver is another type supported inside the Oracle database JVM implementation. This driver will be discussed in the context of Java stored procedure lesson.

Oracle9i: Access the Database with Java and JDBC 3-12

Stage 4: More on Processing Result for the SelectLoad/Register JDBC Driver Connect SQL statement SELECT statement Process results

Close

3-13

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i: Access the Database with Java and JDBC 3-13

How to Process the Results1. Step through the result set.while (rset.next()) { }

2. Use getXXX() to get each column value.String val = rset.getString(colname);

=

String val = rset.getString(colIndex);

while (rset.next()) { String ename = rset.getString("ENAME"); String empno = rset.getInt("EMPNO"); // Process or display the data }3-14 Copyright Oracle Corporation, 2002. All rights reserved.

Obtaining the Column Values Each of the getXXX() methods has two versions, allowing the programmer to specify the column by number or by name. Specifying columns by number: When column numbers are used as input for the getXXX() methods, the columns are numbered from 1. Specifying columns by name: When column names are used as input for the getXXX() methods, the column names are case insensitive. The column names option should be used when column names are used in the SQL query. For columns that were not explicitly named in the query, it is better to use column numbers. ResultSet provides a method called findColumn() that returns the column number for a given column name. getString The example on the slide uses getString() to return the column values. getString() can be used to retrieve any of the basic SQL data types. It is the easiest method to use for visual applications, when you want to display or print the data. It can also be used when the end user will update the data, which you then convert to a SQL UPDATE statement. getBigDecimal All of the getXXX() methods require a single parameter, except for getBigDecimal(colname, scale) and getBigDecimal(colindex, scale), both of which require a second parameter for the number of digits to the right of the decimal point. Other getXXX() methods are covered in more detail later in this lesson.

Oracle9i: Access the Database with Java and JDBC 3-14

Mapping Database Types to Java TypesResultSet maps database types to Java types.ResultSet rset = stmt.executeQuery ("SELECT empno, hiredate, job FROM emp"); while (rset.next()){ int id = rset.getInt(1); Date hiredate = rset.getDate(2); String job = rset.getString(3); Col Name empno hiredate job TypeNUMBER

Method getInt() getDate() getString()

DATE VARCHAR2

3-15

Copyright Oracle Corporation, 2002. All rights reserved.

Mapping Database Types to Java Types In many cases, you can get all of the columns in your result set using the getObject() or getString() methods of ResultSet. For performance reasons, or because you want to perform complex calculations, it is sometimes important to have your data in a type that exactly matches the database column. The JDBC section of the Java tutorial contains a matrix that maps ResultSet.getXXX methods to ANSI SQL types. For each SQL type, the matrix shows: Which getXXX methods can be used to retrieve the SQL type Which getXXX method is recommended to retrieve the SQL type The Java tutorial is available online at http://java.sun.com/docs/books/tutorial/index.html. It is also published in two books; the JDBC section is in The Java Tutorial Continued.

Oracle9i: Access the Database with Java and JDBC 3-15

Table of ANSI SQL types and Java types The following table lists the ANSI SQL types, the corresponding data type to use in Java, and the name of the method to call in ResultSet to obtain that type of column value.ANSI SQL Type CHAR, VARCHAR2 LONGVARCHAR NUMERIC,DECIMAL BIT TINYINT SMALLINT INTEGER BIGINT REAL DOUBLE,FLOAT BINARY,VARBINARY LONGVARBINARY DATE TIME TIMESTAMP Java Type java.lang.String java.io.InputStream java.math.BigDecimal boolean byte short int long float double byte[] java.io.InputStream java.sql.Date java.sql.Time java.sql.Timestamp ResultSet Method getString() getAsciiStream() getBigDecimal() getBoolean() getByte() getShort() getInt() getLong() getFloat() getDouble() getBytes() getBinaryStream() getDate() getTime() getTimestamp()

Table of Oracle SQL typesORACLE SQL TypeNUMBER CHAR RAW DATE ROWID BLOB CLOB BFILE Structured object Object reference Collection(array)

Oracle Type Oracle.Types.NUMBER Oracle.Types.CHAR Oracle.Types.RAW Oracle.Types.DATE Oracle.Types.ROWID Oracle.Types.BLOB Oracle.Types.CLOB n/a Oracle.Types.STRUCT Oracle.Types.REF Oracle.Types.ARRAY

Type Extensionoracle.sql.NUMBER oracle.sql.CHAR oracle.sql.RAW oracle.sql.DATE oracle.sql.ROWID oracle.sql.BLOB oracle.sql.CLOB oracle.sql.BFILE oracle.sql.STRUCT oracle.sql.REF oracle.sql.ARRAY

Oracle9i: Access the Database with Java and JDBC 3-16

How to Handle SQL Null Values Java primitive types cannot have null values. Do not use a primitive type when your query might return a SQL null value. Use ResultSet.wasNull() to determine whether a column has a null value.while (rset.next()) { int empno = rset.getInt("empno"); if (rset.wasNull()) { // Handle null value } }

3-17

Copyright Oracle Corporation, 2002. All rights reserved.

Handling SQL Null Values If your query could return a SQL null value, you should use a getXXX() method that returns an object type, not one that returns a Java primitive. The example in the slide shows how to use ResultSet.wasNull() to determine whether a column has a null value. Note that you must call getXXX() to read the columns value before you can determine whether it has a null value.

Oracle9i: Access the Database with Java and JDBC 3-17

Advanced Data Types Oracle JDBC drivers support object data. oracle.sql (classes to support all Oracle type extensions) oracle.jdbc (interfaces to support database access and updates in Oracle type formats)

JDK 1.1 has problems supporting object data: Use oracle.jdbc2 package with JDK 1.1.

The SDK 1.2 package java.sql supports object data: The oracle.jdbc2 package is not included. Upgrading can require updating and recompiling of code.3-18 Copyright Oracle Corporation, 2002. All rights reserved.

Advanced Data Types Oracle provides two implementations of its JDBC driversone that supports Sun Microsystems JDK 1.2.x and complies with the Sun JDBC 2.0 standard, and another that supports JDK 1.1.x and complies with the Sun JDBC 1.22 standard. Beyond standard features, Oracle JDBC drivers provide Oracle-specific type extensions and performance extensions. Both implementations include the following Java packages: oracle.sql (classes to support all Oracle type extensions) oracle.jdbc (interfaces to support database access and updates in Oracle type formats) In addition to these packages, the implementation for JDK 1.1.x includes the following Java package. This package supports some JDBC 2.0 features by providing interfaces that mimic the JDBC 2.0 interfaces in the standard java.sql package: oracle.jdbc2 (interfaces equivalent to standard JDBC 2.0 interfaces) If you use the oracle.jdbc2 package then upgrading requires updating and recompiling of code. To avoid this, you can use the classes supplied in oracle.sql instead.

Oracle9i: Access the Database with Java and JDBC 3-18

Working with Large Objects Oracle provides corresponding Getter and Setter methods to manipulate BLOBs and CLOBs Data access is performed through a locator Getting the LOB locator:ResultSet rs = stmt.executeQuery ("SELECT blob_col, clob_col FROM lob_table"); while (rs.next()) { // Get LOB locators into Java wrapper classes. BLOB myBlob = ((OracleResultSet)rs).getBLOB(1); CLOB myClob = ((OracleResultSet)rs).getCLOB(2); (... process...)

3-19

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle Extensions for LOBs and BFILEs LOBs (large objects) are stored in a way that optimizes space and provides efficient access. The JDBC drivers provide support for two types of LOBs: BLOBs (unstructured binary data) and CLOBs (character data). BLOB and CLOB data is accessed and referenced by using a locator, which is stored in the database table and points to the BLOB or CLOB data, which is outside the table. To work with LOB data, you must first obtain a LOB locator. Then you can read or write LOB data and perform data manipulation. The JDBC drivers support these oracle.sql.* classes for BLOBs, CLOBs, and BFILEs: oracle.sql.BLOB oracle.sql.CLOB The oracle.sql.BLOB and CLOB classes implement the java.sql.Blob and Clob interfaces, respectively (oracle.jdbc2.Blob and Clob interfaces under JDK 1.1.x). Note: All kind of examples of working code using large objects are available in the /jdbc/demo/directory. (There are examples for BLOB, CLOB, and so on.)

Oracle9i: Access the Database with Java and JDBC 3-19

Reading BLOBsUse getBinaryStream() method to read BLOB data from the BLOB locator.// Read BLOB data from BLOB locator. InputStream byte_stream = myBlob.getBinaryStream(); byte [] byte_array = new