BEA WebLogic - · PDF fileTransaction boundaries ... Your feedback on the BEA WebLogic...

78
BEA WebLogic Installing and Using Document 1.0 April, 2000 WebLogic jDriver for Oracle

Transcript of BEA WebLogic - · PDF fileTransaction boundaries ... Your feedback on the BEA WebLogic...

BEA WebLogicInstalling and Using

D o c u m e n t 1 . 0A p r i l , 2 0 0 0

WebLogic jDriver for Oracle

Copyright

Copyright © 2000 BEA Systems, Inc. All Rights Reserved.

Restricted Rights Legend

This software and documentation is subject to and made available only pursuant to the terms of the BEA SystemsLicense Agreement and may be used or copied only in accordance with the terms of that agreement. It is againstthe law to copy the software except as specifically allowed in the agreement. This document may not, in whole orin part, be copied photocopied, reproduced, translated, or reduced to any electronic medium or machine readableform without prior consent, in writing, from BEA Systems, Inc.

Use, duplication or disclosure by the U.S. Government is subject to restrictions set forth in the BEA SystemsLicense Agreement and in subparagraph (c)(1) of the Commercial Computer Software-Restricted Rights Clauseat FAR 52.227-19; subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause atDFARS 252.227-7013, subparagraph (d) of the Commercial Computer Software--Licensing clause at NASA FARsupplement 16-52.227-86; or their equivalent.

Information in this document is subject to change without notice and does not represent a commitment on the partof BEA Systems. THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUTWARRANTY OF ANY KIND INCLUDING WITHOUT LIMITATION, ANY WARRANTY OFMERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. FURTHER, BEA Systems DOESNOT WARRANT, GUARANTEE, OR MAKE ANY REPRESENTATIONS REGARDING THE USE, OR THERESULTS OF THE USE, OF THE SOFTWARE OR WRITTEN MATERIAL IN TERMS OF CORRECTNESS,ACCURACY, RELIABILITY, OR OTHERWISE.

Trademarks or Service Marks

BEA, WebLogic, jDriver, ObjectBroker, TOP END, and TUXEDO are registered trademarks of BEA Systems,Inc. BEA Builder, BEA Connect, BEA Manager, BEA MessageQ, Jolt and M3 are trademarks of BEA Systems,Inc.

All other company names may be trademarks of the respective companies with which they are associated.

Installing and using jDriver for Oracle

Document Edition Part Number Date Software Version

1.0 April 2000 WebLogic jDriver for Oracle 5.1

Contents

About This DocumentWhat You Need to Know ......................................................................................1

e-docs Web Site.....................................................................................................1

How to Print the Document...................................................................................2

Related Information...............................................................................................2

Contact Us!............................................................................................................2

Documentation Conventions .................................................................................3

1. Installing WebLogic jDriver for OracleOverview ...............................................................................................................7

Important issues for release 5.1.............................................................................8

Other JDBC drivers...............................................................................................8

Installation steps....................................................................................................9

Editing an entry to the XML license file......................................................11

Setting your path and client libraries..................................................................12

JDBC 2.0......................................................................................................13

Platform considerations................................................................................13

Directory to put in your system PATH ........................................................13

Windows NT.........................................................................................13

Solaris ...................................................................................................14

IBM AIX...............................................................................................15

HP-UX 11 ............................................................................................15

SGI IRIX...............................................................................................16

Siemens MIPS.......................................................................................16

Compaq Tru64 UNIX ...........................................................................16

Note for Microsoft SDK for Java (Jview) users..................................................17

Checking connections to the Oracle database .....................................................17

Installing and Using WebLogic jDriver for Oracle v

Setting up a connection pool ........................................................................18

Configuring a connection pool with WebLogic Server ........................18

Using the connection pool in your application .....................................19

Using IDEs or debuggers with WebLogic jDrivers ............................................20

Next step..............................................................................................................20

2. Using WebLogic jDriver for OracleIntroduction .........................................................................................................21

What’s in this document...............................................................................21

Overview of BEA jDrivers...........................................................................22

Software requirements..................................................................................22

Installation....................................................................................................22

Implementing with WebLogic jDriver for Oracle...............................................23

Importing packages ......................................................................................23

Setting CLASSPATH ...........................................................................23

Oracle client library versions, URLs, and Driver class names.....................25

JDBC 1.x...............................................................................................25

JDBC 2.0...............................................................................................25

Connecting to an Oracle DBMS...................................................................25

Connection example..............................................................................27

Connecting using a DataSource object .................................................27

Setting properties for WebLogic JDBC use..........................................27

About the Connection object.................................................................27

Setting Autocommit ..............................................................................28

Making a simple SQL query ........................................................................28

Inserting, updating, and deleting records .....................................................29

Creating and using stored procedures and functions....................................30

Disconnecting and closing objects ...............................................................33

Code example...............................................................................................34

Working with ResultSets from stored procedures........................................37

Support for JDBC Extended SQL ................................................................38

Additional Oracle features...................................................................................39

Allowing mixed case metadata ....................................................................39

Data types .....................................................................................................40

WebLogic jDriver for Oracle and Oracle's NUMBER column ............41

vi Installing and Using WebLogic jDriver for Oracle

Using Oracle Long raw data types........................................................42

Waiting on Oracle resources ........................................................................42

Autocommit .................................................................................................43

Transaction isolation levels..........................................................................43

Codeset support............................................................................................44

Support for Oracle array fetches ..................................................................47

Using stored procedures...............................................................................48

Binding a parameter to an Oracle cursor ..............................................48

Notes on using CallableStatement ........................................................50

Notes on DatabaseMetaData methods .........................................................50

JDBC 2.0 for Oracle............................................................................................51

Overview......................................................................................................51

Configuration ...............................................................................................51

Driver class ...........................................................................................52

Driver URL ...........................................................................................52

Overview of BLOBs and CLOBs ................................................................52

Transaction boundaries .........................................................................52

BLOBs .........................................................................................................53

Connection properties ...........................................................................53

Import statements..................................................................................54

Initializing a BLOB field ......................................................................54

Writing binary data to a BLOB.............................................................55

Writing a BLOB object.........................................................................55

Reading BLOB data..............................................................................56

Other methods.......................................................................................57

CLOBs .........................................................................................................57

Codeset support.....................................................................................57

Initializing a CLOB field ......................................................................58

Writing ASCII data to a CLOB ............................................................59

Writing Unicode data to a CLOB .........................................................60

Writing CLOB objects ..........................................................................60

Reading CLOB data..............................................................................61

Other methods.......................................................................................61

Character and ASCII Streams ......................................................................62

Unicode character Streams ...................................................................62

Installing and Using WebLogic jDriver for Oracle vii

ASCII character streams .......................................................................62

Batch updates ...............................................................................................63

Using Batch updates..............................................................................63

Clearing the batch .................................................................................64

Update counts........................................................................................64

Using with JDBC 1 ...............................................................................64

New date methods ........................................................................................65

Resources.............................................................................................................66

Code Examples.............................................................................................66

3. Release Notes for WebLogic jDriver for OracleUpgrade ...............................................................................................................67

Changes ...............................................................................................................67

Issues ...................................................................................................................68

viii Installing and Using WebLogic jDriver for Oracle

PREFACE

About This Document

This document describes how to install and develop applications using jDriver forOracle, BEA’s type-2 Java Database Connectivity (JDBC) driver for the OracleDatabase management system.

This document covers the following topics:

� Chapter 1, “Installing WebLogic jDriver for Oracle”

� Chapter 2, “Using WebLogic jDriver for Oracle”

� Chapter 3, “Release Notes for WebLogic jDriver for Oracle”

What You Need to Know

This document is intended mainly for application developers who are interested inbuilding applications requiring database access. It assumes a familiarity with SQL,general database concepts, and Java programming.

e-docs Web Site

BEA product documentation is available on the BEA corporate Web site. From theBEA Home page, click on Product Documentation or go directly to the “e-docs”Product Documentation page at http://e-docs.beasys.com.

Installing and Using WebLogic jDriver for Oracle 1

How to Print the Document

You can print a copy of this document from Adobe Acrobat by using the File—>Printoption.

If you do not have the Adobe Acrobat Reader, you can download it for free from theAdobe Web site at http://www.adobe.com/.

Related Information

The most up-to-date version of this document, Installing and Using WebLogic jDriverfor Oracle, is also available in HTML format on the BEA e-docs website. To accessthe online HTML version on the BEA web site, use the following links:

Installing WebLogic jDriver for Oracle:http://www.weblogic.com/docs51/install/install_jdbc.html

Using WebLogic jDriver for Oracle:http://www.weblogic.com/docs51/classdocs/API_joci.html

You can view or print the PDF versions of these documents using Adobe Acrobat,version 3.0 or higher.

Complete documentation for WebLogic Server is available online athttp://www.weblogic.com/docs51/resources.html.

Contact Us!

Your feedback on the BEA WebLogic Enterprise documentation is important to us.Send us e-mail at [email protected] if you have questions or comments. Yourcomments will be reviewed directly by the BEA professionals who create and updatethe jDriver for Oracle documentation.

2 Installing and Using WebLogic jDriver for Oracle

Documentation Conventions

In your e-mail message, please indicate that you are using the documentation for theBEA jDriver for Oracle.

If you have any questions about this version of BEA jDriver for Oracle, or if you haveproblems installing and running BEA jDriver for Oracle, contact BEA CustomerSupport through BEA WebSupport at www.beasys.com. You can also contactCustomer Support by using the contact information provided on the Customer SupportCard, which is included in the product package.

When contacting Customer Support, be prepared to provide the following information:

� Your name, e-mail address, phone number, and fax number

� Your company name and company address

� Your machine type and authorization codes

� The name and version of the product you are using

� A description of the problem and the content of pertinent error messages

Documentation Conventions

The following documentation conventions are used throughout this document.

Convention Item

boldface text Indicates terms defined in the glossary.

Ctrl+Tab Indicates that you must press two or more keys simultaneously.

italics Indicates emphasis or book titles.

Installing and Using WebLogic jDriver for Oracle 3

monospacetext

Indicates code samples, commands and their options, data structures andtheir members, data types, directories, and file names and their extensions.Monospace text also indicates text that you must enter from the keyboard.

Examples:

#include <iostream.h> void main ( ) the pointer psz

chmod u+w *

\tux\data\ap

.doc

tux.doc

BITMAP

float

monospaceboldfacetext

Identifies significant words in code.

Example:

void commit ( )

monospaceitalictext

Identifies variables in code.

Example:

String expr

UPPERCASETEXT

Indicates device names, environment variables, and logical operators.

Examples:

LPT1

SIGNON

OR

{ } Indicates a set of choices in a syntax line. The braces themselves shouldnever be typed.

[ ] Indicates optional items in a syntax line. The brackets themselves shouldnever be typed.

Example:

buildobjclient [-v] [-o name ] [-f file-list]...[-l file-list]...

| Separates mutually exclusive choices in a syntax line. The symbol itselfshould never be typed.

Convention Item

4 Installing and Using WebLogic jDriver for Oracle

Documentation Conventions

... Indicates one of the following in a command line:

� That an argument can be repeated several times in a command line

� That the statement omits additional optional arguments

� That you can enter additional parameters, values, or other information

The ellipsis itself should never be typed.

Example:

buildobjclient [-v] [-o name ] [-f file-list]...[-l file-list]...

.

.

.

Indicates the omission of items from a code example or from a syntax line.The vertical ellipsis itself should never be typed.

Convention Item

Installing and Using WebLogic jDriver for Oracle 5

6 Installing and Using WebLogic jDriver for Oracle

CHAPTER

1 Installing WebLogic jDriver for Oracle

Overview

WebLogic jDriver for Oracle is a new name for the product formerly known asjdbcKona/Oracle.

WebLogic jDriver for Oracle, a Type-2 JDBC driver for the Oracle DBMS is includedwith WebLogic Server. For this driver to function, you must have a complete Oracleclient installed on the machine that will be the client to the Oracle DBMS. This Oracleclient installation contains vendor-supplied client libraries and associated files thatWebLogic jDriver for Oracle requires to operate.

The WebLogic Server distribution includes a choice of several BEA-supplied nativelibraries for WebLogic jDriver for Oracle. The library that you choose depends onwhich Oracle client version you have installed on your client machine and whichversion of the Oracle API you will use to access your Oracle server. Installing thisdriver requires that both the BEA-supplied native library and the Oracle-suppliedclient libraries be available by including them in your the client’s PATH (Windows NT)or shared library path (UNIX), as described below.

For information on using WebLogic jDriver for Oracle see Using WebLogic jDriverfor Oracle (at http://www.weblogic.com/docs51/classdocs/API_joci.html).

Installing and Using WebLogic jDriver for Oracle 7

1 Installing WebLogic jDriver for Oracle

Important issues for release 5.1

Please read the Release notes for details on the issues highlighted below.

Oracle Release Notes are also available on line athttp://www.weblogic.com/docs51/classdocs/release_notes_joci.html.

Platform Support:

Check the Release Notes or the WebLogic Platform Support page (athttp://www.weblogic.com/docs51/platforms/index.html) in the onlinedocumentation for details about which platforms, operating systems, DBMSversions, and Java versions are supported for WebLogic jDriver for Oracle.

Important issues include:

� WebLogic jDriver for Oracle is not supported when using the Oracle 8 API andconnecting to an version 7 Oracle DBMS.

� Using CallableStatement.getResultSet()

� Mixing different versions of the Oracle Client and Oracle Server

� Codeset conversion with CLOBs when using a different operating system on theclient and server.

Other JDBC drivers

BEA also has Type-4 JDBC drivers available for the Informix and Microsoft SQLServer DBMSs. These are pure-Java drivers and do not require vendor-supplied clientlibraries.

For more information on these drivers, please see: WebLogic JDBC Options, athttp://www.weblogic.com/docs51/classdocs/jdbcdrivers.html.

8 Installing and Using WebLogic jDriver for Oracle

Installation steps

Installation steps

1. Select the appropriate native library for your environment.

WebLogic jDriver for Oracle is shipped with dll, sl, or so files for variouscombinations of Oracle client versions, APIs, and platforms. You must place theappropriate file in your system’s path or shared library path for this driver tofunction. Unlike previous releases of WebLogic jDriver for Oracle, which hadonly one such file that was always present in the default path, you now mustspecify this path setting explicitly. For details and instructions on setting theseoptions, see Setting your path and client libraries on page 12.

2. Add the client libraries from your Oracle installation to your system PATH(Windows NT) or load library path (UNIX—the name of this variable differsamong UNIX systems). Check your Oracle documentation for the location ofthese libraries. On Windows NT the client libraries are usually located inc:\ORANT\bin.

3. Unpack the distribution.

If you have purchased WebLogic Server, WebLogic jDriver for Oracle isincluded with your distribution. No further steps are required to unpack thedistribution. The remainder of these installation steps are required only for usersof the stand-alone version of WebLogic jDriver for Oracle.

If you haven’t already, unpack the archive you downloaded in the root directoryof your computer. You must use a program such as WinZip athttp://www.winzip.com that preserves the directory structure of the archive. Thefiles unpack into the weblogic directory.

The instructions in this document assume that you are installing WebLogicjDriver for Oracle on a Windows computer and that you unpacked the archive inthe root directory of your C drive. If you’re installing on a different operatingsystem or in a different location, check your system documentation for help inadjusting the commands shown in these instructions for your own environment.

4. Add the WebLogic jDriver for Oracle classes directory to your CLASSPATHvariable.

Note: If you are using the WebLogic jDriver for Oracle that is bundled withWebLogic Server, the classpath setting are the same as those required for

Installing and Using WebLogic jDriver for Oracle 9

1 Installing WebLogic jDriver for Oracle

WebLogic Server. The standard start up scripts supplied with the WebLogicServer distribution will do this for you.

To change your CLASSPATH temporarily at a Windows Command Prompt, usethis command:

$ set CLASSPATH=%CLASSPATH%;c:\weblogic\informix4\classes

To change your CLASSPATH permanently:

a. Double-click the System icon in the Control Panel.

b. Click the Environment tab.

c. In the lower panel, select the CLASSPATH variable. If no CLASSPATHvariable is defined, add it.

d. Add c:\weblogic\informix4\classes to the value of the CLASSPATHvariable. Use a semicolon (;) to separate the new path from the previous valueof the variable, if any.

Any program you launch after you update the CLASSPATH variable in theSystem control panel will have access to the new value.

For more help setting your CLASSPATH, read Setting classpath athttp://www.weblogic.com/docs51/admindocs/classpath.html. If you’re usingWebLogic jDriver for Oracle from within an IDE like Symantec Cafe orJBuilder, the procedure for adding classes to the CLASSPATH may be different.

5. Install WebLogic jDriver for Oracle for use with browser applets.

If you’re planning to use WebLogic jDriver for Oracle to access databases viaapplets in a web browser, you must install the distribution on the computerexecuting the web server. Furthermore, the web server and the Informix databaseserver must be running on the same computer. This is a security restrictionenforced by most web browsers, including Netscape Navigator and InternetExplorer. For information about browser security and applets, readTroubleshooting Applet Security problems athttp://www.weblogic.com/docs51/techsupport/appletsecurity.html.

The web server must also be able to find the WebLogic jDriver for Oracle classfiles. To ensure that the web server can find the files, install the WebLogicjDriver for Oracle distribution on your web server computer and then set theCLASSPATH on that computer as described in step 4. Be sure to restart the webserver after you change the CLASSPATH so that the web server has access tothe revised CLASSPATH value.

10 Installing and Using WebLogic jDriver for Oracle

Installation steps

6. Install a license file.

With the release of version 5.1 of WebLogic jDriver for Oracle, a new type oflicense is shipped with the distribution. This license uses an XML file to storethe license keys.

There are several issues to consider regarding your license for WebLogic jDriverfor Oracle:

� If you downloaded an evaluation version of the driver, your distributionincludes an evaluation license. Your driver is ready for evaluation use.

� If you have previously purchased a license for WebLogic jDriver for Oracle,you must obtain an updated license file from your BEA contact person andplace that license in your WebLogic jDriver for Oracle installation.

Copy your license key into your WebLogicLicense.xml, file. This file islocated at weblogic/informix4/license/WebLogicLicense.xml (whereweblogic is the directory containing your WebLogic jDriver for Oracleinstallation). For instructions on editing a WebLogic XML license file, seeEditing an entry to the XML license file, below.

To purchase a permanent license for WebLogic jDriver for Oracle, [email protected].

Editing an entry to the XML license file

1. Open the message containing the key(s) you received by email when youpurchased a license from BEA Systems, Inc.

2. Open the WebLogicLicense.xml file in a text editor. This file is located in oneof the following directories:

� standalone driver: weblogic/informix4/license

� using the driver with WebLogic Server: weblogic/license

(Where weblogic is the directory containing your WebLogic jDriver for Oracleor WebLogic Server installation.)

Do not edit this file in Microsoft Word or any other word-processing programthat will save the file as a binary.

3. Copy the keys from the email and paste them at the top of the XML file.

Installing and Using WebLogic jDriver for Oracle 11

1 Installing WebLogic jDriver for Oracle

For example, if you have received a key, it'll look something like this:

<LICENSE PRODUCT="jdbcKona/Informix4"IP="000.000.900.900"UNITS="5"EXPIRATION="31-Mar-1999"KEY="w20f8s08480v0adpup43245paprtnp8ac"

/>

4. Save the WebLogicLicense.xml file into the same directory.

5. Save your license key information and a copy of your WebLogicLicense.xmlfile in a safe place outside the WebLogic distribution, preferably someplace youwill remember. Although no one else will be able to use your license keys, youshould probably save this information in a place protected from either maliciousor innocent tampering by others. Please note that when you upgrade yourWebLogic classes, you will want to keep your original WebLogicLicense.xmland add new keys to it for any new services you purchase.

Setting your path and client libraries

A native dll, so, or sl file containing your driver must be made available to yourWebLogic jDriver for Oracle client by including its directory in your system PATH

(Windows NT), LD_LIBRARY_PATH (most Unix systems), or SHLIB_PATH (HP-UX).The directory containing the correct file varies depending on several factors discussedbelow.

The vendor-supplied libraries from Oracle must also be included in your PATH, load

library path, or shared library path. The location of the directory containingyour Oracle client libraries will vary depending on your installation. On Windows NT,these libraries are normally placed into your machine’s path by the Oracle installer.

Version 5.1 of WebLogic jDriver for Oracle now uses the dll, so, or sl files built withthe Oracle 8 API as the native interface for accessing an Oracle DBMS. This APIallows for improved connectivity to a version 7 or version 8 Oracle Server and alsoprovides access to new features available only in Oracle 8 (some of these featuresrequire JDBC 2.0, which requires a Java 2 JVM).

An older version of these dll, so, or sl files that uses the Oracle 7 API, is alsoincluded with this release to assure backwards compatibility.

12 Installing and Using WebLogic jDriver for Oracle

Setting your path and client libraries

The tables below, under Directory to put in your system PATH, list the Oracle clientversion, the Oracle API version and the directory you must put in your system PATHto access that version of the driver.

JDBC 2.0

JDBC 2.0 features are only available when using a driver that uses the Oracle 8 API.You must also run your WebLogic jDriver for Oracle client under a Java 2 compatibleJDK. Using JDBC 2.0 also requires using a different driver class and URL in your Javacode. For more information, see JDBC 2.0 for Oracle in the document UsingWebLogic jDriver for Oracle athttp://www.weblogic.com/docs51/classdocs/API_joci.html#jdbc20.

Platform considerations

For information on supported platforms and JVM versions for WebLogic jDriver forOracle, see the WebLogic platform support page athttp://www.weblogic.com/docs51/platforms/index.html#jdbc.

The minimum supported client library is Oracle version 7.3.4.

Directory to put in your system PATH

Windows NT

Add weblogic\bin and the appropriate directory from the table below to your PATH,for example:

$ set PATH=%PATH%;c:\weblogic\bin\oci805_8

Where c:\weblogic is the home directory of your WebLogic Server or WebLogicjDriver for Oracle installation.

Installing and Using WebLogic jDriver for Oracle 13

1 Installing WebLogic jDriver for Oracle

Directory to put in your PATH

Solaris

Add weblogic/lib/solaris and the appropriate directory from the table below toyour ld library path. (Where weblogic is the home directory of your WebLogicServer or WebLogic jDriver for Oracle installation)

Directory to put in your ld_library_path

OracleClientversion

Oracle APIversion

Directory Notes

7.3.4 7 oci734_7 Provided for backwards com-

patibility. No Oracle 8 or

JDBC 2.0 features.

8.0.5 7 oci805_7 Provided for backwards com-

patibility. No Oracle 8 or

JDBC 2.0 features.

8.0.5 8 oci805_8 Allows access to Oracle 8 and

JDBC 2.0 features.

8.1.5 8 oci815_8 Allows access to Oracle 8 and

JDBC 2.0 features.

OracleClientversion

Oracle APIversion

Directory Notes

7.3.4 7 oci734_7 Provided for backwards com-

patibility. No Oracle 8 or

JDBC 2.0 features.

8.0.5 7 oci805_7 Provided for backwards com-

patibility. No Oracle 8 or

JDBC 2.0 features.

8.0.5 8 oci805_8 Allows access to Oracle 8 and

JDBC 2.0 features.

8.0.6 8 oci806_8 Allows access to Oracle 8 and

JDBC 2.0 features.

14 Installing and Using WebLogic jDriver for Oracle

Setting your path and client libraries

You must also include the path to your vendor-supplied client libraries from Oracle inyour ld_library_path. The location of these libraries will depend on your Oracleclient installation.

IBM AIX

WebLogic jDriver for Oracle for IBM AIX is available only for the Oracle 7 API. Fora list of supported client versions, see Platform support for JDBC drivers athttp://www.weblogic.com/docs51/platforms/index.html#jdbc.

Add the directory weblogic/lib/aix to your LIBPATH.

Where weblogic is the home directory of your WebLogic Server or WebLogic jDriverfor Oracle installation.

HP-UX 11

Add weblogic/lib/hpux11 and the appropriate directory from the table below toyour SHLIB_PATH. (Where weblogic is the home directory of your WebLogic Serveror WebLogic jDriver for Oracle installation)

8.1.5 8 oci815_8 Allows access to Oracle 8 and

JDBC 2.0 features.

OracleClientversion

Oracle APIversion

Directory Notes

8.0.4 7 oci804_7 Provided for backwards com-

patibility. No Oracle 8 or

JDBC 2.0 features.

8.0.5 8 oci805_8 Allows access to Oracle 8 and

JDBC 2.0 features.

8.1.5 8 OCI815_8 Allows access to Oracle 8 and

JDBC 2.0 features.

Installing and Using WebLogic jDriver for Oracle 15

1 Installing WebLogic jDriver for Oracle

SGI IRIX

WebLogic jDriver for Oracle for SGI IRIX is available only for the Oracle 7 API. Fora list of supported client versions, see Platform support for JDBC drivers athttp://www.weblogic.com/docs51/platforms/index.html#jdbc.

� Irix users must run Java in N32 mode.

� You must have the Oracle 8.0.5 N32 client installed on your computer.

Add the directory weblogic/lib/irixsh to your LD_LIBRARYN32_PATH.

Where weblogic is the home directory of your WebLogic Server or WebLogic jDriverfor Oracle installation.

Siemens MIPS

WebLogic jDriver for Oracle for Siemens MIPS is available only for the Oracle 7 API.For a list of supported client versions, see Platform support for JDBC drivers athttp://www.weblogic.com/docs51/platforms/index.html#jdbc.

Add the directory weblogic/lib/reliantunix to your LD_LIBRARY_PATH.

Where weblogic is the home directory of your WebLogic Server or WebLogic jDriverfor Oracle installation.

Compaq Tru64 UNIX

WebLogic jDriver for Oracle for Compaq Tru64 UNIX is available only for the Oracle7 API. For a list of supported client versions, see Platform support for JDBC drivers athttp://www.weblogic.com/docs51/platforms/index.html#jdbc.

Add the directory weblogic/lib/tru64unix to your LD_LIBRARY_PATH.

Where weblogic is the home directory of your WebLogic Server or WebLogic jDriverfor Oracle installation.

16 Installing and Using WebLogic jDriver for Oracle

Note for Microsoft SDK for Java (Jview) users

Note for Microsoft SDK for Java (Jview) users

� Version 5.00, build 3186 or later of Jview is required for WebLogic jDriver forOracle.

� Jview does not support JDBC 2.0 features.

Checking connections to the Oracle database

Once you have installed WebLogic jDriver for Oracle you should check that you canuse it to connect to your database. A utility called dbping is included with WebLogicServer that you can use to test this connection.

To use this helper application, type the following at the command line (on one line):

$ java -classpathc:\java\lib\classes.zip;c:\weblogic\classes;c:\weblogic\license;utils.dbping ORACLE user password server

Where c:\weblogic is the directory containing your WebLogic Server or WebLogicjDriver for Oracle installation and c:\java is the path to your JDK.

Note: If you are using Java 2 (JDK 1.2), omit “c:\java\lib\classes.zip” fromthe above command.

For more detailed instructions on how to verify your connection to a DBMS, seeTesting connections.

If you have problems, check Troubleshooting problems with shared libraries on UNIX,at http://www.weblogic.com/docs51/techsupport/sharedlibs.html.

Installing and Using WebLogic jDriver for Oracle 17

1 Installing WebLogic jDriver for Oracle

Setting up a connection pool

If you are using WebLogic jDriver for Oracle with either WebLogic Server orWebLogic Express, you can set up a pool of connections to your Oracle DBMS thatwill be established when WebLogic Server is started. Since the connections are sharedamong users, these connection pools eliminate the overhead of opening a new databaseconnection for each user.

Your application then uses a multitier (Type-3) JDBC driver, such as the WebLogicPool, JTS or RMI driver to connect to WebLogic Server. WebLogic Server then usesWebLogic jDriver for Oracle and one of the existing connections from the pool toconnect to the Oracle database on behalf of your application.

Configuring a connection pool with WebLogic Server

1. Include the vendor-supplied native libraries and the WebLogic native libraries forWebLogic jDriver for Oracle in the PATH (Windows) or load library path

(UNIX) of the shell where you will start WebLogic Server (for details, see Settingyour path and client libraries on page 12). For more information on startingWebLogic Server, see Setting up and Starting WebLogic Server athttp://www.weblogic.com/docs51/install/startserver.html.

2. Add an entry to the weblogic.properties file specifying the connection poolproperties (driver name, url, server, password, ACLs, etc.). For example:

weblogic.jdbc.connectionPool.OraclePool=\url=jdbc:weblogic:oracle:myServer:myPort,\driver=weblogic.jdbc.oci.Driver,\loginDelaySecs=1,\initialCapacity=4,\maxCapacity=10,\capacityIncrement=2,\allowShrinking=true,\shrinkPeriodMins=15,\refreshMinutes=10,\testTable=dual,\props=user=myUserName;password=secret;server=myServer;\

weblogic.allow.reserve.weblogic.jdbc.connectionPool.SQLPool=\guest,joe,jill

weblogic.allow.reset.weblogic.jdbc.connectionPool.SQLPool=\joe,jill

18 Installing and Using WebLogic jDriver for Oracle

Checking connections to the Oracle database

weblogic.allow.shrink.weblogic.jdbc.connectionPool.SQLPool=\joe,jill

For more information on setting properties for connection pools, see JDBCConnection Pools, athttp://www.weblogic.com/docs51/admindocs/properties.html#conpools, in theWebLogic Administrators guide Setting WebLogic Properties.

3. Start WebLogic Server.

Using the connection pool in your application

Client-side applications

To use a connection pool in a client-side application, establish the database connectionusing the WebLogic JDBC/RMI driver. For more information, see

� Using WebLogic JDBC/RMI and WebLogic Clustered JDBC athttp://www.weblogic.com/docs51/classdocs/JDBC_RMI.html.

Server-side applications

To use a connection pool in a server-side application (such as a servlet), establish yourdatabase connection using the WebLogic pool or jts drivers. For more information,see:

� Using connection pools with server-side Java (in Using WebLogic HTTPServlets) at http://www.weblogic.com/docs51/classdocs/API_servlet.html#pools0

� Creating a startup connection pool athttp://www.weblogic.com/docs51/classdocs/API_jdbct3.html#startupconnpool

Installing and Using WebLogic jDriver for Oracle 19

1 Installing WebLogic jDriver for Oracle

Using IDEs or debuggers with WebLogic jDrivers

If you are using Symantec Cafe, other IDEs, or debuggers, copy theWebLogic-supplied native library to a new file with a name that ends in _g (before thedot).

For example on a Unix machine, copy libweblogicoci36.so tolibweblogicoci36_g.so. For Windows NT, copy weblogicoci36.dll toweblogicoci36_g.dll

Next step

See Setting your development environment, athttp://www.weblogic.com/docs51/techstart/environment.html for information onsetting up a development environment for running JDBC clients.

Using WebLogic jDriver for Oracle (athttp://www.weblogic.com/docs51/classdocs/API_joci.html). Developers Guide forWebLogic jDriver for Oracle.

20 Installing and Using WebLogic jDriver for Oracle

CHAPTER

2 Using WebLogic jDriver for Oracle

Introduction

WebLogic jDriver for Oracle is a new name for the product previously known asjdbcKona/Oracle.

What’s in this document

This document covers using the WebLogic jDriver for Oracle JDBC driver for theOracle Database management system (DBMS). This driver is a Type-2 JDBC driverand requires the installation of Oracle client libraries on the machine accessing theOracle Server.

This document also includes general notes and an implementation guide for usingJDBC, and information on using Oracle-specific features with WebLogic jDriver forOracle. The discussions and examples in this document assume that the reader isfamiliar with Java, general DBMS concepts, and Structured Query Language (SQL).

This document also covers recent updates to WebLogic jDriver for Oracle, as ofversion 5, that include new JDBC 2.0 for Oracle features such as Blob and Clobsupport and Batch updates.

If you are using WebLogic JDBC, BEA's multitier JDBC implementation, you shouldalso refer to the Developers Guide Using WebLogic JDBC athttp://www.weblogic.com/docs51/classdocs/API_jdbct3.html for more information.

Installing and Using WebLogic jDriver for Oracle 21

2 Using WebLogic jDriver for Oracle

Overview of BEA jDrivers

The BEA WebLogic jDrivers include a Type-2 native JDBC driver for Oracle andType 4 JDBC drivers for Informix and Microsoft SQL Server. The Type-2 driveremploys client libraries supplied by the database vendor while the Type-4 drivers are100% pure Java; they connect to the database server at the wire level withoutvendor-supplied client libraries.

For more information, see WebLogic JDBC Options athttp://www.weblogic.com/docs51/classdocs/jdbcdrivers.html.

Software requirements

For details on the platforms, operating systems, JVMs, DBMS versions, and clientlibraries supported by the WebLogic jDrivers see Platform support for WeblogicjDrivers at http://www.weblogic.com/docs51/platforms/index.html.

Installation

For installation instructions, see Installing WebLogic jDriver for Oracle athttp://www.weblogic.com/docs51/install/install_jdbc.html.

22 Installing and Using WebLogic jDriver for Oracle

Implementing with WebLogic jDriver for Oracle

Implementing with WebLogic jDriver for Oracle

This example follows a simple application through the basic steps:

� Importing JDBC packages

� Connecting to an Oracle DBMS.

� Making a simple SQL query

� Inserting, updating, and deleting records

� Creating and using stored procedures and functions

� Disconnecting and closing objects

� Code example.

Importing packages

The classes that you import into your application should include:

import java.sql.*;import java.util.Properties; // required only if using a Properties

// object to set connection parametersimport weblogic.common.*;

The WebLogic jDriver for Oracle driver implements the java.sql interface. Youwrite your application using the java.sql classes. You do not need to import theJDBC driver class; instead, you load the driver inside the application. This allows youto select an appropriate driver at runtime. You can even decide what DBMS to connectto after the program is compiled.

Setting CLASSPATH

When running a WebLogic jDriver for Oracle client using the driver provided withWebLogic Server you must put the following directory in your CLASSPATH:

Installing and Using WebLogic jDriver for Oracle 23

2 Using WebLogic jDriver for Oracle

weblogic/classes

(where weblogic is the directory containing your WebLogic Server installation)

If you are running a stand-alone version of WebLogic jDriver for Oracle, place thefollowing directory in your classpath:

weblogic/oci/classes

(where weblogic is the directory containing your WebLogic jDriver for Oracleinstallation)

For more information on setting your CLASSPATH and other environment issues, seeSetting your development environment athttp://www.weblogic.com/docs51/techstart/environment.html.

24 Installing and Using WebLogic jDriver for Oracle

Implementing with WebLogic jDriver for Oracle

Oracle client library versions, URLs, and Driver class names

Depending on your platform, which version of the Oracle client libraries you are using,and whether or not you require access to JDBC 2.0 features (Blobs, Clobs, Batchupdates), you need to use a different driver class name and URL.

You must also specify the correct driver version in your system’s path. For moreinformation, see Setting your path and client libraries athttp://www.weblogic.com/docs51/install/install_jdbc.html#client.

JDBC 1.x

Driver class: weblogic.jdbc.oci.Driver

URL: jdbc:weblogic:oracle

JDBC 2.0

Driver class: weblogic.jdbc20.oci.Driver

URL: jdbc20:weblogic:oracle

Connecting to an Oracle DBMS

These steps explain how to set up your application to connect to your Oracle DBMSusing WebLogic jDriver for Oracle. In general, connecting happens in three steps:

1. Load the JDBC driver by calling Class.forName().newInstance() with thefull class name of the WebLogic jDriver for Oracle JDBC driver class, and castingit to a java.sql.Driver object. This procedure properly loads and registers theJDBC driver. For example:

Driver myDriver = (Driver)Class.forName("weblogic.jdbc.oci.Driver").newInstance();

Installing and Using WebLogic jDriver for Oracle 25

2 Using WebLogic jDriver for Oracle

2. Create a java.util.Properties object describing the connection. This objectcontains name-value pairs containing information such as user name, password,database name, server name, and port number. For example:

Properties props = new Properties();props.put("user", "scott");props.put("password", "secret");props.put("server", "DEMO");

The server name (“DEMO” in the example above) refers to an entry in thetnsnames.ora file, which is located in your Oracle client installation anddefines host names and other information about an Oracle database. If you donot supply a server name, the system will look for an environment variable(ORACLE_SID in the case of Oracle). You may also choose to add the servername to the URL, with this format:

"jdbc:weblogic:oracle:DEMO"

in which case you do not need to provide a “server” property.

You can also set properties in a single URL, for use with products likePowerSoft's PowerJ. For details, see Using URLs with WebLogic products athttp://www.weblogic.com/docs51/classdocs/urls.html.

3. Create a JDBC Connection object, which becomes an integral piece in yourJDBC operations, by calling the Driver.connect() method, which takes as itsparameters the URL of the driver and the java.util.Properties object youcreated in step 2. For example:

Connection conn =myDriver.connect("jdbc:weblogic:oracle", props);

In steps 1 and 3, you are describing the JDBC driver: in the first step, you use the fullpackage name of the driver. Note that it is dot-delimited. In the third step, you identifythe driver with its URL, which is colon-delimited. The URL must include at leastweblogic:jdbc:mssqlserver4, and may include other information, including the serverhost name and the database name.

Note: The examples in this document use the driver nameweblogic.jdbc.oci.Driver and the URL jdbc:weblogic:oracle.

These are intended for use where JDBC 2.0 features are not required. You mayalso use the driver name weblogic.jdbc20.oci.Driver and the URLjdbc20:weblogic:oracle if you need to use JDBC 2.0 features. For moreinformation on JDBC 2.0, see JDBC 2.0 for Oracle on page 51.

26 Installing and Using WebLogic jDriver for Oracle

Implementing with WebLogic jDriver for Oracle

There are additional restrictions regarding the use of JDBC 2.0. For moreinformation, see Oracle client library versions, URLs, and Driver class nameson page 25.

Connection example

This example shows how to use a Properties object to connect to a database named“myDB.”

Properties props = new Properties();props.put("user", "scott");props.put("password", "secret");props.put("db", "myDB");

Driver myDriver = (Driver)Class.forName("weblogic.jdbc.oci.Driver").newInstance();

Connection conn =myDriver.connect("jdbc:weblogic:oracle", props);

Connecting using a DataSource object

If you are using WebLogic jDriver for Oracle as a middle-tier driver with WebLogicServer, you can also obtain a connection by using a DataSource object. For moreinformation, see Using a DataSource object to get a connection athttp://www.weblogic.com/docs51/classdocs/DataSource.html.

Setting properties for WebLogic JDBC use

If you are using WebLogic JDBC in a multitier environment with the WebLogicjDriver for Oracle driver, you will set connection properties in a slightly different way.See Using WebLogic JDBC athttp://www.weblogic.com/docs51/classdocs/API_jdbct3.html for more information.

About the Connection object

The Connection object is an important part of the application. The Connection classhas constructors for many fundamental database objects that you will use throughoutthe application, and in the examples that follow, you will see the Connection objectconn used frequently. Connecting to the database completes the initial portion of theapplication.

Installing and Using WebLogic jDriver for Oracle 27

2 Using WebLogic jDriver for Oracle

You should call the close() method on the Connection object as soon as you finishworking with it, usually at the end of a class.

Setting Autocommit

The default transaction mode for JDBC assumes autocommit to be true. WithWebLogic jDriver for Oracle, setting autocommit to false will improve performance.

Making a simple SQL query

The most fundamental task in database access is to retrieve data. With WebLogicjDriver for Oracle, this is a three-step process:

1. Create a Statement to send a SQL query to the DBMS

2. Execute the Statement

3. Retrieve the results into a ResultSet In this example, we execute a simple queryon the Employee table (alias “emp”) and display data from three of the columns.We also access and display metadata about the table from which the data wasretrieved. Note that we close the Statement at the end.

Statement stmt = conn.createStatement();stmt.execute("select * from emp");ResultSet rs = stmt.getResultSet();

while (rs.next()) {System.out.println(rs.getString("empid") + " - " +

rs.getString("name") + " - " +rs.getString("dept"));

}

ResultSetMetaData md = rs.getMetaData();

System.out.println("Number of columns: " +md.getColumnCount());

for (int i = 1; i <= md.getColumnCount(); i++) {System.out.println("Column Name: " +md.getColumnName(i));

System.out.println("Nullable: " +md.isNullable(i));

System.out.println("Precision: " +md.getPrecision(i));

28 Installing and Using WebLogic jDriver for Oracle

Implementing with WebLogic jDriver for Oracle

System.out.println("Scale: " +md.getScale(i));

System.out.println("Size: " +md.getColumnDisplaySize(i));

System.out.println("Column Type: " +md.getColumnType(i));

System.out.println("Column Type Name: "+md.getColumnTypeName(i));

System.out.println("");}

stmt.close();

JDBC ResultSets have a basic functionality for dealing with data on the record level.You may find managing data easier with BEA’s dbKona, which features a higher levelof abstraction. dbKona’s objects, like TableDataSet, QueryDataSet, and Record, aswell as other features like automatic SQL generation and client-side resultsmanagement, sit on top of JDBC. Check the Developers Guide Using dbKona, athttp://www.weblogic.com/docs51/classdocs/API_db.html for more information.

Inserting, updating, and deleting records

We illustrate three common database tasks in this step: inserting, updating, anddeleting records from a database table. We use a JDBC PreparedStatement for theseoperations; we create the PreparedStatement, then execute it and close it.

A PreparedStatement (subclassed from JDBC Statement) allows you to execute thesame SQL over and over again with different values. PreparedStatements use theJDBC “?” syntax.

String inssql ="insert into emp(empid, name, dept) values (?, ?, ?)";

PreparedStatement pstmt = conn.prepareStatement(inssql);for (int i = 0; i < 100; i++) {pstmt.setInt(1, i);pstmt.setString(2, "Person " + i);pstmt.setInt(3, i);pstmt.execute():

}pstmt.close();

We also use a PreparedStatement to update records. In this example, we add the valueof the counter “i” to the current value of the “dept” field.

Installing and Using WebLogic jDriver for Oracle 29

2 Using WebLogic jDriver for Oracle

String updsql ="update emp set dept = dept + ? where empid = ?";

PreparedStatement pstmt2 = conn.prepareStatement(updsql);for (int i = 0; i < 100; i++) {pstmt2.setInt(1, i);pstmt2.setInt(2, i);pstmt2.execute();

}pstmt2.close();

Finally, we use a PreparedStatement to delete the records that added and then updated.

String delsql = "delete from emp where empid = ?";PreparedStatement pstmt3 = conn.prepareStatement(delsql);for (int i = 0; i < 100; i++) {pstmt3.setInt(1, i);pstmt3.execute();

}pstmt3.close();

Creating and using stored procedures and functions

You can use WebLogic jDriver for Oracle to create, use, and drop stored proceduresand functions. First, we execute a series of Statements to drop a set of storedprocedures and functions from the database.

Statement stmt = conn.createStatement();try {stmt.execute("drop procedure proc_squareInt");}catch (SQLException e) {//code to handle the exception goes here;}try {stmt.execute("drop procedure func_squareInt");}catch (SQLException e) {//code to handle the exception goes here;}try {stmt.execute("drop procedure proc_getresults");}catch (SQLException e) {//code to handle the exception goes here;}stmt.close();

We use a JDBC Statement to create a stored procedure or function, and then we use aJDBC CallableStatement (subclassed from Statement) with the JDBC “?” syntax to setIN and OUT parameters.

Note that Oracle does not natively support binding to “?” values in a SQL statement.Instead it uses “:1”, “:2”, etc. You can use either syntax in your SQL with WebLogicjDriver for Oracle.

30 Installing and Using WebLogic jDriver for Oracle

Implementing with WebLogic jDriver for Oracle

Stored procedure input parameters are mapped to JDBC IN parameters, using theCallableStatement.setXXX() methods, like setInt(), and the JDBCPreparedStatement “?” syntax. Stored procedure output parameters are mapped toJDBC OUT parameters, using the CallableStatement.registerOutParameter()methods and JDBC PreparedStatement “?” syntax. A parameter may be both IN andOUT, which requires both a setXXX() and a registerOutParameter() call to bedone on the same parameter number.

In this example, we use a JDBC Statement to create an Oracle stored procedure; thenwe execute the stored procedure with a CallableStatement. We use theregisterOutParameter() method to set an output parameter for the squared value.

Statement stmt1 = conn.createStatement();stmt1.execute("CREATE OR REPLACE PROCEDURE proc_squareInt " +"(field1 IN OUT INTEGER, field2 OUT INTEGER) IS " +"BEGIN field2 := field1 * field1; field1 := " +"field1 * field1; END proc_squareInt;");

stmt1.close();

// Native Oracle SQL is commented out here// String sql = "BEGIN proc_squareInt(?, ?); END;";

// This is the correct syntax as specified by JDBCString sql = "{call proc_squareInt(?, ?)}";CallableStatement cstmt1 = conn.prepareCall(sql);

// Register out parameterscstmt1.registerOutParameter(2, java.sql.Types.INTEGER);for (int i = 0; i < 5; i++) {cstmt1.setInt(1, i);cstmt1.execute();System.out.println(i + " " + cstmt1.getInt(1) + " "+ cstmt1.getInt(2));

} cstmt1.close();

In the next example, we use similar code to create and execute a stored function thatsquares an integer.

Statement stmt2 = conn.createStatement();stmt2.execute("CREATE OR REPLACE FUNCTION func_squareInt " +

"(field1 IN INTEGER) RETURN INTEGER IS " +"BEGIN return field1 * field1; " +"END func_squareInt;");

stmt2.close();

// Native Oracle SQL is commented out here

Installing and Using WebLogic jDriver for Oracle 31

2 Using WebLogic jDriver for Oracle

// sql = "BEGIN ? := func_squareInt(?); END;";

// This is the correct syntax specified by JDBCsql = "{ ? = call func_squareInt(?)}";CallableStatement cstmt2 = conn.prepareCall(sql);

cstmt2.registerOutParameter(1, Types.INTEGER);for (int i = 0; i < 5; i++) {cstmt2.setInt(2, i);cstmt2.execute();System.out.println(i + " " + cstmt2.getInt(1) +

" " + cstmt2.getInt(2));}cstmt2.close();

This next example uses a stored procedure named sp_getmessages (the code for thisstored procedure is not included with this example) This stored procedure takes amessage number as an input parameter, looks up the message number in a tablecontaining the message text and returns the message text in a ResultSet as an outputparameter. Note that you must process all ResultSets returned by a stored procedureusing the Statement.execute() and Statement.getResult() methods beforeOUT parameters and return status are available.

First, we set up the three parameters to the CallableStatement:

1. Parameter 1 (output only) is the stored procedure return value

2. Parameter 2 (input only) is the msgno argument to sp_getmessage

3. Parameter 3 (output only) is the message text return for the message number

String sql = "{ ? = call sp_getmessage(?, ?)}";CallableStatement stmt = conn.prepareCall(sql);

stmt.registerOutParameter(1, java.sql.Types.INTEGER);stmt.setInt(2, 18000); // msgno 18000stmt.registerOutParameter(3, java.sql.Types.VARCHAR);

We execute the stored procedure and check the return value to see if the ResultSet isempty. If it is not, we use a loop to retrieve and display its contents.

boolean hasResultSet = stmt.execute();while (true){

ResultSet rs = stmt.getResultSet();int updateCount = stmt.getUpdateCount();if (rs == null && updateCount == -1) // no more resultsbreak;

32 Installing and Using WebLogic jDriver for Oracle

Implementing with WebLogic jDriver for Oracle

if (rs != null) {// Process the ResultSet until it is emptywhile (rs.next()) {System.out.println("Get first col by id:" + rs.getString(1));

}} else {// we have an update countSystem.out.println("Update count = " +stmt.getUpdateCount());

}stmt.getMoreResults();

}

Once we finish processing the ResultSet, the OUT parameters and return status areavailable.

int retstat = stmt.getInt(1);String msg = stmt.getString(3);

System.out.println("sp_getmessage: status = " +retstat + " msg = " + msg);

stmt.close();

Disconnecting and closing objects

There are occasions on which you will want to call the commit() method to commitchanges you’ve made to the database before you close the connection.

When autocommit is set to true (the default JDBC transaction mode) each SQLstatement is its own transaction. After we created the Connection for these examples,however, we set autocommit to false; in this mode, the Connection always has animplicit transaction associated with it, and any call to the rollback() or commit()methods will end the current transaction and start a new one. Calling commit() beforeclose() ensures that all of the transactions are completed before closing theConnection.

Just as you close Statements, PreparedStatements, and CallableStatements when youhave finished working with them, you should always call the close() method on theconnection as final cleanup in your application, in a try {} block, and you shouldcatch exceptions and deal with them appropriately. The final two lines of this exampleinclude a call to commit and then a call to close the connection.

Installing and Using WebLogic jDriver for Oracle 33

2 Using WebLogic jDriver for Oracle

conn.commit();conn.close();

Code example

Here are selected portions of the code used in these examples to give you an overallidea of structure for a JDBC application. The code example shown here includesretrieving data, displaying metadata, inserting, deleting, and updating data, and storedprocedures and functions. Note the explicit calls to close() for each JDBC-relatedobject, and note also that we close the Connection itself in a finally {} block, withthe call to close() wrapped in a try {} block.

package examples.jdbc.oracle;

import java.sql.*;import java.util.Properties;import weblogic.common.*;

public class test {static int i;Statement stmt = null;

public static void main(String[] argv) {try {Properties props = new Properties();props.put("user", "scott");props.put("password", "tiger");props.put("server", "DEMO");

Driver myDriver = (Driver) Class.forName("weblogic.jdbc.oci.Driver").newInstance();

Connection conn =myDriver.connect("jdbc:weblogic:oracle", props);

}catch (Exception e)e.printStackTrace();

}

try {// This will improve performance in Oracle// You'll need an explicit commit() call laterconn.setAutoCommit(false);

34 Installing and Using WebLogic jDriver for Oracle

Implementing with WebLogic jDriver for Oracle

stmt = conn.createStatement();stmt.execute("select * from emp");ResultSet rs = stmt.getResultSet();

while (rs.next()) {System.out.println(rs.getString("empid") + " - " +

rs.getString("name") + " - " +rs.getString("dept"));

}

ResultSetMetaData md = rs.getMetaData();

System.out.println("Number of Columns: " +md.getColumnCount());

for (i = 1; i <= md.getColumnCount(); i++) {System.out.println("Column Name: " +

md.getColumnName(i));System.out.println("Nullable: " +

md.isNullable(i));System.out.println("Precision: " +

md.getPrecision(i));System.out.println("Scale: " +

md.getScale(i));System.out.println("Size: " +

md.getColumnDisplaySize(i));System.out.println("Column Type: " +

md.getColumnType(i));System.out.println("Column Type Name: "+

md.getColumnTypeName(i));System.out.println("");

}rs.close();stmt.close();

Statement stmtdrop = conn.createStatement();try {stmtdrop.execute("drop procedure proc_squareInt");}catch (SQLException e) {;}try {stmtdrop.execute("drop procedure func_squareInt"); }catch (SQLException e) {;}try {stmtdrop.execute("drop procedure proc_getresults"); }catch (SQLException e) {;}stmtdrop.close();

// Create a stored procedureStatement stmt1 = conn.createStatement();stmt1.execute("CREATE OR REPLACE PROCEDURE proc_squareInt " +"(field1 IN OUT INTEGER, " +"field2 OUT INTEGER) IS " +

Installing and Using WebLogic jDriver for Oracle 35

2 Using WebLogic jDriver for Oracle

"BEGIN field2 := field1 * field1; " +"field1 := field1 * field1; " +"END proc_squareInt;");stmt1.close();

CallableStatement cstmt1 =conn.prepareCall("BEGIN proc_squareInt(?, ?); END;");

cstmt1.registerOutParameter(2, Types.INTEGER);for (i = 0; i < 100; i++) {cstmt1.setInt(1, i);cstmt1.execute();System.out.println(i + " " + cstmt1.getInt(1) +

" " + cstmt1.getInt(2));}cstmt1.close();

// Create a stored functionStatement stmt2 = conn.createStatement();stmt2.execute("CREATE OR REPLACE FUNCTION func_squareInt " +"(field1 IN INTEGER) RETURN INTEGER IS " +"BEGIN return field1 * field1; END func_squareInt;");stmt2.close();

CallableStatement cstmt2 =conn.prepareCall("BEGIN ? := func_squareInt(?); END;");

cstmt2.registerOutParameter(1, Types.INTEGER);for (i = 0; i < 100; i++) {cstmt2.setInt(2, i);cstmt2.execute();System.out.println(i + " " + cstmt2.getInt(1) +

" " + cstmt2.getInt(2));}cstmt2.close();

// Insert 100 recordsSystem.out.println("Inserting 100 records...");String inssql ="insert into emp(empid, name, dept) values (?, ?, ?)";

PreparedStatement pstmt = conn.prepareStatement(inssql);

for (i = 0; i < 100; i++) {pstmt.setInt(1, i);pstmt.setString(2, "Person " + i);pstmt.setInt(3, i);pstmt.execute();

}pstmt.close();

36 Installing and Using WebLogic jDriver for Oracle

Implementing with WebLogic jDriver for Oracle

// Update 100 recordsSystem.out.println("Updating 100 records...");String updsql ="update emp set dept = dept + ? where empid = ?";PreparedStatement pstmt2 = conn.prepareStatement(updsql);

for (i = 0; i < 100; i++) {pstmt2.setInt(1, i);pstmt2.setInt(2, i);pstmt2.execute();

}pstmt2.close();

// Delete 100 recordsSystem.out.println("Deleting 100 records...");String delsql = "delete from emp where empid = ?";PreparedStatement pstmt3 = conn.prepareStatement(delsql);

for (i = 0; i < 100; i++) {pstmt3.setInt(1, i);pstmt3.execute();

}pstmt3.close();

conn.commit();}catch (Exception e) {// Deal with failures appropriately

}finally {try {conn.close();}catch (Exception e) {// Catch and deal with exception

}}

}}

Working with ResultSets from stored procedures

Executing stored procedures may return multiple ResultSets. When you processResultSets returned by a stored procedure, using Statement.execute() andStatement.getResultSet() methods, you must process all ResultSets returnedbefore any of the OUT parameters or the return status codes are available.

Installing and Using WebLogic jDriver for Oracle 37

2 Using WebLogic jDriver for Oracle

Support for JDBC Extended SQL

The JavaSoft JDBC specification includes SQL Extensions, also called SQL EscapeSyntax. All WebLogic jDrivers support Extended SQL. Extended SQL provides accessto common SQL extensions in a way that is portable between DBMSs.

For example, the function to extract the day name from a date is not defined by the SQLstandards. For Oracle, the SQL is:

select to_char(date_column, 'DAY') from table_with_dates

The equivalent function for Sybase and Microsoft SQL Server is:

select datename(dw, date_column) from table_with_dates

Using Extended SQL, you can retrieve the day name for both DBMSs as follows:

select {fn dayname(date_column)} from table_with_dates

Here’s an example that demonstrates several features of Extended SQL:

String query ="-- This SQL includes comments and " +

"JDBC extended SQL syntax.\n" +"select into date_table values( \n" +" {fn now()}, -- current time \n" +" {d '1997-05-24'}, -- a date \n" +" {t '10:30:29' }, -- a time \n" +" {ts '1997-05-24 10:30:29.123'}, -- a timestamp\n" +" '{string data with { or } will not be altered}'\n" +"-- Also note that you can safely include" +

" { and } in comments or\n" +"-- string data.";Statement stmt = conn.createStatement();stmt.executeUpdate(query);

Extended SQL is delimited with curly braces (“{}”) to differentiate it from commonSQL. Comments are preceded by two hyphens, and are ended by a new line (“\n”).The entire Extended SQL sequence, including comments, SQL, and Extended SQL, isplaced within double quotes and passed to the execute() method of a Statementobject. Here is Extended SQL used as part of a CallableStatement:

CallableStatement cstmt =conn.prepareCall("{ ? = call func_squareInt(?)}");

This example shows that you can nest extended SQL expressions:

38 Installing and Using WebLogic jDriver for Oracle

Additional Oracle features

select {fn dayname({fn now()})}

You can retrieve lists of supported Extended SQL functions from a DatabaseMetaDataobject. This example shows how to list all the functions a JDBC driver supports:

DatabaseMetaData md = conn.getMetaData();System.out.println("Numeric functions: " +

md.getNumericFunctions());System.out.println("\nString functions: " +

md.getStringFunctions());System.out.println("\nTime/date functions: " +

md.getTimeDateFunctions());System.out.println("\nSystem functions: " +

md.getSystemFunctions());conn.close();

Refer to chapter 11 of the JDBC 1.2 specification at JavaSoft athttp://splash.javasoft.com/jdbc for a description of Extended SQL.

Additional Oracle features

Allowing mixed case metadata

WebLogic jDriver for Oracle also allows setting the propertyallowMixedCaseMetaData. When set to the boolean true, this property sets up theConnection to use mixed case in calls to DatabaseMetaData methods. If this propertyis set to false, Oracle defaults to UPPERCASE for database metadata. Here is anexample of setting up the properties to include this feature:

Properties props = new Properties();props.put("user", "scott");props.put("password", "tiger");props.put("server", "DEMO");props.put("allowMixedCaseMetaData", "true");

Driver myDriver = (Driver)Class.for.Name(weblogic.jdbc.oci.Driver).newInstance();

Connection conn =myDriver.connect("jdbc:weblogic:oracle", props);

Installing and Using WebLogic jDriver for Oracle 39

2 Using WebLogic jDriver for Oracle

If you do not set this property, WebLogic jDriver for Oracle defaults to the Oracledefault, which uses UPPERCASE for database metadata.

Data types

The table below shows the recommended mapping between Oracle data types and Javatypes. There are additional possibilities for representing Oracle data types in Java.Calling the getObject() method when processing result sets will return the defaultJava data type for the Oracle column being queried.

Figure 2-1 Mapping of types between Oracle and WebLogic jDriver for Oracle.

Oracle WebLogic jDriverfor Oracle

Varchar String

Number Tinyint

Number Smallint

Number Integer

Number Long

Number Float

Number Numeric

Number Double

Long Longvarchar

RowID String

Date Timestamp

Raw (var)Binary

Long raw Longvarbinary

Char (var)Char

40 Installing and Using WebLogic jDriver for Oracle

Additional Oracle features

*Note that when PreparedStatement.setBoolean() is called, it will convert aVARCHAR type to “1” or “0” (string), and it will convert a NUMBER type to 1 or 0(number).

WebLogic jDriver for Oracle and Oracle's NUMBER column

Oracle provides a column type called NUMBER, which can be optionally specified witha precision and a scale, in the forms NUMBER(P) and NUMBER(P,S). Even in the simpleunqualified NUMBER form, this column can hold all number types from small integervalues to very large floating point numbers, with high precision.

WebLogic jDriver for Oracle reliably converts the values in a column to the Java typerequested when a WebLogic jDriver for Oracle application asks for a value from sucha column. Of course, if a value of 123.456 is asked for with getInt(), the value willbe rounded.

The method getObject(), however, poses a little more complexity. WebLogicjDriver for Oracle guarantees to return a Java object which will represent any value ina NUMBER column with no loss in precision. This means that a value of 1 can be returnedin an Integer, but a value like 123434567890.123456789 can only be returned in aBigDecimal.

There is no metadata from Oracle to report the maximum precision of the values in thecolumn, so WebLogic jDriver for Oracle must decide what sort of object to returnbased on each value. This means that one ResultSet may return multiple Java typesfrom getObject() for a given NUMBER column. A table full of integer values mayall be returned as Integer from getObject(), whereas a table of floating pointmeasurements may be returned primarily as Double, with some Integer if any valuehappens to be something like “123.00”. Oracle does not provide any information todistinguish between a NUMBER value of “1” and a NUMBER of “1.0000000000”.

Boolean* Number ORVarchar

MLS label String

Blob Blob

Clob Clob

Installing and Using WebLogic jDriver for Oracle 41

2 Using WebLogic jDriver for Oracle

There is some more reliable behavior with qualified NUMBER columns, that is, thosedefined with a specific precision. Oracle's metadata provides these parameters to thedriver so WebLogic jDriver for Oracle will always return a Java object appropriate forthe given precision and scale, regardless of the values in the table.

Using Oracle Long raw data types

There are two properties available for use with WebLogic jDriver for Oracle in supportof Oracle's chunking of Blobs, Clobs, Long, and Long raw data types. Although Bloband Clob data types are only supported with Oracle Version 8 and JDBC 2.0, theseproperties also apply to Oracle’s Long raw datatype, which is available in OracleVersion 7 and JDBC 1.x. For more information on theses properties, see Connectionproperties in the JDBC 2.0 section, on page 53.

Waiting on Oracle resources

Note: The waitOnResources() method is not supported when using the Oracle 8API. (For more information on your Oracle client, server, and API versions,see Setting your path and client libraries athttp://www.weblogic.com/docs51/install/install_jdbc.html#client.)

The WebLogic jDriver for Oracle driver supports Oracle's oopt() C functionality,which allows a client to wait until resources become available. The Oracle C functionsets options in cases where requested resources are not available; for example, whetherto wait for locks.

Column definition Returned by getObject()

NUMBER(P <= 9) Integer

NUMBER(P <= 18) Long

NUMBER(P = 19) BigDecimal

NUMBER(P <=16, S 0) Double

NUMBER(P = 17, S 0) BigDecimal

42 Installing and Using WebLogic jDriver for Oracle

Additional Oracle features

The developer can set whether a client will wait for DBMS resources, or will receivean immediate exception. Here's an example from the exampleexamples/jdbc/oracle/waiton.java:

java.util.Properties props = new java.util.Properties();props.put("user", "scott");props.put("password", "tiger");props.put("server", "myserver");

Driver myDriver = (Driver)Class.forName("weblogic.jdbc.oci.Driver").newInstance();

// You must cast the Connection as a weblogic.jdbc.oci.Connection// to take advantage of this extension

Connection conn =(weblogic.jdbc.oci.Connection)myDriver.connect("jdbc:weblogic:oracle", props);

// After constructing the Connection object, immediately call// the waitOnResources method

conn.waitOnResources(true);

Note that use of this method can cause several error return codes while waiting forinternal resources that are locked for short durations.

To take advantage of this feature, you must first cast your Connection object as aweblogic.jdbc.oci.Connection, and then call the waitOnResources() method.

This functionality is described in section 4-97 of The OCI Functions for C.

Autocommit

The default transaction mode for JDBC WebLogic jDriver for Oracle assumesautocommit to be true. You will improve the performance of your programs by settingautocommit to false after creating a Connection object with the statement:

Connection.setAutoCommit(false);

Transaction isolation levels

WebLogic jDriver for Oracle supports the following transaction isolation levels:

Installing and Using WebLogic jDriver for Oracle 43

2 Using WebLogic jDriver for Oracle

� SET TRANSACTION ISOLATION LEVEL READ COMMITTED

� SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

The Oracle DBMS only supports these two isolation levels. Unlike other JDBCdrivers, WebLogic jDriver for Oracle throws an exception if you try to use an isolationlevel that is unsupported. Some drivers silently ignore attempts to set an unsupportedisolation level.

The READ_UNCOMMITTED transaction isolation level is not supported.

Codeset support

JDBC and your WebLogic jDriver for Oracle driver handle character strings in Java asUnicode strings. Since the Oracle DBMS uses a different codeset, the driver mustconvert character strings from Unicode to the codeset used by Oracle. The WebLogicjDriver for Oracle will examine the value stored in the Oracle environment variableNLS_LANG and select a codeset for the JDK to use for the conversion, using themapping shown in the table below. If the NLS_LANG variable is not set, or is set to acodeset not recognized by the JDK, the driver will not be able to determine the correctcodeset. (Consult your Oracle documentation for information on the correct syntax forsetting NLS_LANG.)

If you are converting codesets, you should pass the following property to theWebLogic jDriver for Oracle with the Driver.connect() method when youestablish the connection in your code:

props.put(“weblogic.oci.min_bind_size”, 660);

This property defines the minimum size of buffers to be bound. The default is 2000bytes, which is also the maximum value. If you are converting codesets, you shoulduse this property to reduce the bind size to a maximum of 660, one-third of themaximum 2000 bytes, since Oracle codeset conversion triples the buffer to allow forexpansion.

WebLogic jDriver for Oracle provides a way to set the codeset from within your Javacode. By setting a connection property, weblogic.codeset, you can override thevalue stored in the NLS_LANG environment variable. For example, to use the cp932codeset, create a Properties object and set the weblogic.codeset property before callingDriver.connect(), as in this example:

44 Installing and Using WebLogic jDriver for Oracle

Additional Oracle features

java.util.Properties props = new java.util.Properties();props.put("weblogic.codeset", "cp932");props.put("user", "scott");props.put("password", "tiger");

String connectUrl = "jdbc:weblogic:oracle";

Driver myDriver = (Driver)Class.forName("weblogic.jdbc.oci.Driver").newInstance();

Connection conn =myDriver.connect(connectUrl, props);

Note that codeset support can vary with different JVMs. Check the documentation forthe JDK you are using to determine if a particular codeset is supported. You can findthe List of supported encodings for JDK 1.1 at the JavaSoft website.

Table 2-1 Mapping of NLS_LANG settings to JDK codesets

NLS_LANG JDK codeset

us7ascii ASCII

ja16sjis SJIS

us8pc437 Cp437

we8ebcdic37 Cp1046

we8ebcdic500 Cp500

we8pc850 Cp850

we8iso8859p1 ISO8859_1

ee8iso8859p2 ISO8859_2

se8iso8859p3 ISO8859_3

nee8iso8859p4 ISO8859_4

cl8iso8859p5 ISO8859_5

ar8iso8859p6 ISO8859_6

el8iso8859p7 ISO8859_7

iw8iso8859p8 ISO8859_8

we8iso8859p9 ISO8859_9

ne8iso8859p10 ISO8859_10

ru8pc866 Cp866

ee8pc852 Cp852

Installing and Using WebLogic jDriver for Oracle 45

2 Using WebLogic jDriver for Oracle

ru8pc855 Cp855

tr8pc857 Cp857

cl8maccyrillic MacCyrillic

we8pc860 Cp860

is8pc861 Cp861

ee8mswin1250 Cp1250

cl8mswin1251 Cp1251

el8mswin1253 Cp1253

n8pc865 Cp865

ee8macce MacCentralEurope

ee8maccroatian MacCroatian

tr8macturkish MacTurkish

is8macicelandic MacIceland

el8macgreek MacGreek

we8macroman8 MacRoman

th8macthai MacThai

el8pc737 Cp737

lt8pc772 Cp772

lt8pc774 Cp774

cdn8pc863 Cp863

ja16euc EUC_JP

ko16ksc5601 EUC_KR

zht16big5 Big5

al24utffss UTF8

utf8 UTF8

46 Installing and Using WebLogic jDriver for Oracle

Additional Oracle features

Support for Oracle array fetches

WebLogic jDriver for Oracle supports Oracle array fetches. CallingResultSet.next() the first time will get an array of rows and store it in memory,rather than retrieving a single row. Each subsequent call to next() will read a rowfrom the rows in memory until they are exhausted, and only then will next() go backto the database.

You set a property (java.util.Property) to control the size of the array fetch. Theproperty is weblogic.oci.cacheRows; it is set by default to 100. Here's an exampleof setting this property to 300, which means that calls to next() only hit the databaseonce for each 300 rows retrieved by the client.

Properties props = new Properties();props.put("user", "scott");props.put("password", "tiger");props.put("server", "DEMO");props.put("weblogic.oci.cacheRows", "300");

Driver myDriver = (Driver)Class.forName("weblogic.jdbc.oci.Driver").newInstance();

Connection conn = myDriver.connect("jdbc:weblogic:oracle", props);

You can improve client performance and lower the load on the database server bytaking advantage of this JDBC extension. Caching rows in the client, however,requires client resources. You should tune your application for the best balancebetween performance and client resources, depending upon your networkconfiguration and your application.

If any columns in a SELECT are of type LONG, the cache size will be temporarilyreset to one (1) for the ResultSet associated with that select statement.

Installing and Using WebLogic jDriver for Oracle 47

2 Using WebLogic jDriver for Oracle

Using stored procedures

Binding a parameter to an Oracle cursor

WebLogic has created an extension to JDBC(weblogic.jdbc.oci.CallableStatement) that allows you to bind a parameter fora stored procedure to an Oracle cursor. You can create a JDBC ResultSet object withthe results of the stored procedure. This allows you to return multiple ResultSets in anorganized way. The ResultSets are determined at run time in the stored procedure.

Here is an example. First define the stored procedures as follows:

create or replace packagecurs_types astype EmpCurType is REF CURSOR RETURN emp%ROWTYPE;end curs_types;/

create or replace proceduresingle_cursor(curs1 IN OUT curs_types.EmpCurType,ctype in number) AS BEGINif ctype = 1 then

OPEN curs1 FOR SELECT * FROM emp;elsif ctype = 2 then

OPEN curs1 FOR SELECT * FROM emp where sal 2000;elsif ctype = 3 then

OPEN curs1 FOR SELECT * FROM emp where deptno = 20;end if;

END single_cursor;/create or replace proceduremulti_cursor(curs1 IN OUT curs_types.EmpCurType,

curs2 IN OUT curs_types.EmpCurType,curs3 IN OUT curs_types.EmpCurType) AS

BEGINOPEN curs1 FOR SELECT * FROM emp;OPEN curs2 FOR SELECT * FROM emp where sal 2000;OPEN curs3 FOR SELECT * FROM emp where deptno = 20;

END multi_cursor;/

In your Java code, you'll construct CallableStatements with the stored proceduresand register the output parameter as data type java.sql.Types.OTHER. When youretrieve the data into a ResultSet, use the output parameter index as an argument forthe getResultSet() method.

48 Installing and Using WebLogic jDriver for Oracle

Additional Oracle features

weblogic.jdbc.oci.CallableStatement cstmt =(weblogic.jdbc.oci.CallableStatement)conn.prepareCall(

"BEGIN OPEN ? " +"FOR select * from emp; END;");

cstmt.registerOutParameter(1, java.sql.Types.OTHER);

cstmt.execute();ResultSet rs = cstmt.getResultSet(1);printResultSet(rs);rs.close();cstmt.close();

weblogic.jdbc.oci.CallableStatement cstmt2 =(weblogic.jdbc.oci.CallableStatement)conn.prepareCall(

"BEGIN single_cursor(?, ?); END;");cstmt2.registerOutParameter(1, java.sql.Types.OTHER);

cstmt2.setInt(2, 1);cstmt2.execute();rs = cstmt2.getResultSet(1);printResultSet(rs);

cstmt2.setInt(2, 2);cstmt2.execute();rs = cstmt2.getResultSet(1);}printResultSet(rs);

cstmt2.setInt(2, 3);cstmt2.execute();rs = cstmt2.getResultSet(1);printResultSet(rs);cstmt2.close();

weblogic.jdbc.oci.CallableStatement cstmt3 =(weblogic.jdbc.oci.CallableStatement)conn.prepareCall(

"BEGIN multi_cursor(?, ?, ?); END;");cstmt3.registerOutParameter(1, java.sql.Types.OTHER);cstmt3.registerOutParameter(2, java.sql.Types.OTHER);cstmt3.registerOutParameter(3, java.sql.Types.OTHER);

cstmt3.execute();

ResultSet rs1 = cstmt3.getResultSet(1);ResultSet rs2 = cstmt3.getResultSet(2);ResultSet rs3 = cstmt3.getResultSet(3);

For the full code for this example, including the printResultSet() method, see theexamples in the examples/jdbc/oracle/ directory.

Installing and Using WebLogic jDriver for Oracle 49

2 Using WebLogic jDriver for Oracle

Note that the default size of an Oracle stored procedure string is 256K.

Notes on using CallableStatement

The default length of a string bound to an OUTPUT parameter of a CallableStatementis 128 characters. If the value you assign to the bound parameter exceeds that length,you'll get the following error:

ORA-6502: value or numeric error

You can adjust the length of the value of the bound parameter by passing an explicitlength with the scale argument to theCallableStatement.registerOutputParameter() method. Here is a codeexample that binds a VARCHAR that will never be larger than 256 characters:

CallableStatement cstmt =conn.prepareCall("BEGIN testproc(?); END;");

cstmt.registerOutputParameter(1, Types.VARCHAR, 256);cstmt.execute();System.out.println(cstmt.getString());cstmt.close();

Notes on DatabaseMetaData methods

There are some variations in the implementation of DatabaseMetaData methods thatare specific to Oracle and are detailed here:

� As a general rule, the String catalog argument is ignored in allDatabaseMetaData methods.

� In the DatabaseMetaData.getProcedureColumns() method:

� The String catalog argument is ignored.

� The String schemaPattern argument accepts only exact matches (no patternmatching).

� The String procedureNamePattern argument accepts only exact matches (nopattern matching).

� The String columnNamePattern argument is ignored.

50 Installing and Using WebLogic jDriver for Oracle

JDBC 2.0 for Oracle

JDBC 2.0 for Oracle

Overview

The JDBC 2.0 specification defines new functionality that was not available in earlierversions of JDBC, some of which is not yet supported by current DBMS products andtherefore has not been implemented in this driver.

New JDBC 2.0 features implemented in this driver:

� BLOBs (Binary Large Objects).WebLogic jDriver for Oracle can now handle this Oracle data type.

� CLOBs (Character Large Objects)WebLogic jDriver for Oracle can now handle this Oracle data type.

� Character Streams, for both ASCII and Unicode characters.A better way to handle characters streams—as streams of characters, not bytearrays.

� Batch UpdatesYou can now send multiple statements to the database as a single unit.

The above features are available in addition to all of the existing JDBC functionalitypreviously available in the WebLogic jDriver for Oracle. All of your existing code forprevious drivers will work with this new driver. athttp://www.weblogic.com/docs51/classdocs/API_joci.html.

Configuration

Since JDBC 2.0 is a Java 2 specification, you must run WebLogic jDriver for Oraclein a Java 2 environment. This means using one of the BEA supported Java VirtualMachines, such as JDK 1.2.x to run your JDBC clients. For a complete list of supportedconfigurations, see the WebLogic Platform support page athttp://www.weblogic.com/docs51/platforms/index.html.

Installing and Using WebLogic jDriver for Oracle 51

2 Using WebLogic jDriver for Oracle

If you will be using JDBC 2.0 features of WebLogic jDriver for Oracle in a multitierenvironment with the WebLogic RMI, T3, JTS, or pool drivers, then you must run yourWebLogic Server in a JDK 1.2.x JVM.

Driver class

The class name for the WebLogic jDriver for Oracle JDBC 2.0 driver is:

weblogic.jdbc20.oci.Driver

Driver URL

The URL for the WebLogic jDriver for Oracle JDBC 2.0 driver is:

jdbc20:weblogic:oracle

Overview of BLOBs and CLOBs

The BLOB (Binary Large Object) and CLOB (Character Large Object) data typeswere made available with the release of Oracle version 8. The JDBC 2.0 specificationand WebLogic jDriver for Oracle also support these data types. This section containsinformation on using these data types.

Transaction boundaries

BLOBs or CLOBs in Oracle behave differently than other data types in regards totransactional boundaries (statements issued before a SQL commit or rollbackstatement). in that a BLOB or CLOB will be come inactive as soon as a transaction iscommitted. If AutoCommit is set to TRUE, the transaction will be automaticallycommitted after each command issued on the connection, including SELECTstatements. For this reason you will need to set AutoCommit to false if you need tohave a BLOB or CLOB available across multiple SQL statements. You will then needto manually commit (or rollback) the transactions at the appropriate time. To setAutoCommit to false, issue the following command:

conn.setAutoCommit(false); // where conn is your connection object

52 Installing and Using WebLogic jDriver for Oracle

JDBC 2.0 for Oracle

BLOBs

The BLOB data type, available with Oracle version 8, allows you to store and retrievelarge binary objects in an Oracle table. Although BLOBs are defined as part of theJDBC 2.0 specification, the specification does not provide methods to update BLOBcolumns in a table. The BEA WebLogic implementation of BLOBs, however, doesprovide this functionality by means of an extension to JDBC 2.0.

Connection properties

weblobic.oci.selectBlobChunkSize

This property sets the size of an internal buffer used for sending bytes orcharacters to an I/O stream. When the Chunk size is reached, the driver willperform an implicit flush() operation, which will cause the data to be sentto the DBMS.

Explicitly setting this value can be useful in controlling memory usage on theclient.

If the value of this property is not explicitly set, a default value of 65534 willbe used.

Set this property by passing it to the Connection object as a property. Forexample, this code fragment sets weblobic.oci.selectBlobChunkSize to1200:

Properties props = new Properties();props.put("user", "scott");props.put("password", "tiger");props.put("server", "DEMO");

props.put ("weblobic.oci.selectBlobChunkSize","1200");

Driver myDriver = (Driver)Class.forName("weblogic.jdbc20.oci.Driver").newInstance();

Connection conn =driver.connect("jdbc20:weblogic:oracle:myServer", props);

weblogic.oci.insertBlobChunkSize

This property specifies the buffer size (in bytes) of input streams usedinternally by the driver.

Installing and Using WebLogic jDriver for Oracle 53

2 Using WebLogic jDriver for Oracle

Set this property to a positive integer to insert Blobs into an Oracle DBMSwith the Blob chunking feature. By default, this property is set to zero (0),which means that BLOB chunking is turned off.

Import statements

To use the BLOB functionality described in this section, import the following classesin your client code:

import java.sql.*;import java.util.*;import java.io.*;import weblogic.jdbc20.common.*;

Initializing a BLOB field

When you first insert a row containing a BLOB data type, you must insert the row withan “empty” BLOB before the field can be updated with real data. You can insert anempty BLOB with the Oracle EMPTY_BLOB() function.

To initialize a BLOB field:

1. Create a table with one or more columns defined as a BLOB data type.

2. Insert a new row with an empty BLOB column, using the Oracle EMPTY_BLOB()function:

stmt.execute("INSERT into myTable values (1,EMPTY_BLOB()");

3. Obtain a “handle” to the BLOB column:

java.sql.Blob myBlob = null;Statement stmt2 = conn.createStatement();stmt2.execute("SELECT myBlobColumn from myTable");ResultSet rs = stmt2.getResultSet();rs.next() {myBlob = rs.getBlob("myBlobColumn");// do something with the BLOB

}

4. You can now write data to the BLOB. Continue with the next section, Writingbinary data to a BLOB.

54 Installing and Using WebLogic jDriver for Oracle

JDBC 2.0 for Oracle

Writing binary data to a BLOB

To write binary data to a BLOB column:

1. Obtain a handle to the BLOB field as described above, in Initializing a BLOB field,step 3.

2. Create a InputStream object containing the binary data.

java.io.InputStream is = // create your input stream

3. Create an output stream to which you write your BLOB data. Note that you mustcast your BLOB object to weblogic.jdbc20.common.OracleBlob.

java.io.OutputStream os =((weblogic.jdbc20.common.OracleBlob)myBlob).getBinaryOutputStream();

4. Write the input stream containing your binary data to the output stream. Thewrite operation is finalized when you call the flush() method on theOutputStream object.

byte[] inBytes = new byte[65534]; // see note belowint numBytes = is.read(inBytes);while (numBytes > 0) {os.write(inBytes, 0, numBytes);numBytes = is.read(inBytes);

}os.flush();

Note: The value [65534] in the above code presumes that you have not set theweblogic.oci.select.BlobChunkSize property whose default is65534. If you have set this property, setting the byte[] value to match thevalue set in the weblogic.oci.select.BlobChunkSize property

will provide the most efficient handling of the data. For more informationon this property, see Connection properties on page 53.

5. Clean up:

os.close();pstmt.close();conn.close();

Writing a BLOB object

Writing a BLOB object to a table is performed with Prepared Statements. For example,to write the myBlob object to the table myOtherTable:

Installing and Using WebLogic jDriver for Oracle 55

2 Using WebLogic jDriver for Oracle

PreparedStatement pstmt = conn.preparedStatement("UPDATE myOtherTable SET myOtherBlobColumn = ? WHERE id = 12");

pstmt.setBlob(1, myBlob);

Reading BLOB data

When you retrieve a BLOB column with the getBlob() method and then use aResultSet from a SQL SELECT statement, only a pointer to the BLOB data isreturned; the binary data is not actually transferred to the client until thegetBinaryStream() method is called and the data is read into the stream object.

To read BLOB data from an Oracle table:

1. Execute a SELECT statement:

stmt2.execute("SELECT myBlobColumn from myTable");

2. Use the results from the SELECT statement.

int STREAM_SIZE = 10;byte[] r = new byte[STREAM_SIZE];

ResultSet rs = stmt2.getResultSet();java.sql.Blob myBlob = null;while (rs.next) {myBlob = rs.getBlob("myBlobColumn");

java.io.InputStream readis = myBlob.getBinaryStream();

for (int i=0 ; i < STREAM_SIZE ; i++) {r[i] = (byte) readis.read();System.out.println("output [" + i + "] = " + r[i]);

}

3. Clean up:

rs.close();stmt2.close();

Note: You can also use a CallableStatement to generate a ResultSet. ThisResultSet can then be used as shown above. See your JDK documentationunder java.sql.CallableStatment for details.

56 Installing and Using WebLogic jDriver for Oracle

JDBC 2.0 for Oracle

Other methods

The following methods of the java.sql.Blob interface are also implemented in theWebLogic jDriver for Oracle JDBC 2.0 driver. For details, see your JDKdocumentation:

� getBinaryStream()

� getBytes()

� length()

The position() method is not implemented.

CLOBs

The CLOB data type, available with Oracle version 8, enables storage of largecharacter strings in an Oracle table. Since the JDBC 2.0 specification does not includefunctionality to directly update CLOB columns, BEA has implemented the methodsgetAsciiOutputStream() (for ASCII data) and getCharacterOutputStream()

(for Unicode data) to insert or update a CLOB.

Codeset support

Depending on which version of the Oracle Server and client you are using you mayneed to set one of the following properties by passing them to the Connection objectwhen you establish your connection the DBMS in your Java client code.

weblogic.codeset

This property allows you to set a codeset from within your Java code. Thiscodeset overrides the value of any codeset specified with the Oracleenvironment variable NLS_LANG.

weblogic.oci.ncodeset

This property sets the National codeset used by the Oracle server. Thiscodeset overrides the value of any codeset specified with the Oracleenvironment variable NLS_NCHAR.

weblogic.oci.codeset_width

This property tells the WebLogic jDriver for Oracle which type you are using.Note the following restrictions on codeset use:

Installing and Using WebLogic jDriver for Oracle 57

2 Using WebLogic jDriver for Oracle

Oracle Version 8.0.5: only fixed width character sets are supportedOracle Version 8.1.5 and later: character sets may be either fixed orvariable width.

Possible Values:0 (for variable-width codesets)1 (for fixed-width codesets; this is the default value)2 or 3 (the width, in bytes of the codeset)

weblogic.oci.ncodeset_width

If you are using one of Oracle’s National codesets, specify the width of thatcodeset with this property. Note the following restrictions on codeset use:

Oracle Version 8.0.5: only fixed width character sets are supportedOracle Version 8.1.5 and later: character sets may be either fixed orvariable width.

Possible Values:0 (for variable-width codesets)1 (for fixed-width codesets; this is the default value)2 or 3 (the width, in bytes, of the codeset)

weblogic.oci.use_clob_unicode_io

When using CLOBS in conjunction with a character set on the Oracle server(this applies to Client version 8.1.5 only), WebLogic jDriver for Oracleconverts the characters from Unicode to the character set in use by thedatabase. The Oracle server then converts this data back into Unicode. Thisobvious inefficiency can be avoided by setting this property to true, in whichcase all communication will be made in Unicode, preventing unnecessary andexpensive character set translations from occurring. The default value for thisproperty is false.

Initializing a CLOB field

When you first insert a row containing a CLOB data type, you must insert the row withan “empty” CLOB before the field can be updated with real data. You can insert anempty CLOB with the Oracle EMPTY_CLOB() function.

To initialize a CLOB column:

1. Create a table with one or more columns defined as a CLOB data type.

2. Insert a new row with an empty CLOB column, using the Oracle EMPTY_CLOB()function:

stmt.execute("INSERT into myTable VALUES (1,EMPTY_CLOB()");

58 Installing and Using WebLogic jDriver for Oracle

JDBC 2.0 for Oracle

3. Obtain an object for the CLOB column:

java.sql.Clob myClob = null;Statement stmt2 = conn.createStatement();stmt2.execute("SELECT myClobColumn from myTable");ResultSet rs = stmt2.getResultSet();while (rs.next) {myClob = rs.getClob("myClobColumn");

}

4. You can now write character data to the CLOB. If your data is in the ASCIIformat, Continue with the next section, Writing ASCII data to a CLOB. If yourcharacter data is in Unicode format, see Writing Unicode data to a CLOB

Writing ASCII data to a CLOB

To write ASCII character data to a CLOB column:

1. Obtain a “handle” to the CLOB as described above, in Initializing a CLOB field,step 3.

2. Create an object containing the character data:

String s = // some ASCII data

3. Create an ASCII output stream to which you write your CLOB characters. Notethat you must cast your CLOB object toweblogic.jdbc20.common.OracleClob.

java.io.OutputStream os =((weblogic.jdbc20.common.OracleClob)myclob).getAsciiOutputStream();

4. Write the input stream containing your ASCII data to the output stream. Thewrite operation is finalized when you call the flush() method on theOutputStream object.

byte[] b = s.getBytes("ASCII");

os.write(b);os.flush();

5. Clean up:

os.close();pstmt.close();conn.close();

Installing and Using WebLogic jDriver for Oracle 59

2 Using WebLogic jDriver for Oracle

Writing Unicode data to a CLOB

To write Unicode character data to a CLOB column:

1. Obtain a “handle” to the CLOB as described above, in Initializing a CLOB field,step 3.

2. Create an object containing the character data:

String s = // some Unicode character data

3. Create a character output stream to which you write your CLOB characters. Notethat you must cast your CLOB object toweblogic.jdbc20.common.OracleClob.

java.io.Writer wr =((weblogic.jdbc20.common.OracleClob)myclob).getCharacterOutputStream();

4. Write the input stream containing your ASCII data to the output stream. Thewrite operation is finalized when you call the flush() method on theOutputStream object.

char[] b = s.toCharArray(); // converts ’s’ to a character array

wr.write(b);wr.flush();

5. Clean up:

wr.close();pstmt.close();conn.close();

Writing CLOB objects

Writing a CLOB object to a table is performed with Prepared Statements. For example,to write the myClob object to the table myOtherTable:

PreparedStatement pstmt = conn.preparedStatement("UPDATE myOtherTable SET myOtherClobColumn = ? WHERE id = 12");

pstmt.setClob(1, myClob);

60 Installing and Using WebLogic jDriver for Oracle

JDBC 2.0 for Oracle

Reading CLOB data

When a CLOB column is retrieved using a result set from a SQL SELECT statement,only a pointer to the CLOB data is returned; the actual data is not transferred to theclient with the result set until the getAsciiStream() method is called and thecharacters are read in to the stream.

To read CLOB data from an Oracle table:

1. Execute a SELECT statement:

java.sql.Clob myClob = null;Statement stmt2 = conn.createStatement();stmt2.execute("SELECT myClobColumn from myTable");

2. Use the results from the SELECT statement:

ResultSet rs = stmt2.getResultSet();

while (rs.next) {myClob = rs.getClob("myClobColumn");java.io.InputStream readClobis =

myReadClob.getAsciiStream();char[] c = new char[26];for (int i=0 ; i < 26 ; i++) {

c[i] = (char) readClobis.read();System.out.println("output [" + i + "] = " + c[i]);

}}

3. Clean up:

rs.close();stmt2.close();

Note: You can also use a CallableStatement to generate a ResultSet. ThisResultSet can then be used as shown above. See your JDK documentationunder java.sql.CallableStatment for details.

Other methods

The following methods of the java.sql.Clob interface are also implemented in theWebLogic jDriver for Oracle JDBC 2.0 driver. For details, see your JDKdocumentation:

Installing and Using WebLogic jDriver for Oracle 61

2 Using WebLogic jDriver for Oracle

� getSubString()

� length()

The position() method is not implemented.

Character and ASCII Streams

Some new methods are included in the JDBC 2.0 specification that allow character andASCII streams to be manipulated as characters rather than as bytes, as wasimplemented in earlier versions. The following methods for handling character andASCII streams are implemented in WebLogic jDriver for Oracle.

Unicode character Streams

getCharacterStream()

The java.sql.ResultSet interface uses this method for reading Unicodestreams as the Java type java.io.Reader. This method replaces thedeprecated getUnicodeStream() method.

setCharacterStream()

The java.sql.PreparedStatement interface uses this method for writinga java.io.Reader object. This method replaces the deprecatedsetUnicodeStream() method.

ASCII character streams

getAsciiStream()

The java.sql.ResultSet interface uses this method for reading ASCIIstreams as the Java type java.io.InputStream.

setAsciiStream()

The java.sql.PreparedStatement interface uses this method for writinga java.io.InputStream object.

For details on using these methods, consult your JDK documentation.

62 Installing and Using WebLogic jDriver for Oracle

JDBC 2.0 for Oracle

Batch updates

Batch updates are a new feature of JDBC 2.0 that allows you to send multiple SQLupdate statements to the DBMS as a single unit. Depending on the application, this canprovide improved performance over sending multiple update statements individually.The Batch update feature is available in the Statement interface and requires the useof SQL statements that return an update count and do not return a result set. UsingBatch updates with the callableStatement or preparedStatement is notsupported.

The following SQL statements can be used with Batch updates:

� INSERT INTO

� UPDATE

� DELETE

� CREATE TABLE

� DROP TABLE

� ALTER TABLE

Using Batch updates

This is the basic procedure for using Batch updates:

1. Get a connection using the WebLogic jDriver for Oracle JDBC 2.0 driver asdescribed in Connecting to an Oracle DBMS on page 25. For this example, theconnection object is called “conn”.

2. Create a statement object using the createStatement() method. For example:

Statement stmt = conn.createStatement();

3. Use the addBatch() method to add SQL statements to the batch. Thesestatements will not be sent to the DBMS until the executeBatch() method iscalled. For example:

stmt.addBatch("INSERT INTO batchTest VALUES ('JOE', 20,35)");stmt.addBatch("INSERT INTO batchTest VALUES ('Bob', 30,44)");stmt.addBatch("INSERT INTO batchTest VALUES ('Ed', 34,22)");

4. Use the executeBatch() method to send the batch to the DBMS for processing.For example:

Installing and Using WebLogic jDriver for Oracle 63

2 Using WebLogic jDriver for Oracle

stmt.executeBatch();

If any of the statements fail an exception will be thrown, and none of thestatements will be executed.

Clearing the batch

You may clear a batch of statements that was created using addBatch() method withthe clearBatch() method. For example:

stmt.clearBatch();

Update counts

According to the JDBC 2.0 specification, the executeBatch() method should returnan array of Integers containing the number of rows updated for each Statement. TheOracle DBMS, however, does not supply this information to the driver. The OracleDBMS will instead return -2 for all updates.

Using with JDBC 1

If you are running your client application (or WebLogic Server, if WebLogic jDriverfor Oracle is being used in the middle tier) under JDK 1.1, you may use Batch updatesby casting your Statement object to weblogic.jdbc.oci.Statement. For example:

weblogic.jdbc.oci.Statement stmt =(weblogic.jdbc.oci.Statement) conn.createStatement();

64 Installing and Using WebLogic jDriver for Oracle

JDBC 2.0 for Oracle

New date methods

The following methods have a new signature which takes a java.util.Calendarobject as a parameter. java.util.Calendar allows you to specify time zone andlocation information that is used to translate dates. Consult your JDK API guide fordetails on using the java.util.Calendar class.

java.sql.ResultSet.getDate(int columnIndex, Calendar cal)

(returns a java.sql.Date object)

java.sql.PreparedStatement.setDate(int parameterIndex, Date x, Calendar cal)

java.sql.CallableStatement.getDate(int parameterIndex, Calendar cal)

(returns a java.sql.Date object)

Installing and Using WebLogic jDriver for Oracle 65

2 Using WebLogic jDriver for Oracle

Resources

For more information about

� using BLOBS and CLOBS, see the article Using SQL3 Datatypes, from Sun’sJava Tutorial, available athttp://java.sun.com/docs/books/tutorial/jdbc/jdbc2dot0/sql3.html.

� WebLogic Server and JNDI, see Using WebLogic JNDI, athttp://www.weblogic.com/docs51/classdocs/API_jndi.html.

� installing WebLogic JDBC drivers, see Installing JDBC Drivers, athttp://www.weblogic.com/docs51/install/install_jdbc.html.

� the JDBC 2.0 specification, see New Features in the JDBC 2.0 API, athttp://java.sun.com/docs/books/tutorial/jdbc/jdbc2dot0/index.html.

Code Examples

Oracle examples

Examples using JDBC 2.0 featuresBatch UpdatesBlobs and Clobs

66 Installing and Using WebLogic jDriver for Oracle

Upgrade

3 Release Notes for WebLogic jDriver for Oracle

Upgrade

This driver is now called WebLogic jDriver for Oracle. Its former name wasjdbcKona/Oracle.

WebLogic jDriver for Oracle has been updated to incorporate some of the featuresavailable in Oracle 8, such as Blobs and Clobs, and also for new features available inthe JDBC 2.0 specification (using JDBC 2.0 requires that you run your driver with aJDK 1.2.x JVM).

These changes require a different setting for your system PATH orld_library_path. For details, see Setting your path and client libraries on page 12.

WebLogic jDriver for Oracle is not available on all platforms in this release. SeeSetting your path and client libraries on page 12 for details.

Changes

jDriver for Oracle available for the HP-UX 11 platform.

Installing and Using WebLogic jDriver for Oracle 67

3 Release Notes for WebLogic jDriver for Oracle

WebLogic jDriver for Oracle (formerly called jdbcKona/Oracle) is now available forthe HP-UX 11 platform for Oracle client versions 8.0.4, 8.0.5, and 8.1.5. There aresome restrictions on its use. For more information, see Issues on page 68 and InstallingWebLogic jDriver for Oracle athttp://www.weblogic.com/docs51/install/install_jdbc.html.

For information on using new Oracle 8 and JDBC 2.0 features, see the DeveloperGuides Using jdbcKona/Oracle athttp://www.weblogic.com/docs51/classdocs/API_joci.html.

WebLogic jDriver for Oracle: Blobs and Clobs

The procedure for using Oracle Blobs and Clobs requires that you cast the Blob or Clobobject to weblogic.jdbc20.common.OracleClob orweblogic.jdbc20.common.OracleBlob.

Issues

Issue 9431.

WebLogic jDriver for Oracle is not supported when using the Oracle 8 APIand connecting to an version 7 Oracle DBMS.

Issue 9283

CallableStatement.getResultSet()with a defined ResultSet Cursor doesnot work when using the Oracle 8.1.5 DBMS on the Solaris operating system.

When using Oracle client version 8.0.5 and executing a CallableStatementwith a defined ResultSet Cursor, you must re-register the cursor prior to eachCallableStatement.getResultSet() call. For example:

weblogic.jdbc.common.OracleCallableStatement cstmt2 =(weblogic.jdbc.common.OracleCallableStatement)conn.prepareCall("{CALL single_cursor(?, ?)}");

cstmt2.registerOutParameter(1, java.sql.Types.OTHER);

// You can also set input parameters, execute the statement,// retrieve the query into a ResultSet, and print it// for each set of input parameters.

68 Installing and Using WebLogic jDriver for Oracle

Issues

System.out.println("FIRST sproc 'single_cursor' exec for INT==1\n\n\n\n");

cstmt2.setInt(2, 1);cstmt2.execute();rs = cstmt2.getResultSet(1);

System.out.println("FIRST sproc 'single_cursor' exec forINT==2\n\n\n\n");

// Add the following line to re-register the cursor:cstmt2.registerOutParameter(1, java.sql.Types.OTHER);

cstmt2.setInt(2, 2);cstmt2.execute();rs = cstmt2.getResultSet(1);

Cross-platform incompatibility when using Oracle 8.0.5 and 8.1.5 clients running onHP.

The following combinations are known to be incompatible:

� Oracle 8.0.5 Client running on HP connecting to an Oracle 8.1.5 DBMSrunning on Windows NT or Solaris.

� Oracle 8.1.5 client running on HP connecting to an Oracle 8.1.5 DBMSrunning on Solaris.

Issue 9708

Using the CLOB datatype and using codeset conversions while running theOracle client and Oracle server on different operating systems will fail.

Issue 10026

jDriver for Oracle is only supported on HP when the Oracle client and Oracleserver are the same version. For example, an Oracle 8.0.5 client is onlysupported when connecting to an Oracle 8.0.5 server.

Installing and Using WebLogic jDriver for Oracle 69

3 Release Notes for WebLogic jDriver for Oracle

70 Installing and Using WebLogic jDriver for Oracle