Vous êtes sur la page 1sur 204
Programmer’s Reference jConnect™ for JDBC™ 6.05

Programmer’s Reference

jConnect™ for JDBC™

6.05

DOCUMENT ID: DC39001-01-0605-02

LAST REVISED: August 2006

Copyright © 1997-2005 by Sybase, Inc. All rights reserved.

This publication pertains to Sybase software and to any subsequent release until otherwise indicated in new editions or technical notes. Information in this document is subject to change without notice. The software described herein is furnished under a license agreement, and it may be used or copied only in accordance with the terms of that agreement.

To order additional documents, U.S. and Canadian customers should call Customer Fulfillment at (800) 685-8225, fax (617) 229-9845.

Customers in other countries with a U.S. license agreement may contact Customer Fulfillment via the above fax number. All other international customers should contact their Sybase subsidiary or local distributor. Upgrades are provided only at regularly scheduled software release dates. No part of this publication may be reproduced, transmitted, or translated in any form or by any means, electronic, mechanical, manual, optical, or otherwise, without the prior written permission of Sybase, Inc.

Sybase, the Sybase logo, ADA Workbench, Adaptable Windowing Environment, Adaptive Component Architecture, Adaptive Server, Adaptive Server Anywhere, Adaptive Server Enterprise, Adaptive Server Enterprise Monitor, Adaptive Server Enterprise Replication, Adaptive Server Everywhere, Adaptive Warehouse, Afaria, Answers Anywhere, Anywhere Studio, Application Manager, AppModeler, APT Workbench, APT-Build, APT-Edit, APT-Execute, APT-Translator, APT-Library, AvantGo Mobile Delivery, AvantGo Mobile Inspection, AvantGo Mobile Marketing Channel, AvantGo Mobile Pharma, AvantGo Mobile Sales, AvantGo Pylon, AvantGo Pylon Application Server, AvantGo Pylon Conduit, AvantGo Pylon PIM Server, AvantGo Pylon Pro, Backup Server, BizTracker, ClearConnect, Client-Library, Client Services, Convoy/DM, Copernicus, Data Pipeline, Data Workbench, DataArchitect, Database Analyzer, DataExpress, DataServer, DataWindow, DataWindow .NET, DB-Library, dbQueue, Developers Workbench, DirectConnect, DirectConnect Anywhere, Distribution Director, e-ADK, E-Anywhere, e-Biz Impact, e-Biz Integrator, E-Whatever, EC Gateway, ECMAP, ECRTP, eFulfillment Accelerator, Embedded SQL, EMS, Enterprise Application Studio, Enterprise Client/Server, Enterprise Connect, Enterprise Data Studio, Enterprise Manager, Enterprise SQL Server Manager, Enterprise Work Architecture, Enterprise Work Designer, Enterprise Work Modeler, eProcurement Accelerator, EWA, Financial Fusion, Financial Fusion Server, Gateway Manager, GlobalFIX, iAnywhere, iAnywhere Solutions, ImpactNow, Industry Warehouse Studio, InfoMaker, Information Anywhere, Information Everywhere, InformationConnect, InternetBuilder, iScript, Jaguar CTS, jConnect for JDBC, M2M Anywhere, Mach Desktop, Mail Anywhere Studio, Mainframe Connect, Maintenance Express, Manage Anywhere Studio, M-Business Channel, M-Business Network, M-Business Server, MDI Access Server, MDI Database Gateway, media.splash, MetaWorks, mFolio, Mirror Activator, MySupport, Net- Gateway, Net-Library, New Era of Networks, ObjectConnect, ObjectCycle, OmniConnect, OmniSQL Access Module, OmniSQL Toolkit, Open Biz, Open Client, Open ClientConnect, Open Client/Server, Open Client/Server Interfaces, Open Gateway, Open Server, Open ServerConnect, Open Solutions, Optima++, PB-Gen, PC APT Execute, PC DB-Net, PC Net Library, PocketBuilder, Pocket PowerBuilder, Power++, power.stop, PowerAMC, PowerBuilder, PowerBuilder Foundation Class Library, PowerDesigner, PowerDimensions, PowerDynamo, PowerScript, PowerSite, PowerSocket, Powersoft, PowerStage, PowerStudio, PowerTips, Powersoft Portfolio, Powersoft Professional, PowerWare Desktop, PowerWare Enterprise, ProcessAnalyst, QAnywhere, Rapport, RemoteWare, RepConnector, Replication Agent, Replication Driver, Replication Server, Replication Server Manager, Replication Toolkit, Report- Execute, Report Workbench, Resource Manager, RFID Anywhere, RW-DisplayLib, RW-Library, S-Designor, SDF, Secure SQL Server, Secure SQL Toolset, Security Guardian, SKILS, smart.partners, smart.parts, smart.script, SQL Advantage, SQL Anywhere, SQL Anywhere Studio, SQL Code Checker, SQL Debug, SQL Edit, SQL Edit/TPU, SQL Everywhere, SQL Modeler, SQL Remote, SQL Server, SQL Server Manager, SQL SMART, SQL Toolset, SQL Server/CFT, SQL Server/DBM, SQL Server SNMP SubAgent, SQL Station, SQLJ, STEP, SupportNow, S.W.I.F.T. Message Format Libraries, Sybase Central, Sybase Client/Server Interfaces, Sybase Financial Server, Sybase Gateways, Sybase IQ, Sybase MPP, Sybase SQL Desktop, Sybase SQL Lifecycle, Sybase SQL Workgroup, Sybase User Workbench, SybaseWare, Syber Financial, SyberAssist, SybFlex, SyBooks, System 10, System 11, System XI (logo), SystemTools, Tabular Data Stream, TradeForce, Transact-SQL, Translation Toolkit, UltraLite, UltraLite.NET, UNIBOM, Unilib, Uninull, Unisep, Unistring, URK Runtime Kit for UniCode, VisualWriter, VQL, WarehouseArchitect, Warehouse Control Center, Warehouse Studio, Warehouse WORKS, Watcom, Watcom SQL, Watcom SQL Server, Web Deployment Kit, Web.PB, Web.SQL, WebSights, WebViewer, WorkGroup SQL Server, XA-Library, XA-Server, XcelleNet, and XP Server are trademarks of Sybase, Inc.

02/05

Unicode and the Unicode Logo are registered trademarks of Unicode, Inc.

All other company and product names used herein may be trademarks or registered trademarks of their respective companies.

Use, duplication, or disclosure by the government is subject to the restrictions set forth in subparagraph (c)(1)(ii) of DFARS 52.227-7013 for the DOD and as set forth in FAR 52.227-19(a)-(d) for civilian agencies.

Sybase, Inc., One Sybase Drive, Dublin, CA 94568.

Contents

About This Book

vii

CHAPTER 1

Introduction

1

What is JDBC?

1

What is jConnect?

2

CHAPTER 2

Programming Information

5

Setting up jConnect

5

Setting the jConnect version

5

Invoking the jConnect driver

11

Establishing a connection

12

Setting connection properties

12

Connecting to Adaptive Server

24

Connecting to a server using JNDI

26

Implementing custom socket plug-ins

32

Creating and configuring a custom socket

33

Handling internationalization and localization

36

Using jConnect to pass Unicode data

36

jConnect character-set converters

38

Working with databases

43

Implementing high availability failover support

44

Performing server-to-server remote procedure calls

48

Using wide table support for ASE 12.5 and later

50

Accessing database metadata

50

Using cursors with result sets

52

Support for batch updates

62

Updating a database from a result set of a stored procedure . 64

Working with datatypes

65

Implementing advanced features

71

Using event notification

72

Handling error messages

74

Storing Java objects as column data in a table

79

Using dynamic class loading

83

Contents

JDBC 2.0 optional package extensions support

87

Restrictions on and interpretations of JDBC standards

98

Using JDBC 3.0 method stubs

99

Using Connection.isClosed and IS_CLOSED_TEST

99

Using Statement.close with unprocessed results

100

Making adjustments for multithreading

101

Using ResultSet.getCursorName

101

Using setLong with large parameter values

102

New datatypes supported

102

Using COMPUTE statements

103

Executing stored procedures

103

CHAPTER 3

Security

107

Overview

107

Restrictions

108

SSL

108

Kerberos

108

Configuring jConnect applications for Kerberos

109

GSSMANAGER_CLASS connection property

109

Setting up the Kerberos environment

112

Sample applications

114

Interoperability

117

Troubleshooting

118

Related documents

118

CHAPTER 4

Troubleshooting

121

Debugging with jConnect

121

Obtaining an instance of the Debug class

121

Turning on debugging in your application

122

Turning off debugging in your application

122

Setting the CLASSPATH for debugging

123

Using the Debug methods

123

Capturing TDS communication

124

PROTOCOL_CAPTURE connection property

125

pause and resume methods in the Capture class

125

Resolving connection errors

126

Gateway connection refused

126

Unable to connect to a 4.9.2 SQL Server

127

Managing memory in jConnect applications

127

Resolving stored procedure errors

128

RPC returns fewer output parameters than registered

128

Fetch/state errors when output parameters are returned

129

Stored procedure executed in unchained transaction mode. 129

Contents

Resolving a custom socket implementation error

129

CHAPTER 5

Performance and Tuning

131

Improving jConnect performance

131

BigDecimal rescaling

132

REPEAT_READ connection property

132

SunIoConverter character-set conversion

133

Performance tuning for prepared statements in dynamic SQL

134

Choosing prepared statements and stored procedures

135

Prepared statements in portable applications

135

Prepared statements with jConnect extensions

136

Connection.prepareStatement

137

DYNAMIC_PREPARE connection property

137

SybConnection.prepareStatement

139

ESCAPE_PROCESSING_DEFAULT connection property

140

Cursor performance

140

LANGUAGE_CURSOR connection property

140

CHAPTER 6

Migrating jConnect Applications

143

Migrating applications to jConnect 6.x

143

Changing Sybase extensions

144

Extension change example

144

Method names

145

Debug class

145

CHAPTER 7

Web Server Gateways

147

About Web server gateways

147

Using TDS tunnelling

147

Configuring jConnect and gateways

148

Usage requirements

152

Reading the index.html file

153

Running the sample Isql applet

153

Using the TDS-tunnelling servlet

154

Reviewing requirements

155

Installing the servlet

156

Invoking the servlet

157

Tracking active TDS sessions

157

Resuming a TDS session

158

Using TDS and Netscape Enterprise Server 3.5.1 on Solaris 158

APPENDIX A

SQL Exception and Warning Messages

161

Contents

APPENDIX B

jConnect Sample Programs

183

 

Running IsqlApp

183

Running jConnect sample programs and code

185

Sample applications

186

Sample code

187

Index

189

About This Book

Audience

Related Documents

Other sources of information

The Sybase jConnect for JDBC Programmer’s Reference describes the jConnect™ for JDBC™ product and explains how to use it to access data stored in relational database management systems.

This manual is for database-application programmers who are familiar with the Java programming language, JDBC, and Transact-SQL ® , the Sybase ® version of Structured Query Language (SQL).

You may find the following documents helpful:

• The Sybase jConnect for JDBC Installation Guide

• The Sybase jConnect for JDBC Release Bulletin

• The javadoc documentation of jConnect extensions to JDBC. The Java Development Kit (JDK) from Java Software contains a javadoc script for extracting comments from source-code files. This script has been used to extract documentation of jConnect packages, classes, and methods from jConnect source files. When you install jConnect using the full installation or javadocs option, the javadoc information is placed in the javadocs directory:

Installation_directory/docs/en/javadocs

Use the Sybase Getting Started CD, the SyBooks™ CD, and the Sybase Product Manuals Web site to learn more about your product:

• The Getting Started CD contains release bulletins and installation guides in PDF format, and may also contain other documents or updated information not included on the SyBooks CD. It is included with your software. To read or print documents on the Getting Started CD, you need Adobe Acrobat Reader, which you can download at no charge from the Adobe Web site using a link provided on the CD.

• The SyBooks CD contains product manuals and is included with your software. The Eclipse-based SyBooks browser allows you to access the manuals in an easy-to-use, HTML-based format.

Some documentation may be provided in PDF format, which you can access through the PDF directory on the SyBooks CD. To read or print the PDF files, you need Adobe Acrobat Reader.

Refer to the SyBooks Installation Guide on the Getting Started CD, or the README.txt file on the SyBooks CD for instructions on installing and starting SyBooks.

• The Sybase Product Manuals Web site is an online version of the SyBooks CD that you can access using a standard Web browser. In addition to product manuals, you will find links to EBFs/Maintenance, Technical Documents, Case Management, Solved Cases, newsgroups, and the Sybase Developer Network.

To access the Sybase Product Manuals Web site, go to Product Manuals at

Sybase certifications on the Web

Technical documentation at the Sybase Web site is updated frequently.

Finding the latest information on product certifications

1 Point your Web browser to Technical Documents at

http://www.sybase.com/support/techdocs/.

2 Select Products from the navigation bar on the left.

3 Select a product name from the product list and click Go.

4 Select the Certification Report filter, specify a time frame, and click Go.

5 Click a Certification Report title to display the report.

Finding the latest information on component certifications

1 Point your Web browser to Availability and Certification Reports at http://certification.sybase.com/.

2 Either select the product family and product under Search by Product; or select the platform and product under Search by Platform.

3 Select Search to display the availability and certification report for the selection.

Creating a personalized view of the Sybase Web site (including support pages)

Set up a MySybase profile. MySybase is a free service that allows you to create a personalized view of Sybase Web pages.

1 Point your Web browser to Technical Documents at

http://www.sybase.com/support/techdocs/.

2 Click MySybase and create a MySybase profile.

About This Book

Sybase EBFs and software maintenance

 

Finding the latest information on EBFs and software maintenance

 

1 Point your Web browser to the Sybase Support Page at http://www.sybase.com/support.

2 Select EBFs/Maintenance. If prompted, enter your MySybase user name and password.

3 Select a product.

4 Specify a time frame and click Go. A list of EBF/Maintenance releases is displayed.

Padlock icons indicate that you do not have download authorization for certain EBF/Maintenance releases because you are not registered as a Technical Support Contact. If you have not registered, but have valid information provided by your Sybase representative or through your support contract, click Edit Roles to add the “Technical Support Contact” role to your MySybase profile.

5 Click the Info icon to display the EBF/Maintenance report, or click the product description to download the software.

Conventions

This manual uses the following font and syntax conventions:

• Classes, interfaces, methods, and packages are shown in Helvetica within paragraph text. For example:

SybConnection class

SybEventHandler interface

setBinaryStream method

com.sybase.jdbcx package

• Objects, instances, and parameter names are shown in italics. For example:

“In the following example, ctx is a DirContext object.”

“eventHdler is an instance of the SybEventHandler class that you implement.”

“The classes parameter is a string that lists specific classes you want to debug.”

• Code fragments are shown in a monospaced font. Variables in code fragments (that is, words that stand for values that you fill in) are italicized. For example:

Connection con = DriverManager.getConnection("jdbc:

Accessibility

features

sybase:Tds: host:port ", props);

This document is available in an HTML version that is specialized for accessibility. You can navigate the HTML with an adaptive technology such as a screen reader, or view it with a screen enlarger.

<jConnect for JDBC> and the HTML documentation have been tested for compliance with U.S. government Section 508 Accessibility requirements. Documents that comply with Section 508 generally also meet non-U.S. accessibility guidelines, such as the World Wide Web Consortium (W3C) guidelines for Web sites.

The online help for this product is also provided in HTM, which you can navigate using a screen reader.

Note You might need to configure your accessibility tool for optimal use. Some screen readers pronounce text based on its case; for example, they pronounce ALL UPPERCASE TEXT as initials, and MixedCase Text as words. You might find it helpful to configure your tool to announce syntax conventions. Consult the documentation for your tool.

If you need help

For information about how Sybase supports accessibility, see Sybase

Accessibility at http://www.sybase.com/accessibility. The Sybase Accessibility

site includes links to information on Section 508 and W3C standards.

Each Sybase installation that has purchased a support contract has one or more designated people who are authorized to contact Sybase Technical Support. If you cannot resolve a problem using the manuals or online help, please have the designated person contact Sybase Technical Support or the Sybase subsidiary in your area.

CHAPTER

1

Introduction

This chapter introduces you to jConnect for JDBC and describes its concepts and components.

Topic

Page

What is JDBC?

1

What is jConnect?

2

What is JDBC?

JDBC (Java Database Connectivity), from the Java Software Division of Sun MicroSystems, Inc., is a specification for an application program interface (API) that allows Java applications to access multiple database management systems using Structured Query Language (SQL). The JDBC Driver Manager handles multiple drivers that connect to different databases.

A set of interfaces is included in the standard JDBC API so you can open connections to databases, execute SQL commands, and process results. The interfaces are described in Table 1-1.

What is jConnect?

Table 1-1: JDBC interfaces

Interface

Description

java.sql.Driver

Locates the driver for a database URL

java.sql.Connection

Used to connect to a specific database

java.sql.Statement

Executes SQL statements

java.sql.PreparedStatement

Handles SQL statements with parameters

java.sql.CallableStatement

Handles database stored procedure calls

java.sql.ResultSet

Gets the results of SQL statements

java.sql.DatabaseMetaData

Used to access information about a connection to a database.

java.sql.ResultSetMetaData

Used to access information describing the attributes of a ResultSet.

Each relational database management system requires a driver to implement these interfaces. There are four types of JDBC drivers:

Type 1 JDBC-ODBC bridge – translates JDBC calls into ODBC calls and passes them to an ODBC driver. Some ODBC software must reside on the client machine. Some client database code may also reside on the client machine.

Type 2 native-API partly-Java driver – converts JDBC calls into database- specific calls. This driver, which communicates directly with the database server, also requires some binary code on the client machine.

Type 3 net-protocol all-Java driver – communicates to a middle-tier server using a DBMS-independent net protocol. A middle-tier gateway then converts the request to a vendor-specific protocol.

Type 4 native-protocol all-Java driver – converts JDBC calls to the vendor-specific DBMS protocol, allowing client applications direct communication with the database server.

What is jConnect?

jConnect is the Sybase high-performance JDBC driver. jConnect is both:

• A net-protocol/all-Java driver within a three-tier environment, and

• A native-protocol/all-Java driver within a two-tier environment.

CHAPTER 1

Introduction

The protocol used by jConnect is TDS 5.0 (Tabular Data Stream™, version 5), the native protocol for Adaptive Server ® and Open Server™ applications. jConnect implements the JDBC standard to provide optimal connectivity to the complete family of Sybase products, allowing access to over 25 enterprise and legacy systems, including:

• Adaptive Server Enterprise

• Adaptive Server Anywhere™

• Adaptive Server IQ (formerly Sybase IQ™)

• Replication Server®

• DirectConnect™

Note Since changing the name of Sybase SQL Server™ to Adaptive Server Enterprise, Sybase may use the names Adaptive Server and Adaptive Server Enterprise to refer collectively to all supported versions of Sybase SQL Server and Adaptive Server Enterprise. From this point forward, in this document, Adaptive Server Enterprise is referred to as Adaptive Server.

In addition, jConnect for JDBC can access Oracle, AS/400, and other data sources using Sybase DirectConnect.

In some instances, the jConnect implementation of JDBC deviates from the JDBC 1.x, 2.x and 3.x specifications. For more information, see “Restrictions on and interpretations of JDBC standards” on page 98.

What is jConnect?

CHAPTER

2

Programming Information

This chapter describes the basic components and programming requirements that comprise jConnect for JDBC. It explains how to invoke the jConnect driver, set connection properties, and connect to a database server. It also contains information about using jConnect features.

Note For information about JDBC programming, go to http://java.sun.com/jdbc.

The following topics are included in this chapter:

Topic

Page

Setting up jConnect

5

Establishing a connection

12

Implementing custom socket plug-ins

32

Handling internationalization and localization

36

Working with databases

43

Implementing advanced features

71

Restrictions on and interpretations of JDBC standards

98

Setting up jConnect

This section describes the tasks you need to perform before you use jConnect.

Setting the jConnect version

There are several versions of jConnect. Use a version setting to determine:

• The default value of the LANGUAGE connection property

• The version-specific features that are available

Setting up jConnect

• The default character set, if no character set is specified through the CHARSET connection property

• The default value of the CHARSET_CONVERTER connection property

• The default value of the CANCEL_ALL connection property, which is used to set the behavior of Statement.cancel, which by default cancels the object on which it is invoked and any other Statement objects that have begun to execute and are waiting for results

• If you are requesting support for wide tables from the server

• If you would like to request server support for storing character data in unichar (Unicode) columns

Note Only Adaptive Server version 12.5 and later support wide tables and unichar character data.

• If you would like to request support from the server for the date and time SQL datatypes

Note Only Adaptive Server version 12.5.1 and later support the date and time SQL datatypes.

Table 2-1 lists the version settings available and their features.

CHAPTER 2

Programming Information

Table 2-1: jConnect version settings and their features

JCONNECT_

VERSION

Features

Comments

“6.05”

jConnect requests support for the date and time SQL datatypes from the server. This request is ignored by servers other than Adaptive Server version 12.5.1 and later.

For jConnect version 6.05, the default is “6.05”

 

For additional information for date and time datatypes, see “Using date and time datatypes” on page 70.

 

jConnect requests support for the unichar and univarchar datatypes from the server. This request is ignored by servers other than Adaptive Server 12.5 and later.

For more information on unichar and univarchar datatypes and Unicode, see “Using jConnect to pass Unicode data” on page 36.

The default value of the LANGUAGE connection property is null.

For more information on wide tables, see “Using wide table support for ASE 12.5 and later” on page 50.

By default, Statement.cancel cancels only the Statement object it is invoked on.

Computed columns – the jConnect driver supports accessing these specific computed columns, including their metadata information.

Large identifiers – the jConnect driver fully supports large identifiers in your applications. Large identifiers limits, which define the length of object names or identifiers, is increased to 255 bytes. The new large identifier applies to most user- defined identifiers, including table name, column name, and index name. As a result of the expanded limits.

Setting up jConnect

JCONNECT_

VERSION

Features

Comments

“6”

jConnect requests support for the date and time SQL datatypes from the server. This request is ignored by servers other than Adaptive Server version 12.5.1 and later.

For jConnect version 6.0, the default is

 

VERSION_6.

 

For additional information for date and time datatypes, see “Using date and time datatypes” on page 70.

 

jConnect requests support for the unichar and univarchar datatypes from the server. This request is ignored by servers other than Adaptive Server 12.5 and later.

For more information on unichar and univarchar datatypes and Unicode, see “Using jConnect to pass Unicode data” on page 36.

 

jConnect requests support for wide tables from the server. This request is ignored by servers other than Adaptive Server 12.5 and later.

For more information on wide tables, see “Using wide table support for ASE 12.5 and later” on page 50.

The default value of the LANGUAGE connection property is null.

If the CHARSET connection property does not specify a character set, jConnect uses the default character set of the database. The default value for CHARSET_CONVERTER is the

 

CheckPureConverter class.

The default value of DISABLE_UNICHAR_SENDING is set to false.

 

By default, Statement.cancel cancels only the Statement object it is invoked on.

JDBC 2.0 methods can be used to store and retrieve Java objects as column data.

“5”

The default value of the LANGUAGE connection property is null.

For jConnect versions 5.x, the default is

 

VERSION_5.

 

If the CHARSET connection property does not specify a character set, jConnect uses the default character set of the database.The default value for CHARSET_CONVERTER is the

 

CheckPureConverter class.

 

By default, Statement.cancel cancels only the Statement object it is invoked on.

JDBC 2.0 methods can be used to store and retrieve Java objects as column data.

CHAPTER 2

Programming Information

JCONNECT_

VERSION

Features

Comments

“4”

The default value of the LANGUAGE connection property is null.

Server messages are localized according to the language setting in your local environment. The languages supported are Chinese, U.S. English, French, German, Japanese, Korean, Polish, Portuguese, and Spanish.

The default behavior of Statement.cancel is JDBC-compliant.

If the CHARSET connection property does not specify a character set, jConnect uses the default character set of the database.The default value for CHARSET_CONVERTER is the

 

CheckPureConverter class.

Use CANCEL_ALL to set the behavior of

 

By default, Statement.cancel cancels only the Statement object it is invoked on.

Statement.cancel. See “CANCEL_ALL

 

connection property” on page 11.

 

JDBC 2.0 methods can be used to store and retrieve Java objects as column data.

For information on Java objects as column data, see “Storing Java objects as column data in a table” on page 79.

“3”

The default value of the LANGUAGE connection property is us_english.

See the comments for VERSION_2.

If the CHARSET connection property does not specify a character set, jConnect uses the default character set of the database.

The default value for CHARSET_CONVERTER is the

 

CheckPureConverter class.

 

By default, Statement.cancel cancels the object it is invoked on and any other Statement objects that have begun to execute and are waiting for results.

“2”

The default value of the LANGUAGE connection property is us_english.

The LANGUAGE connection property determines the language in which messages from jConnect and the server appear.

For information on the CHARSET and CHARSET_CONVERTER connection classes, see “jConnect character-set converters” on page 38.

If the CHARSET connection property does not specify a character set, the default character set is iso_1.

The default value for CHARSET_CONVERTER is the

 

TruncationConverter class, unless the

The VERSION_2 default behavior of Statement.cancel is not JDBC-compliant. Use CANCEL_ALL to set the behavior of

Statement.cancel. See “CANCEL_ALL

CHARSET connection property specifies a multibyte or 8-bit character set, in which case the default CHARSET_CONVERTER

is the CheckPureConverter class.

connection property” on page 11.

 

By default, Statement.cancel cancels the object it is invoked on and any other Statement objects that have begun to execute and are waiting for results.

Setting up jConnect

JCONNECT_VERSION connection property

As described in this section, you can use JCONNECT_VERSION to override the SybDriver version setting and specify a different version setting for a specific connection.

Use JCONNECT_VERSION to specify the version setting for a specific session.You can set JCONNECT_VERSION to a value of “2,” “3,” “4,” “5,” “6,” or “6.05,” depending on the characteristics you want.

When referring to the version constant, use this syntax:

com.sybase.jdbcx.SybDriver.VERSION_6

Although the preferred approach is to use JCONNECT_VERSION connection property, you can alternately use constant values in SybDriver.

Use SybDriver.setVersion to set the jConnect version. The setVersion method affects the jConnect default behavior for all connections created by the SybDriver object. However, you can use the JCONNECT_VERSION connection property to set version-specific behavior for individual connections. The following code sample shows how to load the jConnect driver and set the version:

import com.sybase.jdbcx.SybDriver; SybDriver sybDriver = (SybDriver) Class.forName

("com.sybase.jdbc3.jdbc.SybDriver").newInstance();

sybDriver.setVersion

(com.sybase.jdbcx.SybDriver.VERSION_6);

DriverManager.registerDriver(sybDriver);

You can call setVersion multiple times to change the version setting. New connections inherit the behavior associated with the version setting at the time the connection was made. Changing the version setting during a session does not affect the current connection. jConnect provides a

com.sybase.jdbcx.SybDriver.VERSION_LATEST constant which can be used to

ensure that you are always requesting the highest version value possible for the jConnect driver you are using. However, by setting the version to

com.sybase.jdbcx.SybDriver.VERSION_LATEST, you may see behavior

changes if you replace your current jConnect driver with a newer one.

CHAPTER 2

Programming Information

CANCEL_ALL connection property

CANCEL_ALL is a Boolean-valued connection property for specifying the behavior of the Statement.cancel method.

Note In jConnect version 4.0 and earlier, the default for CANCEL_ALL is "true." In jConnect version 4.1 and later, to comply with the JDBC specification, if you set the connection property JCONNECT_VERSION to “4” or later, the default setting for CANCEL_ALL is "false."

The settings for CANCEL_ALL have the following effect on

Statement.cancel( ):

• If CANCEL_ALL is "false," invoking Statement.cancel cancels only the Statement object it is invoked on. Thus, if stmtA is a Statement object, stmtA.cancel cancels the execution of the SQL statement contained in stmtA in the database, but no other statements are affected. stmtA is canceled whether it is in cache waiting to execute or has started to execute and is waiting for results.

• If CANCEL_ALL is "true," invoking Statement.cancel cancels not only the object it is invoked on, but also any other Statement objects on the same connection that have executed and are waiting for results.

The following example sets CANCEL_ALL to "false." In the example, props is a Properties object for specifying connection properties:

props.put("CANCEL_ALL", "false");

Note To cancel the execution of all Statement objects on a connection, regardless of whether or not they have begun execution on the server, use the

extension method SybConnection.cancel.

Invoking the jConnect driver

To register and invoke the Sybase jConnect driver, use either of the following two suggested methods:

• Use Class.forName as shown:

Class.forName("com.sybase.jdbc3.jdbc.SybDriver")

.newInstance();

Establishing a connection

• Add the jConnect driver to the jdbc.drivers system property. At initialization, the DriverManager class attempts to load the drivers listed in jdbc.drivers. This is less efficient than the Class.forName call approach. You can list multiple drivers in this property, separated with a colon (:). The following code samples show how to add a driver to jdbc.drivers within a program:

Properties sysProps = System.getProperties(); String drivers = "com.sybase.jdbc3.jdbc.SybDriver"; String oldDrivers = sysProps.getProperty("jdbc.drivers"); if (oldDrivers != null) drivers += ":" + oldDrivers; sysProps.put("jdbc.drivers", drivers.toString());

Note System.getProperties is not allowed for Java applets. Instead, use the

Class.forName method.

Establishing a connection

This section describes how to establish a connection to an Adaptive Server or Adaptive Server Anywhere database using jConnect.

Setting connection properties

Table 2-2 lists the connection properties for jConnect and indicates their default values. You must set the connection properties before you make a connection.

There are two ways to set the driver connection properties:

• Use the DriverManager.getConnection method in your application.

• Set the connection properties when you define the URL.

Note Driver connection properties set in the URL do not override any corresponding connection properties set in the application using the

DriverManager.getConnection method.

CHAPTER 2

Programming Information

To obtain a current list of properties for any driver, use the

Driver.getDriverPropertyInfo(String url, Properties props), which returns an array

of DriverPropertyInfo objects. The array lists:

• Driver properties

• Current settings on which the driver properties are based

• The URL and props passed in Driver connection property names are not case sensitive (jConnect uses the

String.equalsIgnoreCase(String) method to compare property names).

Table 2-2: Connection properties

Property

Description

Default value

APPLICATIONNAME

Specifies an application name. This is a user- defined property. The server side can be programmed to interpret the value given to this property.

Null

BE_AS_JDBC_COMPLIANT_

Adjusts other properties to ensure that jConnect methods respond in a way that is as compliant as possible with the JDBC 3.0 standard.

These properties are affected (and overridden) when this property is set to "true":

False

AS_POSSIBLE

• CANCEL_ALL (set to "false")

• LANGUAGE CURSOR (set to "false")

• SELECT_OPENS_CURSOR (set to "true")

• FAKE_METADATA (set to "true")

• GET_BY_NAME_USES_COLUMN_LABEL (set to "false")

CACHE_COLUMN_METADATA

To improve performance when you are setting DYNAMIC_PREPARE to “true,” jConnect will cache ResultSet Metadata on consecutive executions.

None

CANCEL_ALL

Determines the behavior of the Statement.cancel method. See “CANCEL_ALL connection property” on page 11.

Depends on version setting. See “Setting the jConnect version” on page

 

5.

Establishing a connection

Property

Description

Default value

CAPABILITY_TIME

Used only when JCONNECT_VERSION >= 6. When jConnect is connected to a server that

False

supports the TIME datatype, and all parameters

of type java.sql.Time or escape literals {t

}

are

processed as TIME.

 

Previous versions of jConnect treat such parameters as DATETIME and prepend '1970-01- 01' to the java.sql.Time parameter. If the underlying datatype is datetime or smalldatetime the date part also gets stored in the database. In the new versions of jConnect when TIME is processed, then the server converts time to the underlying datatype and will prepend its own base year. This can result in incompatibilities between old and new data. If you are using

 

datetime or smalldatetime datatypes for

 

java.sql.Time, then for backward compatiblity you should leave CAPABILITY_TIME as false.

 

Leaving this property as false forces jConnect to process java.sql.Time parameters or escape

literals {t

}

as DATETIME regardless of the

 

server capability of handling TIME datatype.

Setting this property to true will cause jConnect to process java.sql.Time parameters as TIME datatype when connected to ASE 12.5.1 or later. Sybase recommends you leave this property as

 

false if you are using smalldatetime or datetime

columns to store time values.

 

CAPABILITY_WIDETABLE

If you do not require JDBC ResultSetMetaData like Column name as a performance

False

improvement, you can set this to “false.” The result is that less data is exchanged over the network and increases performance. Unless you are using EAServer, Sybase recommends, that you use the default setting. See “Using wide table support for ASE 12.5 and later” on page

50.

CHAPTER 2

Programming Information

Property

Description

Default value

CHARSET

Specifies the character set for strings passed to the database. If the CHARSET value is null, jConnect uses the default character set of the server to send string data to the server. If you specify a CHARSET, the database must be able to handle characters in that format. If the database cannot do so, a message is generated indicating that character conversion cannot be properly completed.

Null

Note When using jConnect 6.05 with DISABLE_UNICHAR_SENDING set to “false”, jConnect detects when a client is trying to send characters to the server that cannot be represented in the character set that is being used for the connection. When that occurs, jConnect sends the character data to the server as unichar data, which allows clients to insert Unicode data into unichar/univarchar columns and parameters.

CHARSET_CONVERTER_CLASS

Specifies the character-set converter class you want jConnect to use. jConnect uses the version setting from SybDriver.setVersion, or the version passed in with the JCONNECT_VERSION property, to determine the default character-set converter class to use. See “Selecting a character-set converter” on page 39 for details.

Version-

dependent

CLASS_LOADER

A property you set to a DynamicClassLoader object that you create. The DynamicClassLoader is used to load Java classes that are stored in the database but which are not in the CLASSPATH at application start-up time. See“Using dynamic class loading” on page 83 for more information.

Null

CONNECTION_FAILOVER

Used with the Java Naming and Directory Interface (JNDI). See “CONNECTION_FAILOVER connection property” on page 29.

True

Establishing a connection

Property

Description

Default value

DISABLE_UNICHAR_SENDING

When a client application sends unichar characters to the server (along with non-unichar characters), there is a slight performance hit for any character data sent to the database. This property defaults to "false" in jConnect 6.05. Clients using older versions of jConnect who wish to send unichar data to the database must set this property to "false”. See “Using jConnect to pass Unicode data” on page 36.

Version-

dependent

DISABLE_UNPROCESSED_

Disables warnings. During results processing for

False

PARAM_WARNINGS

a

stored procedure, jConnect often reads return

values other than row data. If you do not process the return value, jConnect raises a warning. To disable these warnings (which can help performance), set this property to "true."

 

DYNAMIC_PREPARE

Determines whether dynamic SQL prepared statements are precompiled in the database. See “DYNAMIC_PREPARE connection property” on page 137.

False

ENABLE_SERVER_PACKETSIZE

Allows you to specify if you want to use server specified packet size. By default this property is set to “true” that uses the server specified packet size.

True

ENCRYPT_PASSWORD

Allows a secure login. When it is set to “true,” both login and remote site passwords are encrypted and sent to the server.

False

ESCAPE_PROCESSING_DEFAULT

Circumvents processing of JDBC function escapes in SQL statements. By default, jConnect parses all SQL statements submitted to the database for valid JDBC function escapes. If your application is not going to use JDBC function escapes in its SQL calls, you can set this connection property to "false" to avoid this processing. This can provide a slight performance benefit.

True

EXPIRESTRING

Contains the license expiration date. Expiration

Never

is never except for evaluation copies of

jConnect. This is a read-only property.

CHAPTER 2

Programming Information

Property

Description

Default value

FAKE_METADATA

Returns phony metadata. When you call the

False

ResultSetMetaData methods getCatalogName, getSchemaName, and getTableName and this

property is set to "true," the call returns empty strings ("") because the server does not supply useful metadata.

When this property is set to "false," calling these methods throws a “Not Implemented” SQLException.

Note If you have enabled wide tables and are using an Adaptive Server 12.5 or later, this property setting is ignored, because the server does supply useful metadata.

GET_BY_NAME_USES_

Provides backward compatibility with versions of jConnect earlier than 6.0.

True

COLUMN_LABEL

With Adaptive Server version 12.5, jConnect has access to more metadata than was previously available. Previous to version 12.5, column name and column alias meant the same thing. jConnect can now differentiate between the two when used with a 12.5 or later Adaptive Server with wide tables enabled.

To preserve backward compatibility, set this property to "true."

If you want calls to getByte, getInt, get* (String columnName) to look at the actual name for the column (called for in the JDBC 2.0 specification), set this property to "false."

GSSMANAGER_CLASS

Specifies a third-party implementation of the org.ietf.jgss.GSSManager class.

Null

This property can be set to a string or a GSSManager object.

If the property is set to a string, the value should be the fully qualified class name of the third- party GSSManager implementation. If the property is set to an object, the object must extend the org.ietf.jgss.GSSManager class. See Chapter 3, “Security” for more information.

Establishing a connection

Property

Description

Default value

HOSTNAME

Identifies the name of the current host.

None. The max length is 30 characters

 

and, if exceeded, it is truncated to

30.

HOSTPROC

Identifies the application process on the host machine.

None

IGNORE_DONE_IN_PROC

Determines that intermediate update results (as in stored procedures) are not returned, only the final result set.

False

IS_CLOSED_TEST

Allows you to specify what query, if any, is sent to the database when Connection.isClosed is called. For additional information, see the “Using Connection.isClosed and IS_CLOSED_TEST” on page 99.

Null

JCONNECT_VERSION

Sets version-specific characteristics. See “JCONNECT_VERSION connection property” on page 10.

6

LANGUAGE

Sets the language for error messages returned from the server and for jConnect messages. The setting must match a language in syslanguages.

Version dependent. See “Setting the jConnect version” on page

 

5.

LANGUAGE_CURSOR

Determines that jConnect uses “language cursors” instead of “protocol cursors.” See “Cursor performance” on page 140.

False

LITERAL_PARAMS

When set to "true," any parameters set by the

False

setXXX methods in the PreparedStatement

interface are inserted literally into the SQL statement when it is executed.

If set to "false," parameter markers are left in the SQL statement and the parameter values are sent to the server separately.

CHAPTER 2

Programming Information

Property

Description

Default value

USE_METADATA

Creates and initializes a DatabaseMetaData object when you establish a connection. The DatabaseMetaData object is necessary to connect to a specified database.

True

jConnect uses DatabaseMetaData for some features, including Distributed Transaction Management support (JTA/JTS) and dynamic class loading (DCL).

If you receive error 010SJ, which indicates that your application requires metadata, install the stored procedures for returning metadata that come with jConnect. See “Installing Stored Procedures” in Chapter 3 of the jConnect for JDBC Installation Guide.

PACKETSIZE

Identifies the network packet size. If you are using ASE 15.0, Sybase recommends that you do not set this property and allow jConnect and ASE 15.0 to pick the network packet size that is appropriate for your environment. See

512

PASSWORD

Identifies the login password.

None

Set automatically if using the

getConnection(String, String, String) method, or explicitly if using getConnection(String, Props).

PRELOAD_JARS

Contains a comma-separated list of .jar file names that are associated with the CLASS_LOADER that you specify. These .jar files are loaded at connect time, and are available for use by any other connection using the same jConnect driver. See “Preloading .jar files” on page 86 for more information.

Null

PROTOCOL_CAPTURE

Specifies a file for capturing TDS communication between an application and an Adaptive Server.

Null

PROXY

Specifies a gateway address. For the HTTP protocol, the URL is http://host:port.

None

To use the HTTPS protocol that supports encryption, the URL is https://host:port/servlet_alias.

Establishing a connection

Property

Description

Default value

QUERY_TIMEOUT_CANCELS_ALL

Forces jConnect to cancel all Statements on a Connection when a read timeout is encountered. This behavior can be used when a client has calls execute() and the timeout occurs because of a deadlock (for example, trying to read from a table that is currently being updated in another transaction). The default value is false. Depending on future discussions with Sun, this property may be lumped in with the property values affected by the BE_AS_JDBC_COMPLIANT_AS_POSSIBLE property.

False

REMOTEPWD

Contains remote server passwords for access through server-to-server remote procedure calls. See “Performing server-to-server remote procedure calls” on page 48.

None

REPEAT_READ

Determines whether the driver keeps copies of columns and output parameters so that columns can be read out of order or repeatedly. See “REPEAT_READ connection property” on page 132.

True

REQUEST_HA_SESSION

Indicates whether the connecting client wants to begin an high availability (HA) failover session with a version 12 or later Adaptive Server configured for failover. See “Implementing high availability failover support” on page 44.

False

Note Setting this property to "true" causes jConnect to attempt a failover login. If you do not set this connection property, a failover session does not start, even if the server is configured for failover.

You cannot reset the property once a connection has been made.

If you want more flexibility for requesting failover sessions, code the client application to set REQUEST_HA_SESSION at runtime.

CHAPTER 2

Programming Information

Property

Description

Default value

REQUEST_KERBEROS_SESSION

Determines whether jConnect uses Kerberos for authentication. If this property is set to "true," a value for the SERVICE_PRINCIPAL_NAME property must also be specified.

False

You may also wish to provide a value for the GSSMANAGER_CLASS property. See Chapter 3, “Security,” for more information.

RMNAME

Sets the Resource Manager name when using distributed transactions (XA). This property overrides a Resource Manager name that may be set in an LDAP server entry. See “Distributed transaction management support” on page 94 for more information.

Null

SECONDARY_SERVER_

Sets the hostname and port for the secondary server when the client is using an HA failover session. The value for this property should be in

the form of hostName:portNumber. This

Null

HOSTPORT

property is ignored unless you have also set REQUEST_HA_SESSION to "true." See “Implementing high availability failover support” on page 44 for more information.

SELECT_OPENS_CURSOR

Determines whether calls to

False

Statement.executeQuery automatically generate

cursor when the query contains a FOR UPDATE clause.

a

If

you have previously called

Statement.setFetchSize or Statement.setCursorName on the same

 

statement, a setting of "true" for SELECT_OPENS_CURSOR has no effect.

Note You may experience some performance degradation when SELECT_OPENS_CURSOR is set to "true."

See “Using cursors with result sets” on page 52 for more information on using cursors with jConnect.

SERIALIZE_REQUESTS

Determines whether jConnect waits for responses from the server before sending additional requests.

False

Establishing a connection

Property

Description

Default value

SERVER_INITIATED_

Allows the server to control transactions. By default the property is set to “true” and jConnect lets the server start and control transactions by

using Transact-SQL™ set chained on."If set to

True

TRANSACTIONS

“false,” the transactions are started and controlled by jConnect by using transact sql "begin tran." Sybase recommends that you allow the server to control the transactions.

SERVICENAME Indicates the name of a back-end database server that a DirectConnect gateway serves. Also used to indicate which database should be used upon connecting to Adaptive Server Anywhere.

None

SERVERTYPE

When connected to OpenSwitch set this property to "OSW." This allows jConnect to send certain instructions to OpenSwitch that allows OpenSwitch to remember initial connection settings for example, isolation level, textsize, quoted identifier and autocommit when OpenSwitch is moved to a different server instance.

None

SERVICE_PRINCIPAL_NAME

Used when establishing a Kerberos connection to Adaptive Server Enterprise. The value of this property should correspond both to the server entry in your Key Distribution Center (KDC) and to the server name under which your database is running.

Null

The value of the SERVICE_PRINCIPAL_NAME property is ignored if the REQUEST_KERBEROS_SESSION property is set to "false." See Chapter 3, “Security,” for more information.

SESSION_ID

A TDS session ID. When this property is set, jConnect assumes that an application is trying to resume communication on an existing TDS session held open by the TDS-tunnelling gateway. jConnect skips the login negotiations and forwards all requests from the application to the specified session ID.

Null

CHAPTER 2

Programming Information

Property

Description

Default value

SESSION_TIMEOUT Specifies the amount of time (in seconds) that an HTTP-tunnelled session (created using the jConnect TDS-tunnelling servlet) remains alive while idle. After the specified time, the connection is automatically closed. For more information about the TDS-tunnelling servlet, see page 154.

Null

SQLINITSTRING

Defines a set of commands to be passed to the database server when a connection is opened. These must be SQL commands that can be

Null

executed using the Statement.executeUpdate

method.

STREAM_CACHE_SIZE

Specifies the maximum size used to cache statement response streams.

Null (unlimited

cache size)

SYBSOCKET_FACTORY

Enables jConnect to use your custom socket implementation.

Null

Set SYBSOCKET_FACTORY either to:

• The name of a class that implements

com.sybase.jdbcx.SybSocketFactory; or

• “DEFAULT,” which instantiates a new

java.net.Socket( )

Use this property to make an SSL connection to your database.

See “Implementing custom socket plug-ins” on page 32.

TEXTSIZE

Allows you to set the TEXTSIZE. By default ASE and ASA allow 32627 bytes to be read from an image or text column. If you have the jConnect mda tables installed, jConnect changes that value to 2GB. However setting this value when connected to OpenSwitch allows the connection to remember the setting when OpenSwitch is moved to a different server instance.

2GB

USER

Specifies the login ID.

None

Set automatically if using the

getConnection(String, String, String) method, or explicitly if using getConnection(String, Props).

VERSIONSTRING

Provides read-only version information for the JDBC driver.

jConnect driver

version

Establishing a connection

The following code is an example of setting connection properties. The sample programs provided with jConnect also contain examples of setting these properties.

Properties props = new Properties();

props.put("user", "userid "); props.put("password", "user_password"); /*

* If the program is an applet that wants to access

* a server that is not on the same host as the

* web server, then it uses a proxy gateway.

*/ props.put("proxy", "localhost : port ");

/*

*

Make sure you set connection properties before

*

attempting to make a connection. You can also

*

set the properties in the URL.

*/ Connection con = DriverManager.getConnection ("jdbc:sybase:Tds:host:port ", props);

Connecting to Adaptive Server

In your Java application, define a URL using the jConnect driver to connect to an Adaptive Server. The basic format of the URL is:

jdbc:sybase:Tds: host :port

where:

jdbc:sybase identifies the driver.

Tds is the Sybase communication protocol for Adaptive Server.

host:port is the Adaptive Server host name and listening port. See $SYBASE/interfaces (UNIX) or %SYBASE%\ini\sql.ini (Windows) for the entry that your database or Open Server application uses. Obtain the host:port from the “query” entry.

You can connect to a specific database using this format:

CHAPTER 2

Programming Information

jdbc:sybase:Tds: host : port/database

Note To connect to a specific database using Adaptive Server Anywhere or DirectConnect, use the SERVICENAME connection property to specify the database name instead of “/database.”

Example

The following code creates a connection to an Adaptive Server on host “myserver” listening on port 3697:

SysProps.put("user","userid "); SysProps.put("password","user_password "); String url = "jdbc:sybase:Tds:myserver:3697"; Connection_con = DriverManager.getConnection(url,SysProps);

URL connection property parameters

You can specify the values for the jConnect driver connection properties when you define a URL.

Note Driver connection properties set in the URL do not override any corresponding connection properties set in the application using the

DriverManager.getConnection method.

To set a connection property in the URL, append the property name and its value to the URL definition. Use this syntax:

jdbc:sybase:Tds: host : port / database ? property_name = value

To set multiple connection properties, append each additional connection property and value, preceded by “&.” For example:

jdbc:sybase:Tds:myserver:1234/mydatabase?

LITERAL_PARAMS=true&PACKETSIZE=512&HOSTNAME=myhost

If the value for one of the connection properties contains “&,” precede the “&” in the connection property value with a backslash (\). For example, if your host name is “a&bhost,” use this syntax:

jdbc:sybase:Tds:myserver:1234/mydatabase?

LITERAL_PARAMS=true&PACKETSIZE=512&HOSTNAME=

a\&bhost

Establishing a connection

Do not use quotes for connection property values, even if they are strings. For example, use:

HOSTNAME=myhost

not:

HOSTNAME="myhost"

Connecting to a server using JNDI

In jConnect, you can use the Java Naming and Directory Interface (JNDI) to provide connection information, which offers:

• A centralized location where you can specify host names and ports for connecting to a server. You do not need to hard code a specific host and port number in an application.

• A centralized location where you can specify connection properties and a default database for all applications to use.

• The jConnect CONNECTION_FAILOVER property for handling unsuccessful connection attempts. When CONNECTION_FAILOVER is set to "true," jConnect attempts to connect to a sequence of host/port server addresses in the JNDI name space until one succeeds.

To use jConnect with JNDI, you need to make sure that certain information is available in any directory service that JNDI accesses and that required information is set in the javax.naming.Context class. This section covers the following topics:

• Connection URL for using JNDI

• Required directory service information

• CONNECTION_FAILOVER connection property

• Providing JNDI context information

Connection URL for using JNDI

To specify that jConnect should use JNDI to obtain connection information, place “jndi” as the URL protocol after “sybase”:

jdbc:sybase:jndi:protocol-information-for-use-with-JNDI

Anything that follows “jndi” in the URL is handled through JNDI. For example, to use JNDI with the Lightweight Directory Access Protocol (LDAP), you might enter:

jdbc:sybase:jndi:ldap://LDAP_hostname : port_number/servername=

Sybase11,o=MyCompany,c=US

This URL tells JNDI to obtain information from an LDAP server, gives the host name and port number of the LDAP server to use, and provides the name of a database server in an LDAP-specific form.

Required directory service information

When you use JNDI with jConnect, JNDI needs to return the following information for the target database server:

• A host name and port number to connect to

• The name of the database to use

• Any connection properties that individual applications are not allowed to set on their own

This information needs to be stored according to a fixed format in any directory service used for providing connection information. The required format consists of a numerical object identifier (OID), which identifies the type of information being provided (for example, the destination database), followed by the formatted information (see “Example 1” on page 23).

Note You can use the alias name to reference the attribute instead of the OID. See “Example 2” on page 24.

Table 2-3 shows the required formatting.

Establishing a connection

Table 2-3: Directory service information for JNDI

Attribute description

Alias

OID (object_id)

Interfaces entry replacement in LDAP directory services

sybaseServer

1.3.6.1.4.1.897.4.1.1

Collection point for sybaseServer LDAP attributes

sybaseServer

1.3.6.1.4.1.897.4.2

Version Attribute

sybaseVersion

1.3.6.1.4.1.897.4.2.1

Servername Attribute

sybaseServer

1.3.6.1.4.1.897.4.2.2

Service Attribute

sybaseService

1.3.6.1.4.1.897.4.2.3

Status Attribute

sybaseStatus

1.3.6.1.4.1.897.4.2.4

Address Attribute

sybaseAddress

1.3.6.1.4.1.897.4.2.5

Security Mechanism Attribute

sybaseSecurity

1.3.6.1.4.1.897.4.2.6

Retry Count Attribute

sybaseRetryCount

1.3.6.1.4.1.897.4.2.7

Loop Delay Attribute

sybaseRetryDelay

1.3.6.1.4.1.897.4.2.8

jConnect Connection Protocol

sybaseJconnectProtocol

1.3.6.1.4.1.897.4.2.9

jConnect Connection Property

sybaseJconnectProperty

1.3.6.1.4.1.897.4.2.10

Database Name

sybaseDatabasename

1.3.6.1.4.1.897.4.2.11

High Availability Failover Servername Attribute

sybaseHAservername

1.3.6.1.4.1.897.4.2.15

ResourceManager Name

sybaseResourceManager

1.3.6.1.4.1.897.4.2.16

Name

ResourceManager Type

sybaseResourceManager

1.3.6.1.4.1.897.4.2.17

Type

JDBCDataSource Interface

sybaseJdbcDataSource-

1.3.6.1.4.1.897.4.2.18

Interface

ServerType

sybaseServerType

1.3.6.1.4.1.897.4.2.19

Note Attributes in italics are required.

The following examples show connection information entered for the database server “SYBASE11” under an LDAP directory service. Example 1 uses the attribute OID. Example 2 uses the attribute alias, which is not case sensitive. You can use either the OID or the alias.

Example 1

dn: servername=SYBASE11,o=MyCompany,c=US

servername:SYBASE11

1.3.6.1.4.1.897.4.2.5:TCP#1#giotto 1266 1.3.6.1.4.1.897.4.2.5:TCP#1#giotto 1337 1.3.6.1.4.1.897.4.2.5:TCP#1#standby1 4444

CHAPTER 2

Programming Information

1.3.6.1.4.1.897.4.2.10:REPEAT_READ=false&PACKETSIZE=1024

1.3.6.1.4.1.897.4.2.10:CONNECTION_FAILOVER=true

1.3.6.1.4.1.897.4.2.11:pubs2

1.3.6.1.4.1.897.4.2.9:Tds

Example 2

dn: servername=SYBASE11,o=MyCompany,c=US

servername:SYBASE11

sybaseAddress:TCP#1#giotto 1266 sybaseAddress:TCP#1#giotto 1337 sybaseAddress:TCP#1#standby1 4444

sybaseJconnectProperty:REPEAT_READ=false&PACKETSIZE=1024

sybaseJconnectProperty:CONNECTION_FAILOVER=true

sybaseDatabasename:pubs2

sybaseJconnectProtocol:Tds

In these examples, SYBASE11 can be accessed through either port 1266 or port 1337 on host “giotto,” and it can be accessed through port 4444 on host “standby1.” Two connection properties, REPEAT_READ and PACKETSIZE, are set within one entry. The CONNECTION_FAILOVER connection property is set as a separate entry. Applications connecting to SYBASE11 are initially connected with the pubs2 database. You do not need to specify a connection protocol, but if you do, you must enter the attribute as “Tds”, not “TDS”.

CONNECTION_FAILOVER connection property

CONNECTION_FAILOVER is a Boolean-valued connection property you can use when jConnect uses JNDI to get connection information.

If CONNECTION_FAILOVER is set to "true," jConnect makes multiple attempts to connect to a server. If one attempt to connect to a host and port number associated with a server fails, jConnect uses JNDI to get the next host and port number associated with the server and attempts to connect through them. Connection attempts proceed sequentially through all the hosts and ports associated with a server.

For example, if CONNECTION_FAILOVER is set to "true," and a database server is associated with the following hosts and port numbers, as in the earlier LDAP example:

1.3.6.1.4.1.897.4.2.5:TCP#1#giotto 1266 1.3.6.1.4.1.897.4.2.5:TCP#1#giotto 1337 1.3.6.1.4.1.897.4.2.5:TCP#1#standby 4444

Establishing a connection

To get a connection to the server, jConnect tries to connect to the host “giotto” at port 1266. If this fails, jConnect tries port 1337 on “giotto.” If this fails, jConnect tries to connect to host “standby1” through port 4444.

The default for CONNECTION_FAILOVER is "true."

If CONNECTION_FAILOVER is set to "false," jConnect attempts to connect to an initial host and port number. If the attempt fails, jConnect throws a SQL exception and does not try again.

Providing JNDI context information

To use jConnect with JNDI, you should be familiar with the JNDI specification from Sun Microsystems, available from the Web:

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

In particular, you need to make sure that required initialization properties are

set in javax.naming.directory.DirContext when JNDI and jConnect are used

together. These properties can be set either at the system level or at runtime.

Two key properties are:

• Context.INITIAL_CONTEXT_FACTORY

This property takes the fully qualified class name of the initial context factory for JNDI to use. This determines the JNDI driver that is used with the URL specified in the Context.PROVIDER_URL property.

• Context.PROVIDER_URL

This property takes the URL of the directory service that the driver (for example, the LDAP driver) is to access. The URL should be a string, such as “ldap://ldaphost:427”.

The following example shows how to set context properties at runtime and how to get a connection using JNDI and LDAP. In the example, the INITIAL_CONTEXT_FACTORY context property is set to invoke the Sun Microsystem implementation of an LDAP service provider. The PROVIDER_URL context property is set to the URL of an LDAP directory service located on the host “ldap_server1” at port 983.

Properties props = new Properties();

/* We want to use LDAP, so INITIAL_CONTEXT_FACTORY is set to the

* class name of an LDAP context factory. In this case, the

* context factory is provided by Sun’s implementation of a

* driver for LDAP directory service.

CHAPTER 2

Programming Information

*/

props.put(Context.INITIAL_CONTEXT_FACTORY,

"com.sun.jndi.ldap.LdapCtxFactory");

/* Now, we set PROVIDER_URL to the URL of the LDAP server that * is to provide directory information for the connection. */ props.put(Context.PROVIDER_URL, "ldap://ldap_server1:983");

/* Set up additional context properties, as needed. */ props.put("user", "xyz"); props.put("password", "123");

/* get the connection */ Connection con = DriverManager.getConnection ("jdbc:sybase:jndi:ldap://ldap_server1:983" +

"/servername=Sybase11,o=MyCompany,c=US",props);

The connection string passed to getConnection contains LDAP-specific information, which the developer must provide.

When JNDI properties are set at runtime, as in the preceding example, jConnect passes them to JNDI to be used in initializing a server, as in the following jConnect code:

javax.naming.directory.DirContext ctx = new javax.naming.directory.InitialDirContext(props);

jConnect then obtains the connection information it needs from JNDI by invoking DirContext.getAtributes, as in the following example, where ctx is a

DirContext object:

javax.naming.directory.Attributes attrs =

ctx.getAttributes(ldap://ldap_server1:983/servername=

Sybase11, SYBASE_SERVER_ATTRIBUTES);

In the example, SYBASE_SERVER_ATTRIBUTES is an array of strings defined within jConnect. The array values are the OIDs for the required directory information listed in Table 2-3.

Implementing custom socket plug-ins

Implementing custom socket plug-ins

This section discusses how to plug a custom socket implementation into an application to customize the communication between a client and server. javax.net.ssl.SSLSocket is an example of a socket that you could customize to enable encryption.

com.sybase.jdbcx.SybSocketFactory is a Sybase extension interface that contains the createSocket(String, int, Properties) method that returns a

java.net.Socket. For a jConnect version 4.1 or later driver to load a custom socket, an application must:

• Implement this interface

• Define the createSocket method

jConnect uses the new socket for its subsequent input/output operations. Classes that implement SybSocketFactory create sockets and provide a general framework for the addition of public socket-level functionality, as shown:

/**

* Returns a socket connected to a ServerSocket on the named host,

* at the given port.

* @param host the server host

* @param port the server port

* @param props Properties passed in through the connection

* @returns Socket

* @exception IOException, UnknownHostException

*/ public java.net.Socket createSocket(String host, int port, Properties props)

throws IOException, UnknownHostException;

Passing in properties allows instances of SybSocketFactory to use connection properties to implement an intelligent socket.

When you implement SybSocketFactory to produce a socket, the same application code can use different kinds of sockets by passing the different kinds of factories or pseudo-factories that create sockets to the application.

CHAPTER 2

Programming Information

You can customize factories with parameters used in socket construction. For example, you can customize factories to return sockets with different networking timeouts or security parameters already configured. The sockets returned to the application can be subclasses of java.net.Socket to directly expose new APIs for features such as compression, security, record marking, statistics collection, or firewall tunnelling (javax.net.SocketFactory).

Note SybSocketFactory is intended to be an overly simplified javax.net.SocketFactory, enabling applications to bridge from java.net.* to

javax.net.*

Using a custom socket with jConnect

1 Provide a Java class that implements com.sybase.jdbcx.SybSocketFactory.

See “Creating and configuring a custom socket” on page 33.

2 Set the SYBSOCKET_FACTORY connection property so that jConnect can use your implementation to obtain a socket.

To use a custom socket with jConnect, set the SYBSOCKET_FACTORY connection property to a string that is either:

• The name of a class that implements

com.sybase.jdbcx.SybSocketFactory

or

• DEFAULT, which instantiates a new java.net.Socket.

See “Setting connection properties” on page 12 for instructions on how to set SYBSOCKET_FACTORY.

Creating and configuring a custom socket

Once jConnect obtains a custom socket, it uses the socket to connect to a server. Any configuration of the socket must be completed before jConnect obtains it.

This section explains how to plug in an SSL socket implementation, such as

javax.net.ssl.SSLSocket, with jConnect.

Note Currently, only Adaptive Server version 12.5 and later supports SSL.

Implementing custom socket plug-ins

The following example shows how an implementation of SSL can create an instance of SSLSocket, configure it, and then return it. In the example, the

MySSLSocketFactory class implements SybSocketFactory and extends javax.net.ssl.SSLSocketFactory to implement SSL. It contains two createSocket methods—one for SSLSocketFactory and one for SybSocketFactory—that:

• Create an SSL socket

• Invoke SSLSocket.setEnableCipherSuites to specify the cipher suites

available for encryption

• Return the socket to be used by jConnect

Example

public class MySSLSocketFactory extends SSLSocketFactory implements SybSocketFactory

{

/**

*

Create a socket, set the cipher suites it can use, return

*

the socket.

*

Demonstrates how cither suites could be hard-coded into the

*

implementation.

*

*

See javax.net.SSLSocketFactory#createSocket

*/ public Socket createSocket(String host, int port) throws IOException, UnknownHostException

{

 

// Prepare an array containing the cipher suites that are to // be enabled. String enableThese[] =

{

"SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA",

"SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5",

"SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"

}

;

Socket s = SSLSocketFactory.getDefault().createSocket(host, port); ((SSLSocket)s).setEnabledCipherSuites(enableThese);

return s;

}

/**

* Return an SSLSocket.

* Demonstrates how to set cipher suites based on connection

CHAPTER 2

Programming Information

*

properties like:

*

Properties _props = new Properties();

*

Set other url, password, etc. properties.

*

_props.put(("CIPHER_SUITES_1",

*

"SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA");

*

_props.put("CIPHER_SUITES_2",

*

"SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5");

*

_props.put("CIPHER_SUITES_3",

*

"SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA");

*

_conn = _driver.getConnection(url, _props);

*

*

See com.sybase.jdbcx.SybSocketFactory#createSocket

*/ public Socket createSocket(String host, int port, Properties props) throws IOException, UnknownHostException

{

// check to see if cipher suites are set in the connection // properites Vector cipherSuites = new Vector(); String cipherSuiteVal = null; int cipherIndex = 1; do

{

if((cipherSuiteVal = props.getProperty("CIPHER_SUITES_" + cipherIndex++)) == null)

{

if(cipherIndex <= 2)

{

 

// No cipher suites available // return what the object considers its default // SSLSocket, with cipher suites enabled. return createSocket(host, port);

}

else

{

 

// we have at least one cipher suite to enable // per request on the connection break;

}

else

}

 

// add to the cipher suit Vector, so that // we may enable them together cipherSuites.addElement(cipherSuiteVal);

}

Handling internationalization and localization

}

while(true); // lets you create a String[] out of the created vector String enableThese[] = new String[cipherSuites.size()];

cipherSuites.copyInto(enableThese); // enable the cipher suites Socket s = SSLSocketFactory.getDefault().createSocket (host, port); ((SSLSocket)s).setEnabledCipherSuites(enableThese); // return the SSLSocket return s;

}

// other methods

}

Because jConnect requires no information about the kind of socket it is, you must complete any configuration before you return a socket.

For additional information, see:

EncryptASE.java – located in the sample2 subdirectory of your jConnect installation, this sample shows you how to use the SybSocketFactory interface with jConnect applications.

MySSLSocketFactoryASE.java – also located in the sample2 subdirectory of your jConnect installation, this is a sample implementation of the SybSocketFactory interface that you can plug in to your application and use.

Handling internationalization and localization

This section discusses internationalization and localization issues relevant to jConnect.

Using jConnect to pass Unicode data

In Adaptive Server version 12.5 and later, database clients can take advantage of the unichar and univarchar datatypes. The two datatypes allow for the efficient storage and retrieval of Unicode data.

Quoting from the Unicode Standard, version 2.0:

CHAPTER 2

Programming Information

“The Unicode Standard is a fixed-width, uniform encoding scheme for

encoding characters and text. The repertoire of this international character code for information processing includes characters for the major scripts of the world, as well as technical symbols in common. The Unicode character encoding treats alphabetic characters, ideographic characters, and symbols identically, which means they can be used in any mixture and with equal facility. The Unicode Standard is modeled on the ASCII character set, but uses

a 16-bit encoding to support full multilingual text.”

This means that the user can designate database table columns to store Unicode data, regardless of the default character set of the server.

Note In Adaptive Server version 12.5 through 12.5.0.3, the server had to have

a default character set of utf-8 in order to use the Unicode datatypes. However,

in Adaptive Server 12.5.1 and later, database users can use unichar and univarchar without having to consider the default character set of the server.

When the server accepts unichar and univarchar data, jConnect behaves as

follows:

• For all character data that a client wishes to send to the server—for

example, using PreparedStatement.setString (int column, String value)

jConnect determines if the string can be converted to the default character set of the server.

• If jConnect determines that the characters cannot be converted to the character set of the server (for example, some characters cannot be represented in the character set of the server), it sends the data to the server

encoded as unichar/univarchar data.

For example, if a client attempts to send a Unicode Japanese character to an Adaptive Server 12.5.1 that has iso_1 as the default character set, jConnect detects that the Japanese character cannot be converted to an iso_1 character. jConnect then sends the string as Unicode data.

There is a performance penalty when a client sends unichar/univarchar data to

a server. This is because jConnect must perform character-to-byte conversion

twice for all strings and characters that do not map directly to the default character set of the server.

If you are using a jConnect version that is earlier than 6.05 and you wish to use

the unichar and univarchar datatypes, you must perform the following tasks:

1 Set the JCONNECT_VERSION = 6 or later. See “Setting the jConnect version” on page 5 for more information.

Handling internationalization and localization

2 You need to set the DISABLE_UNICHAR_SENDING connection property to false. Starting with jConnect 6.05 this property is set to false by default. See “Setting connection properties” on page 12 for more information.

Note For more information on support for unichar and univarchar datatypes, see the manuals for Adaptive Server version 12.5 or later.

jConnect character-set converters

jConnect uses special classes for all character-set conversions. By selecting a character-set converter class, you specify how jConnect handles single-byte and multibyte character-set conversions, and what performance impact the conversions have on your applications.

There are two character-set conversion classes. The conversion class that jConnect uses is based on the JCONNECT_VERSION, CHARSET, and CHARSET_CONVERTER_CLASS connection properties.

• The TruncationConverter class works only with single-byte character sets that use ASCII characters such as iso_1 and cp850. It does not work with multibyte character sets or single-byte character sets that use non-ASCII characters.

Using the TruncationConverter class, jConnect 6.05 handles character sets in the same manner as jConnect version 2.2. The TruncationConverter class is the default converter when the JCONNECT_VERSION = 2.

• The PureConverter class is a pure Java, multibyte character-set converter. jConnect uses this class if the JCONNECT_VERSION = 4 or later. jConnect also uses this converter when JCONNECT_VERSION = 2 if it detects a character set specified in the CHARSET connection property that is not compatible with the TruncationConverter class.

Although it enables multibyte character-set conversions, the PureConverter class may negatively impact jConnect driver performance. If driver performance is a concern, see “Improving character-set conversion performance” on page 40.

CHAPTER 2

Programming Information

Selecting a character-set converter

jConnect uses the JCONNECT_VERSION to determine the default character-set converter class to use. For JCONNECT_VERSION = 2 or higher, the default is PureConverter the default is TruncationConverter. For JCONNECT_VERSION = 4 or higher, the default is PureConverter.

You can also set the CHARSET_CONVERTER_CLASS connection property to specify which character-set converter you want jConnect to use. This is useful if you want to use a character-set converter other than the default for your jConnect version.

For example, if you set JCONNECT_VERSION = 4 or later but want to use the TruncationConverter class rather than the multibyte PureConverter class, you can set CHARSET_CONVERTER_CLASS:

props.put("CHARSET_CONVERTER_CLASS",

"com.sybase.jdbc3.utils.TruncationConverter")

Setting the CHARSET connection property

You can specify the character set to use in your application by setting the CHARSET driver property. If you do not set the CHARSET property:

• For JCONNECT_VERSION = 2, jConnect uses iso_1 as the default character set.

• For JCONNECT_VERSION = 3, and later, jConnect uses the default character set of the database, and adjusts automatically to perform any necessary conversions on the client side.

• For jConnect versions starting with 6.05, if jConnect cannot successfully convert the user data to the negotiated charset, it will send unconverted unicode characters to the server, if the server supports the unicode characters (ASE 12.5 or higher), else it will throw an exception.

You can also use the -J charset command line option for the IsqlApp application to specify a character set.

To determine which character sets are installed on your Adaptive Server, issue the following SQL query on your server:

select name from syscharsets go

Handling internationalization and localization

For the PureConverter class, if the designated CHARSET does not work with the client Java Virtual Machine (VM), the connection fails with a SQLException, indicating that you must set CHARSET to a character set that is supported by both Adaptive Server and the client.

When the TruncationConverter class is used, character truncation is applied regardless of whether the designated CHARSET is 7-bit ASCII or not. Therefore, if your application needs to handle non-ascii data (for instance any asian languages), you should not use TruncationConverter, as this causes data corruption.

Improving character-set conversion performance

If you use multibyte character sets and need to improve driver performance, you can use the SunIoConverter class provided with the jConnect samples. See “SunIoConverter character-set conversion” on page 133 for details.

In addition, you can use TruncationConverter to improve performance if your application deals with only 7-bit ASCII data.

Supported character sets

Table 2-4 lists the Sybase character sets that are supported by jConnect. The table also lists the corresponding JDK byte converter for each supported character set.

Although jConnect supports UCS-2, currently no Sybase databases or Open Servers support UCS-2.

CHAPTER 2

Programming Information

Adaptive Server versions 12.5 and later support a version of Unicode known as the UTF-16 encoding.

Table 2-4 lists the character sets currently supported by Sybase.

Table 2-4: Supported Sybase character sets

SybCharset name

JDK byte converter

ascii_7

ASCII

big5

Big5

big5hk (see note)

Big5_HKSCS

cp037

Cp037

cp437

Cp437

cp500

Cp500

cp850

Cp850

cp852

Cp852

cp855

Cp855

cp857

Cp857

cp860

Cp860

cp863

Cp863

cp864

Cp864

cp866

Cp866

cp869

Cp869

cp874

Cp874

cp932

MS932

cp936

GBK

cp950

Cp950

cp1250

Cp1250

cp1251

Cp1251

cp1252

Cp1252

cp1253

Cp1253

cp1254

Cp1254

cp1255

Cp1255

cp1256

Cp1256

cp1257

Cp1257

cp1258

Cp1258

deckanji

EUC_JP

eucgb

EUC_CN

eucjis

EUC_JP

eucksc

EUC_KR

Handling internationalization and localization

SybCharset name

JDK byte converter

GB18030

GB18030

ibm420

Cp420

ibm918

Cp918

iso_1

ISO8859_1

iso88592

ISO8859-2

is088595

ISO8859_5

iso88596

ISO8859_6

iso88597

ISO8859_7

iso88598

ISO8859_8

iso88599

ISO8859_9

iso15

ISO8859_15_FDIS

koi8

KOI8_R

mac

Macroman

mac_cyr

MacCyrillic

mac_ee

MacCentralEurope

macgreek

MacGreek

macturk

MacTurkish

sjis

MS932

tis620

MS874

utf8

UTF8

Note The big5hk character set is supported only if you are using JDK 1.3 or later.

European currency symbol support

jConnect versions 4.1 and later support the use of the new European currency symbol, or “euro,” and its conversion to and from UCS-2 Unicode.

The euro has been added to the following Sybase character sets: cp1250, cp1251, cp1252, cp1253, cp1254, cp1255, cp1256, cp1257, cp1258, cp874, iso885915, and utf8.

To use the euro symbol:

• Use the PureConvertor or CheckPureConverter class, pure Java, multibyte character-set converter. See “jConnect character-set converters” on page 38 for more information.

CHAPTER 2

Programming Information

• Verify that the new character sets are installed on the server.

The euro symbol is supported only on Adaptive Server Enterprise; Adaptive Server Anywhere version 8.0 and later provides support for the euro symbol.

• Select the appropriate character set on the client. See “Setting the CHARSET connection property” on page 39 for more information.

Unsupported character sets

The following Sybase character sets are not supported in jConnect because no JDK byte converters are analogous to the Sybase character sets:

• cp1047

• euccns

• greek8

• roman8

• turkish8

You can use these character sets with the TruncationConverter class as long as the application uses only the 7-bit ASCII subsets of these characters.

Working with databases

This section discusses database issues relevant to jConnect and includes these topics:

• Implementing high availability failover support

• Performing server-to-server remote procedure calls

• Using wide table support for ASE 12.5 and later

• Accessing database metadata

• Using cursors with result sets

• Support for batch updates

• Updating a database from a result set of a stored procedure

• Working with datatypes