DB2DevJava Db2aje953
DB2DevJava Db2aje953
5
for Linux, UNIX, and Windows
Version 9 Release 5
SC23-5853-03
DB2 Version 9.5
for Linux, UNIX, and Windows
Version 9 Release 5
SC23-5853-03
Note
Before using this information and the product it supports, read the general information under Appendix B, “Notices,” on
page 523.
Edition Notice
This document contains proprietary information of IBM. It is provided under a license agreement and is protected
by copyright law. The information contained in this publication does not include any product warranties, and any
statements provided in this manual should not be interpreted as such.
You can order IBM publications online or through your local IBM representative.
v To order publications online, go to the IBM Publications Center at www.ibm.com/shop/publications/order
v To find your local IBM representative, go to the IBM Directory of Worldwide Contacts at www.ibm.com/
planetwide
To order DB2 publications from DB2 Marketing and Sales in the United States or Canada, call 1-800-IBM-4YOU
(426-4968).
When you send information to IBM, you grant IBM a nonexclusive right to use or distribute the information in any
way it believes appropriate without incurring any obligation to you.
© Copyright IBM Corporation 2006, 2010.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract
with IBM Corp.
Contents
About this book . . . . . . . . . . . vii Data retrieval in JDBC applications . . . . . 45
Who should use this book . . . . . . . . . vii Calling stored procedures in JDBC applications 58
LOBs in JDBC applications with the IBM Data
Chapter 1. Java application development Server Driver for JDBC and SQLJ . . . . . . 66
ROWIDs in JDBC with the IBM Data Server
for IBM data servers . . . . . . . . . 1 Driver for JDBC and SQLJ . . . . . . . . 71
Supported drivers for JDBC and SQLJ . . . . . . 2 Distinct types in JDBC applications . . . . . 73
JDBC driver and database version compatibility . 3 Invocation of stored procedures with ARRAY
parameters in JDBC applications . . . . . . 74
Chapter 2. Installing the IBM Data Server Savepoints in JDBC applications . . . . . . 75
Driver for JDBC and SQLJ . . . . . . . 5 Retrieval of automatically generated keys in
DB2Binder utility . . . . . . . . . . . . . 8 JDBC applications . . . . . . . . . . . 76
DB2LobTableCreator utility . . . . . . . . . 15 Using named parameter markers in JDBC
Customization of IBM Data Server Driver for JDBC applications . . . . . . . . . . . . . 80
and SQLJ configuration properties . . . . . . . 16 Providing extended client information to the data
Special setup for accessing DB2 for z/OS servers source with IBM Data Server Driver for JDBC
from Java programs . . . . . . . . . . . 17 and SQLJ-only methods . . . . . . . . . 83
DB2T4XAIndoubtUtil for distributed transactions Providing extended client information to the data
with DB2 UDB for OS/390 and z/OS Version 7 source with client info properties . . . . . . 84
servers . . . . . . . . . . . . . . . . 18 Optimistic locking in JDBC applications . . . . . 87
XML data in JDBC applications . . . . . . . . 89
Chapter 3. JDBC application XML column updates in JDBC applications . . . 90
XML data retrieval in JDBC applications. . . . 92
programming . . . . . . . . . . . . 21
Invocation of routines with XML parameters in
Example of a simple JDBC application . . . . . 21
Java applications . . . . . . . . . . . 95
How JDBC applications connect to a data source . . 23
Java support for XML schema registration and
How DB2 applications connect to a data source
removal . . . . . . . . . . . . . . 96
using the DriverManager interface with the DB2
Transaction control in JDBC applications. . . . . 98
JDBC Type 2 Driver . . . . . . . . . . 25
IBM Data Server Driver for JDBC and SQLJ
Connecting to a data source using the
isolation levels . . . . . . . . . . . . 99
DriverManager interface with the IBM Data
Committing or rolling back JDBC transactions . . 99
Server Driver for JDBC and SQLJ . . . . . . 26
Default JDBC autocommit modes. . . . . . 100
Connecting to a data source using the
Exceptions and warnings under the IBM Data
DataSource interface . . . . . . . . . . 30
Server Driver for JDBC and SQLJ. . . . . . . 100
How to determine which type of IBM Data
Handling an SQLException under the IBM Data
Server Driver for JDBC and SQLJ connectivity to
Server Driver for JDBC and SQLJ. . . . . . 103
use . . . . . . . . . . . . . . . . 32
Handling an SQLWarning under the IBM Data
JDBC connection objects . . . . . . . . . 33
Server Driver for JDBC and SQLJ. . . . . . 106
Creating and deploying DataSource objects . . . 33
Retrieving information from a
Java packages for JDBC support . . . . . . . 34
BatchUpdateException . . . . . . . . . 107
Learning about a data source using
Handling an SQLException under the DB2 JDBC
DatabaseMetaData methods . . . . . . . . . 35
Type 2 Driver (deprecated) . . . . . . . . . 109
DatabaseMetaData methods for identifying the
Handling an SQLWarning under the DB2 JDBC
type of data source . . . . . . . . . . . 36
Type 2 Driver . . . . . . . . . . . . 109
Variables in JDBC applications . . . . . . . . 37
Disconnecting from data sources in JDBC
JDBC interfaces for executing SQL . . . . . . . 37
applications . . . . . . . . . . . . . . 110
Creating and modifying database objects using
the Statement.executeUpdate method . . . . . 38
Updating data in tables using the Chapter 4. SQLJ application
PreparedStatement.executeUpdate method . . . 38 programming . . . . . . . . . . . 113
JDBC executeUpdate methods against a DB2 for Example of a simple SQLJ application . . . . . 113
z/OS server . . . . . . . . . . . . . 40 Connecting to a data source using SQLJ . . . . 115
Making batch updates in JDBC applications . . 41 SQLJ connection technique 1: JDBC
Learning about parameters in a DriverManager interface . . . . . . . . . 115
PreparedStatement using ParameterMetaData SQLJ connection technique 2: JDBC
methods . . . . . . . . . . . . . . 44 DriverManager interface . . . . . . . . . 117
Contents v
DB2BaseDataSource class . . . . . . . . 390 SDK for Java differences that affect the IBM Data
DB2CallableStatement interface . . . . . . 397 Server Driver for JDBC and SQLJ. . . . . . . 481
DB2CataloguedDatabase class . . . . . . . 403 Error codes issued by the IBM Data Server Driver
DB2ClientRerouteServerList class . . . . . . 404 for JDBC and SQLJ . . . . . . . . . . . 481
DB2Connection interface . . . . . . . . 405 SQLSTATEs issued by the IBM Data Server Driver
DB2ConnectionPoolDataSource class . . . . 422 for JDBC and SQLJ . . . . . . . . . . . 488
DB2DatabaseMetaData interface . . . . . . 424 How to find IBM Data Server Driver for JDBC and
DB2Diagnosable interface . . . . . . . . 425 SQLJ version and environment information . . . 489
DB2ExceptionFormatter class . . . . . . . 426 Commands for SQLJ program preparation. . . . 491
DB2FileReference class . . . . . . . . . 426 sqlj - SQLJ translator . . . . . . . . . . 491
DB2JCCPlugin class . . . . . . . . . . 427 db2sqljcustomize - SQLJ profile customizer . . 494
DB2ParameterMetaData interface . . . . . . 428 db2sqljbind - SQLJ profile binder . . . . . . 506
DB2PooledConnection class . . . . . . . 428 db2sqljprint - SQLJ profile printer . . . . . 512
DB2PoolMonitor class . . . . . . . . . 431
DB2PreparedStatement interface . . . . . . 433 Appendix A. Overview of the DB2
DB2ResultSet interface . . . . . . . . . 443 technical information . . . . . . . . 513
DB2ResultSetMetaData interface . . . . . . 444
DB2 technical library in hardcopy or PDF format 514
DB2RowID interface . . . . . . . . . . 445
Ordering printed DB2 books . . . . . . . . 516
DB2SimpleDataSource class . . . . . . . 445
Displaying SQL state help from the command line
DB2Sqlca class . . . . . . . . . . . . 446
processor . . . . . . . . . . . . . . . 517
DB2Statement interface . . . . . . . . . 447
Accessing different versions of the DB2
DB2SystemMonitor interface . . . . . . . 450
Information Center . . . . . . . . . . . 517
DB2TraceManager class . . . . . . . . . 453
Displaying topics in your preferred language in the
DB2TraceManagerMXBean interface . . . . . 456
DB2 Information Center . . . . . . . . . . 518
DB2Types class . . . . . . . . . . . . 459
Updating the DB2 Information Center installed on
DB2XADataSource class . . . . . . . . . 460
your computer or intranet server . . . . . . . 518
DB2Xml interface . . . . . . . . . . . 462
DB2 tutorials . . . . . . . . . . . . . 520
JDBC differences between the current IBM Data
DB2 troubleshooting information . . . . . . . 520
Server Driver for JDBC and SQLJ and earlier DB2
Terms and Conditions . . . . . . . . . . 521
JDBC drivers . . . . . . . . . . . . . 464
JDBC differences between versions of the IBM Data
Server Driver for JDBC and SQLJ. . . . . . . 474 Appendix B. Notices . . . . . . . . 523
Examples of ResultSetMetaData.getColumnName
and ResultSetMetaData.getColumnLabel values . . 477 Index . . . . . . . . . . . . . . . 527
SQLJ differences between the IBM Data Server
Driver for JDBC and SQLJ and other DB2 JDBC
drivers . . . . . . . . . . . . . . . 479
You can access data in DB2 and IDS database systems using JDBC, SQL, or
pureQuery.
JDBC
SQLJ
SQLJ provides support for embedded static SQL in Java applications. SQLJ was
initially developed by IBM, Oracle, and Tandem to complement the dynamic SQL
JDBC model with a static SQL model.
For connections to DB2, in general, Java applications use JDBC for dynamic SQL
and SQLJ for static SQL.
Because SQLJ can inter-operate with JDBC, an application program can use JDBC
and SQLJ within the same unit of work.
pureQuery
With pureQuery, you can write Java applications that treat relational data as
objects, whether that data is in databases or JDBC DataSource objects. Your
applications can also treat objects that are stored in in-memory Java collections as
though those objects are relational data. To query or update your relational data or
Java objects, you use SQL.
According to the JDBC specification, there are four types of JDBC driver
architectures:
Type 1
Drivers that implement the JDBC API as a mapping to another data access API,
such as Open Database Connectivity (ODBC). Drivers of this type are generally
dependent on a native library, which limits their portability. The DB2 database
system does not provide a type 1 driver.
Type 2
Drivers that are written partly in the Java programming language and partly in
native code. The drivers use a native client library specific to the data source to
which they connect. Because of the native code, their portability is limited.
Type 3
Drivers that use a pure Java client and communicate with a data server using a
data-server-independent protocol. The data server then communicates the
client's requests to the data source. The DB2 database system does not provide
a type 3 driver.
Type 4
Drivers that are pure Java and implement the network protocol for a specific
data source. The client connects directly to the data source.
DB2 Database for Linux, UNIX, and Windows supports the following drivers:
IBM Data Server Driver for JDBC and SQLJ (type 2 and type 4)
The IBM Data Server Driver for JDBC and SQLJ is a single driver that includes
JDBC type 2 and JDBC type 4 behavior. When an application loads the IBM Data
Server Driver for JDBC and SQLJ, a single driver instance is loaded for type 2 and
type 4 implementations. The application can make type 2 and type 4 connections
using this single driver instance. The type 2 and type 4 connections can be made
concurrently. IBM Data Server Driver for JDBC and SQLJ type 2 driver behavior is
referred to as IBM Data Server Driver for JDBC and SQLJ type 2 connectivity. IBM
Data Server Driver for JDBC and SQLJ type 4 driver behavior is referred to as IBM
Data Server Driver for JDBC and SQLJ type 4 connectivity.
Two versions of the IBM Data Server Driver for JDBC and SQLJ are available. IBM
Data Server Driver for JDBC and SQLJ version 3.5x is JDBC 3.0-compliant. IBM
Data Server Driver for JDBC and SQLJ version 4.x is JDBC 4.0-compliant.
The IBM Data Server Driver for JDBC and SQLJ supports these JDBC and SQLJ
functions:
DB2 JDBC Type 2 Driver for Linux, UNIX and Windows (DB2
JDBC type 2 driver) (deprecated)
The DB2 JDBC type 2 driver lets Java applications make calls to DB2 through
JDBC. Calls to the DB2 JDBC type 2 driver are implemented with Java native
methods. The DB2 JDBC Type 2 Driver uses the DB2 CLI interface to communicate
with DB2 data servers. The Java applications that use this driver must run on a
DB2 client, through which JDBC requests flow to the DB2 data server. DB2
Connect™ must be installed before the DB2 JDBC application driver can be used to
access DB2 for i data sources or data sources in the DB2 for z/OS® environments.
The DB2 JDBC type 2 driver supports these JDBC and SQLJ functions:
v Most of the methods that are described in the JDBC 1.2 specification, and some
of the methods that are described in the JDBC 2.0 specification.
v SQLJ statements that perform equivalent operations to all JDBC methods
v Connection pooling
v Distributed transactions
v Java user-defined functions and stored procedures
The DB2 JDBC Type 2 Driver for Linux, UNIX and Windows will not be supported
in future releases. You should therefore consider moving to the IBM Data Server
Driver for JDBC and SQLJ.
Compatibility for IBM Data Server Driver for JDBC and SQLJ type
4 connectivity
The IBM Data Server Driver for JDBC and SQLJ is always downward compatible
with DB2 databases at the previous release level. For example, IBM Data Server
Driver for JDBC and SQLJ type 4 connectivity from the IBM Data Server Driver for
The IBM Data Server Driver for JDBC and SQLJ is upward compatible with the
next version of a DB2 database if the applications under which the driver runs use
no new features. For example, IBM Data Server Driver for JDBC and SQLJ type 4
connectivity from the IBM Data Server Driver for JDBC and SQLJ version 2.x,
which is shipped with DB2 for z/OS Version 8, to a DB2 for z/OS Version 9.1
database is supported, if the applications under which the driver runs contain no
DB2 for z/OS Version 9.1 features.
IBM Data Server Driver for JDBC and SQLJ type 4 connectivity to IBM Informix is
supported only for IDS Version 11 and later.
Compatibility for IBM Data Server Driver for JDBC and SQLJ type
2 connectivity
In general, IBM Data Server Driver for JDBC and SQLJ type 2 connectivity is
intended for connections to the local database system, using the driver version that
is shipped with that database version. For example, version 3.6x of the IBM Data
Server Driver for JDBC and SQLJ is shipped with DB2 Database for Linux, UNIX,
and Windows Version 9.5 and Version 9.7, and DB2 for z/OS Version 8 and later.
However, for IBM Data Server Driver for JDBC and SQLJ type 2 connectivity to a
local DB2 Database for Linux, UNIX, and Windows database, the database version
can be one version earlier or one version later than the DB2 Database for Linux,
UNIX, and Windows version with which the driver was shipped. For IBM Data
Server Driver for JDBC and SQLJ type 2 connectivity to a local DB2 for z/OS
subsystem, the subsystem version can be one version later than the DB2 for z/OS
version with which the driver was shipped.
If the database version to which your applications are connecting is later than the
database version with which the driver was shipped, the applications cannot use
features of the later database version.
Before you install the IBM Data Server Driver for JDBC and SQLJ, you need the
following software.
v An SDK for Java, 1.4.2 or later.
For all DB2 products except the IBM Data Server Runtime Client and the IBM
Data Server Driver Package, the DB2 Database for Linux, UNIX, and Windows
installation process automatically installs the SDK for Java, Version 5.
If you want to use JDBC 4.0 functions, you need to install an SDK for Java, 6 or
later.
If you plan to run JDBC or SQLJ applications on your system, but not to prepare
them, you need a Java run-time environment only.
Important: Support for the SDK for Java 1.4.2 is deprecated for Java routines,
and might be discontinued in a future release.
v JVM native threads support
Any JVMs that run Java applications that access DB2 databases must include
native threads support. You can specify native threads as the default thread
support for some JVMs by setting the THREADS_FLAG environment variable to
"native". Refer to the documentation for your Java environment for instructions
on making native threads the default on your system.
v Unicode support for System i® servers
If any SQLJ or JDBC programs will use IBM Data Server Driver for JDBC and
SQLJ type 4 connectivity to connect to a DB2 for i server, the System i operating
system must support the Unicode UTF-8 encoding scheme. The following table
lists the System i PTFs that you need for Unicode UTF-8 support:
Table 1. System i PTFs for Unicode UTF-8 support
System i version PTF numbers
V5R3 or later None (support is included)
Restriction: If you install the IBM Data Server Driver for JDBC and SQLJ on a
Windows 64-bit operating system, you cannot use IBM Data Server Driver for
JDBC and SQLJ type 2 connectivity to connect to a DB2 Database for Linux, UNIX,
and Windows instance from a 32-bit Java application.
Important: This step is performed automatically only for the db2jcc.jar and
sqlj.zip file. If you are using the db2jcc4.jar file or the sqlj4.zip file, you must
modify the CLASSPATH manually. Change db2jcc.jar to db2jcc4.jar or sqlj.zip
to sqlj4.zip in the CLASSPATH.
You also need to make this change in every DB2 command line window that
you open.
The port number used for applets and SQLJ programs needs to be the same
as the TCP/IP SVCENAME number used in the database manager
configuration file.
c. Execute the db2stop and db2start commands for the service name setting to
take effect.
4. On DB2 Database for Linux, UNIX, and Windows servers on which you plan to
run Java stored procedures or user-defined functions, ensure that the
DB2_USE_DB2JCCT2_JROUTINE environment variable is not set, or is set to its
default value of YES, yes, ON, on, TRUE, true, or 1 on those database servers. This
setting indicates that Java stored procedures run under the IBM Data Server
Driver for JDBC and SQLJ.
If you need to run stored procedures under the DB2 JDBC Type 2 Driver for
Linux, UNIX and Windows, set the DB2_USE_DB2JCCT2_JROUTINE
environment variable to OFF.
5. On DB2 Database for Linux, UNIX, and Windows servers on which you plan to
run Java stored procedures or user-defined functions, update the database
manager configuration to include the path where the SDK for Java is located.
You can do this by entering commands similar to these on the server command
line:
v For database systems on UNIX or Linux:
db2 update dbm cfg using JDK_PATH /home/db2inst/jdk15
Chapter 2. Installing the IBM Data Server Driver for JDBC and SQLJ 7
v For database systems on Windows:
db2 update dbm cfg using JDK_PATH c:\Program Files\jdk15
c:\Program Files\jdk15 is the path where the SDK for Java is installed.
To verify the correct value for the JDK_PATH field in the DB2 database manager
configuration, enter the following command on the database server:
db2 get dbm cfg
You might want to redirect the output to a file for easier viewing. The JDK_PATH
field appears near the beginning of the output.
6. If you plan to call SQL procedures that are on DB2 Database for Linux, UNIX,
and Windows servers from Java programs, and the date and time format that is
associated with the territory code of the database servers is not the USA
format, take the following actions:
a. Set the DB2_SQLROUTINE_PREPOPTS registry variable on the database
servers to indicate that the default datetime format is ISO:
db2set DB2_SQLROUTINE_PREPOPTS="DATETIME ISO"
b. Redefine any existing SQL procedures that you plan to call from Java
programs.
These steps are necessary to ensure that the calling application receives date
and time values correctly.
7. If you plan to access DB2 for z/OS database servers with your Java
applications, follow the instructions in "Special setup for accessing DB2 for
z/OS servers from Java programs" in Developing Java Applications.
DB2Binder utility
The DB2Binder utility binds the DB2 packages that are used at the data server by
the IBM Data Server Driver for JDBC and SQLJ, and grants EXECUTE authority on
the packages to PUBLIC. Optionally, the DB2Binder utility can rebind DB2
packages that are not part of the IBM Data Server Driver for JDBC and SQLJ.
DB2Binder syntax
java com.ibm.db2.jcc.DB2Binder -url jdbc : db2 : // server / database
: port
-action add
-collection collection-name , -action replace
-action drop
-tracelevel trace-option -action rebind
-blocking all
-reopt none -blocking unambig
-reopt always -blocking no -optprofile profile-name
-reopt once
-reopt auto
-package package-name -version version-id -bindoptions " options-string "
-verbose -help
Chapter 2. Installing the IBM Data Server Driver for JDBC and SQLJ 9
objects that can be open concurrently, or the number of IBM Data Server
Driver for JDBC and SQLJ packages that are dropped.
The meaning of the -size parameter depends on the -action parameter:
v If the value of -action is add or replace, the value of -size is an integer that
is used to calculate the number of DB2 packages that the IBM Data Server
Driver for JDBC and SQLJ binds. If the value of -size is integer, the total
number of packages is:
number-of-isolation-levels*
number-of-holdability-values*
integer+
number-of-packages-for-static-SQL
= 4*2*integer+1
Chapter 2. Installing the IBM Data Server Driver for JDBC and SQLJ 11
-bindoptions
Specifies a string that is enclosed in quotation marks. The contents of that
string are one or more parameter and value pairs that represent options for
rebinding a user package. All items in the string are delimited with spaces:
"parm1 value1 parm2 value2 ... parmn valuen"
-bindoptions does not apply to IBM Data Server Driver for JDBC and SQLJ
packages.
Possible parameters and values are:
bindObjectExistenceRequired
Specifies whether the data server issues an error and does not rebind
the package, if all objects or needed privileges do not exist at rebind
time. Possible values are:
true This option corresponds to the SQLERROR(NOPACKAGE)
bind option.
false This option corresponds to the SQLERROR(CONTINUE) bind
option.
degreeIOParallelism
Specifies whether to attempt to run static queries using parallel
processing to maximize performance. Possible values are:
1 No parallel processing.
This option corresponds to the DEGREE(1) bind option.
-1 Allow parallel processing.
This option corresponds to the DEGREE(ANY) bind option.
packageAuthorizationRules
Determines the values that apply at run time for the following
dynamic SQL attributes:
v The authorization ID that is used to check authorization
v The qualifier that is used for unqualified objects
v The source for application programming options that the data server
uses to parse and semantically verify dynamic SQL statements
v Whether dynamic SQL statements can include GRANT, REVOKE,
ALTER, CREATE, DROP, and RENAME statements
Possible values are:
0 Use run behavior. This is the default.
This option corresponds to the DYNAMICRULES(RUN) bind
option.
1 Use bind behavior.
This option corresponds to the DYNAMICRULES(BIND) bind
option.
2 When the package is run as or runs under a stored procedure
or user-defined function package, the data server processes
dynamic SQL statements using invoke behavior. Otherwise, the
data server processes dynamic SQL statements using run
behavior.
Chapter 2. Installing the IBM Data Server Driver for JDBC and SQLJ 13
-verbose
Specifies that the DB2Binder utility displays detailed information about the
bind process.
-help
Specifies that the DB2Binder utility describes each of the options that it
supports. If any other options are specified with -help, they are ignored.
If the target data source for DB2Binder is not on the Windows operating system,
DB2Binder returns one of the following return codes.
Table 3. DB2Binder return codes when the target operating system is not Windows
Return
code Meaning
0 Successful execution.
1 An error occurred during DB2Binder execution.
If the target data source for DB2Binder is on the Windows operating system,
DB2Binder returns one of the following return codes.
Table 4. DB2Binder return codes when the target operating system is Windows
Return
code Meaning
0 Successful execution.
-100 No bind options were specified.
-101 -url value was not specified.
-102 -user value was not specified.
-103 -password value was not specified.
-200 No valid bind options were specified.
-114 The -package option was not specified, but the -generic option was specified.
-201 -url value is invalid.
-204 -action value is invalid.
-205 -blocking value is invalid.
-206 -collection value is invalid.
-207 -dbprotocol value is invalid.
-208 -keepdynamic value is invalid.
-210 -reopt value is invalid.
-211 -size value is invalid.
-212 -tracelevel value is invalid.
-307 -dbprotocol value is not supported by the target data server.
-308 -keepdynamic value is not supported by the target data server.
-310 -reopt value is not supported by the target data server.
DB2LobTableCreator utility
The DB2LobTableCreator utility creates tables on a DB2 for z/OS database server.
Those tables are required by JDBC or SQLJ applications that use LOB locators to
access data in DBCLOB or CLOB columns.
DB2LobTableCreator syntax
java com.ibm.db2.jcc.DB2LobTableCreator -url jdbc:db2: //server / database
:port
Chapter 2. Installing the IBM Data Server Driver for JDBC and SQLJ 15
-password
Specifes the password for the user ID.
-help
Specifies that the DB2LobTableCreator utility describes each of the options that
it supports. If any other options are specified with -help, they are ignored.
Each IBM Data Server Driver for JDBC and SQLJ configuration property setting is
of this form:
property=value
2. Run the com.ibm.db2.jcc.DB2Binder utility to bind the DB2 packages that are
used at the server by the IBM Data Server Driver for JDBC and SQLJ.
3. On DB2 for z/OS database servers, customize and run job DSNTIJMS.
DSNTIJMS is located in data set prefix.SDSNSAMP. It performs the following
functions:
v Creates the following stored procedures to support DatabaseMetaData
methods, tracing, and error message formatting.
– SQLCOLPRIVILEGES
– SQLCOLUMNS
– SQLFOREIGNKEYS
– SQLFUNCTIONS
– SQLFUNCTIONCOLUMNS
– SQLGETTYPEINFO
– SQLPRIMARYKEYS
– SQLPROCEDURECOLS
– SQLPROCEDURES
– SQLSPECIALCOLUMNS
– SQLSTATISTICS
– SQLTABLEPRIVILEGES
– SQLTABLES
– SQLUDTS
– SQLCAMESSAGE
v Creates the following tables to support efficient storing of data in CLOB or
DBCLOB columns and the use of LOB locators for CLOB or DBCLOB
retrieval:
– SYSIBM.SYSDUMMYU
– SYSIBM.SYSDUMMYA
– SYSIBM.SYSDUMMYE
An alternative way to create those tables is to run the
com.ibm.db2.jcc.DB2LobTableCreator utility on the client, against each of the
DB2 for z/OS servers.
4. Enable Unicode support for OS/390® and z/OS servers.
If any SQLJ or JDBC programs will use IBM Data Server Driver for JDBC and
SQLJ type 4 connectivity to connect to a DB2 for z/OS Version 7 server, the
OS/390 or z/OS operating system must support the Unicode UTF-8 encoding
scheme. This support requires OS/390 Version 2 Release 9 with APAR
Chapter 2. Installing the IBM Data Server Driver for JDBC and SQLJ 17
OW44581, or a later release of OS/390 or z/OS, plus the OS/390 R8/R9/R10
Support for Unicode. Information APARs II13048 and II13049 contain additional
information.
5. If you plan to use IBM Data Server Driver for JDBC and SQLJ type 4
connectivity to implement distributed transactions against DB2 for z/OS
Version 7 servers, run the DB2T4XAIndoubtUtil utility once for each of those
DB2 for z/OS Version 7 servers.
DB2T4XAIndoubtUtil authorization
DB2T4XAIndoubtUtil syntax
java com.ibm.db2.jcc.DB2T4XAIndoubtUtil -url jdbc:db2: //server / database
:port
-priqty integer -secqty integer -bindonly -showSQL
Chapter 2. Installing the IBM Data Server Driver for JDBC and SQLJ 19
Important: The -priqty value divided by the page size for the table space in
which SYSIBM.INDOUBT resides must be greater than the maximum number
of indoubt transactions that are allowed at a given time. For example, for a 4
KB page size, the default -priqty value of 1000 allows about 250 concurrent
indoubt transactions.
-secqty
Specifies the secondary space allocation, in kilobytes, for the table space that
contains the SYSIBM.INDOUBT table. The default value for -secqty is 0.
Recommendation: Always use the default value of 0 for the -secqty value, and
specify a -priqty value that is large enough to accommodate the maximum
number of concurrent indoubt transactions.
-bindonly
Specifies that the DB2T4XAIndoubtUtil utility binds the T4XAIN01, T4XAIN02,
T4XAIN03, and T4XAIN04 packages and grants permission to PUBLIC to
execute the packages, but does not create the SYSIBM.INDOUBT table.
-showSQL
Specifies that the DB2T4XAIndoubtUtil utility displays the SQL statements that
it executes.
-jdbcCollection collection-name|NULLID
Specifies the value of the -collection parameter that was used when the IBM
Data Server Driver for JDBC and SQLJ packages were bound with the
DB2Binder utility. The -jdbcCollection parameter must be specified if the
explicitly or implicitly specified value of the -collection parameter was not
NULLID.
The default is -jdbcCollection NULLID.
To create the SYSTEM.INDOUBT table and its index manually, use these SQL
statements:
CREATE TABLESPACE INDBTTS
USING STOGROUP
LOCKSIZE ROW
BUFFERPOOL BP0
SEGSIZE 32
CCSID EBCDIC;
DB2T4XAIndoubtUtil example
Run the DB2T4XAIndoubtUtil to allow a DB2 for OS/390 and z/OS Version 7
subsystem that has IP address mvs1, port number 446, and DB2 location name
SJCEC1 to participate in XA distributed transactions.
java com.ibm.db2.jcc.DB2T4XAIndoubtUtil -url jdbc:db2://mvs1:446/SJCEC1 \
-user SYSADM -password mypass
Although the tasks that you need to perform are similar to those in other
languages, the way that you execute those tasks is somewhat different.
// Check the that first argument has the correct form for the portion
// of the URL that follows jdbc:db2:,
// as described
// in the Connecting to a data source using the DriverManager
// interface with the IBM Data Server Driver for JDBC and SQLJ topic.
// For example, for IBM Data Server Driver for
// JDBC and SQLJ type 2 connectivity,
// args[0] might be MVS1DB2M. For
// type 4 connectivity, args[0] might
// be //stlmvs1:10110/MVS1DB2M.
if (args.length!=3)
{
System.err.println ("Invalid value. First argument appended to "+
"jdbc:db2: must specify a valid URL.");
System.err.println ("Second argument must be a valid user ID.");
System.err.println ("Third argument must be the password for the user ID.");
// Create the connection using the IBM Data Server Driver for JDBC and SQLJ
con = DriverManager.getConnection (url, user, password); 3b
// Commit changes manually
con.setAutoCommit(false);
System.out.println("**** Created a JDBC connection to the data source");
catch (ClassNotFoundException e)
{
System.err.println("Could not load JDBC driver");
System.out.println("Exception: " + e);
e.printStackTrace();
}
Note Description
1 This statement imports the java.sql package, which contains the JDBC core API.
For information on other Java packages that you might need to access, see "Java
packages for JDBC support".
2 String variable empNo performs the function of a host variable. That is, it is
used to hold data retrieved from an SQL query. See "Variables in JDBC
applications" for more information.
3a and 3b These two sets of statements demonstrate how to connect to a data source using
one of two available interfaces. See "How JDBC applications connect to a data
source" for more details.
Step 3a (loading the JDBC driver) is not necessary if you use JDBC 4.0.
4a and 4b These two sets of statements demonstrate how to perform a SELECT in JDBC.
For information on how to perform other SQL operations, see "JDBC interfaces
for executing SQL".
5 This try/catch block demonstrates the use of the SQLException class for SQL
error handling. For more information on handling SQL errors, see "Handling an
SQLException under the IBM Data Server Driver for JDBC and SQLJ". For
information on handling SQL warnings, see "Handling an SQLWarning under
the IBM Data Server Driver for JDBC and SQLJ".
6 This statement disconnects the application from the data source. See
"Disconnecting from data sources in JDBC applications".
The IBM Data Server Driver for JDBC and SQLJ supports type 2 and type 4
connectivity. Connections to DB2 databases can use type 2 or type 4 connectivity.
Connections to IBM Informix (IDS) databases can use type 4 connectivity.
The following figure shows how a Java application connects to a data source using
IBM Data Server Driver for JDBC and SQLJ type 2 connectivity.
DriverManager
or
DataSource
JDBC driver*
Local database
or DB2
subsystem
Database
server
Figure 2. Java application flow for IBM Data Server Driver for JDBC and SQLJ type 2
connectivity
The following figure shows how a Java application connects to a data source using
IBM Data Server Driver for JDBC and SQLJ type 4 connectivity.
Java application
DriverManager
or
DataSource
JDBC driver*
DRDA
Database
server
Figure 3. Java application flow for IBM Data Server Driver for JDBC and SQLJ type 4
connectivity
The Java application first loads the JDBC driver by invoking the Class.forName
method. After the application loads the driver, it connects to a data source by
invoking the DriverManager.getConnection method.
For the DB2 JDBC Type 2 Driver for Linux, UNIX and Windows (DB2 JDBC Type 2
Driver), you load the driver by invoking the Class.forName method with the
following argument:
COM.ibm.db2.jdbc.app.DB2Driver
The following code demonstrates loading the DB2 JDBC Type 2 Driver:
try {
// Load the DB2 JDBC Type 2 Driver with DriverManager
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
The catch block is used to print an error if the driver is not found.
After you load the driver, you connect to the data source by invoking the
DriverManager.getConnection method. You can use one of the following forms of
getConnection:
getConnection(String url);
getConnection(String url, user, password);
getConnection(String url, java.util.Properties info);
For the DB2 JDBC Type 2 Driver, specify a URL of the following form:
Specifying a user ID and password for a connection: There are several ways to specify a
user ID and password for a connection:
v Use the form of the getConnection method that specifies user and password.
Example: Setting the user ID and password in user and password parameters:
String url = "jdbc:db2:toronto";
// Set URL for data source
String user = "db2adm";
String password = "db2adm";
Connection con = DriverManager.getConnection(url, user, password);
// Create connection
The catch block is used to print an error if the driver is not found.
2. Connect to a data source by invoking the DriverManager.getConnection
method.
You can use one of the following forms of getConnection:
getConnection(String url);
getConnection(String url, user, password);
getConnection(String url, java.util.Properties info);
For IBM Data Server Driver for JDBC and SQLJ type 4 connectivity, the
getConnection method must specify a user ID and password, through
parameters or through property values.
Example: Establishing a connection and setting the user ID and password in a URL:
String url = "jdbc:db2://myhost:5021/mydb:" +
"user=dbadm;password=dbadm;";
Example: Establishing a connection and setting the user ID and password in user and
password parameters:
String url = "jdbc:db2://myhost:5021/mydb";
// Set URL for data source
String user = "dbadm";
String password = "dbadm";
Connection con = DriverManager.getConnection(url, user, password);
// Create connection
URL format for IBM Data Server Driver for JDBC and SQLJ type
4 connectivity
If you are using type 4 connectivity in your JDBC application, and you are making
a connection using the DriverManager interface, you need to specify a URL in the
DriverManager.getConnection call that indicates type 4 connectivity.
IBM Data Server Driver for JDBC and SQLJ type 4 connectivity URL
syntax
URL format for IBM Data Server Driver for JDBC and SQLJ type
2 connectivity
If you are using type 2 connectivity in your JDBC application, and you are making
a connection using the DriverManager interface, you need to specify a URL in the
DriverManager.getConnection call that indicates type 2 connectivity.
IBM Data Server Driver for JDBC and SQLJ type 2 connectivity URL
syntax
property = value ;
IBM Data Server Driver for JDBC and SQLJ type 2 connectivity URL
options descriptions
When you connect to a data source using the DataSource interface, you use a
DataSource object.
The simplest way to use a DataSource object is to create and use the object in the
same application, as you do with the DriverManager interface. However, this
method does not provide portability.
The best way to use a DataSource object is for your system administrator to create
and manage it separately, using WebSphere Application Server or some other tool.
The program that creates and manages a DataSource object also uses the Java
Naming and Directory Interface (JNDI) to assign a logical name to the DataSource
object. The JDBC application that uses the DataSource object can then refer to the
object by its logical name, and does not need any information about the underlying
data source. In addition, your system administrator can modify the data source
attributes, and you do not need to change your application program.
To learn about deploying DataSource objects yourself, see "Creating and deploying
DataSource objects".
You can use the DataSource interface and the DriverManager interface in the same
application, but for maximum portability, it is recommended that you use only the
DataSource interface to obtain connections.
Use the second form if you need to specify a user ID and password for the
connection that are different from the ones that were specified when the
DataSource was deployed.
Example of obtaining a connection using a DataSource object that was created by the
system administrator: In this example, the logical name of the data source that you
need to connect to is jdbc/sampledb. The numbers to the right of selected
statements correspond to the previously-described steps.
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
...
Context ctx=new InitialContext(); 2
DataSource ds=(DataSource)ctx.lookup("jdbc/sampledb"); 3
Connection con=ds.getConnection(); 4
Note Description
1 Import the package that contains the implementation of the DataSource interface.
2 Creates a DB2SimpleDataSource object. DB2SimpleDataSource is one of the IBM
Data Server Driver for JDBC and SQLJ implementations of the DataSource
interface. See "Creating and deploying DataSource objects" for information on
DB2's DataSource implementations.
For the DriverManager interface, you specify the type of connectivity through the
URL in the DriverManager.getConnection method. For the DataSource interface,
you specify the type of connectivity through the driverType property.
The following table summarizes the differences between type 2 connectivity and
type 4 connectivity:
Table 6. Comparison of IBM Data Server Driver for JDBC and SQLJ type 2 connectivity and IBM Data Server Driver
for JDBC and SQLJ type 4 connectivity
IBM Data Server Driver for JDBC IBM Data Server Driver for JDBC
and SQLJ type 2 connectivity and SQLJ type 4 connectivity
Function support support
Sysplex workload balancing and Supported through DB2 Connect Supported directly by the driver for a
connection concentrator connection within a single JVM
The following points can help you determine which type of connectivity to use.
Use IBM Data Server Driver for JDBC and SQLJ type 2 connectivity under these
circumstances:
v Your JDBC or SQLJ application runs locally most of the time.
Local applications have better performance with type 2 connectivity.
v You are running a Java stored procedure.
A stored procedure environment consists of two parts: a client program, from
which you call a stored procedure, and a server program, which is the stored
Use IBM Data Server Driver for JDBC and SQLJ type 4 connectivity under these
circumstances:
v Your JDBC or SQLJ application runs remotely most of the time.
Remote applications have better performance with type 4 connectivity.
v You are using IBM Data Server Driver for JDBC and SQLJ connection
concentrator and Sysplex workload balancing support.
The IBM Data Server Driver for JDBC and SQLJ provides the following DataSource
implementations:
v com.ibm.db2.jcc.DB2SimpleDataSource, which does not support connection
pooling. You can use this implementation with IBM Data Server Driver for JDBC
and SQLJ type 2 connectivity or IBM Data Server Driver for JDBC and SQLJ
type 4 connectivity.
v com.ibm.db2.jcc.DB2ConnectionPoolDataSource, which supports connection
pooling. You can use this implementation with IBM Data Server Driver for JDBC
and SQLJ type 2 connectivity or IBM Data Server Driver for JDBC and SQLJ
type 4 connectivity.
The DB2 JDBC Type 2 Driver provides the following DataSource implementations:
v COM.ibm.db2.jdbc.DB2DataSource, which is enabled for connection pooling.
With this implementation, connection pooling is handled internally and is
transparent to the application.
v COM.ibm.db2.jdbc.DB2XADataSource, which does not have built-in support for
distributed transactions and connection pooling. With this implementation, you
must manage the distributed transactions and connection pooling yourself,
either by writing your own code or by using a tool such as WebSphere
Application Server.
When you create and deploy a DataSource object, you need to perform these tasks:
1. Create an instance of the appropriate DataSource implementation.
2. Set the properties of the DataSource object.
3. Register the object with the Java Naming and Directory Interface (JNDI)
naming service.
dbds.setDatabaseName("db2loc1"); 2
dbds.setDescription("Our Sample Database");
dbds.setUser("john");
dbds.setPassword("mypw");
...
Context ctx=new InitialContext(); 3
Ctx.bind("jdbc/sampledb",dbds); 4
Note Description
1 Creates an instance of the DB2SimpleDataSource class.
2 This statement and the next three statements set values for properties of this
DB2SimpleDataSource object.
3 Creates a context for use by JNDI.
4 Associates DBSimple2DataSource object dbds with the logical name
jdbc/sampledb. An application that uses this object can refer to it by the name
jdbc/sampledb.
In generic applications that can access various data sources, you need to test
whether a data source can handle various database operations before you execute
them. For example, you need to determine whether the driver at a data source is at
the JDBC 3.0 level before you invoke JDBC 3.0 methods against that driver.
Connection con;
DatabaseMetaData dbmtadta;
ResultSet rs;
int mtadtaint;
String procSchema;
String procName;
String dtfnList;
...
dbmtadta = con.getMetaData(); // Create the DatabaseMetaData object 1
mtadtaint = dmtadta.getDriverVersion(); 2
// Check the driver version
System.out.println("Driver version: " + mtadtaint);
rs = dbmtadta.getProcedures(null, null, "%");
// Get information for all procedures
while (rs.next()) { // Position the cursor 3a
procSchema = rs.getString("PROCEDURE_SCHEM");
// Get procedure schema
procName = rs.getString("PROCEDURE_NAME");
// Get procedure name
System.out.println(procSchema + "." + procName);
// Print the qualified procedure name
}
dtfnList = dbmtadta.getTimeDateFunctions();
// Get list of supported datetime functions
System.out.println("Supported datetime functions:");
System.out.println(dtfnList); // Print the list of datetime functions
rs.close(); // Close the ResultSet 3b
Some of those identifiers have the same function as host variables in other
languages: they hold data that you pass to or retrieve from database tables.
Identifier empNo in the following code holds data that you retrieve from the
EMPNO table column, which has the CHAR data type.
String empNo;
// Execute a query and generate a ResultSet instance
rs = stmt.executeQuery("SELECT EMPNO FROM EMPLOYEE");
while (rs.next()) {
String empNo = rs.getString(1);
System.out.println("Employee number = " + empNo);
}
Your choice of Java data types can affect performance because DB2 picks better
access paths when the data types of your Java variables map closely to the DB2
data types.
The following code creates Statement object stmt, executes the UPDATE statement,
and returns the number of rows that were updated in numUpd. The numbers to the
right of selected statements correspond to the previously-described steps.
Connection con;
Statement stmt;
int numUpd;
...
stmt = con.createStatement(); // Create a Statement object 1
numUpd = stmt.executeUpdate(
"UPDATE EMPLOYEE SET PHONENO=’4657’ WHERE EMPNO=’000010’"); 2
// Perform the update
stmt.close(); // Close Statement object 3
DB2 for z/OS does not support dynamic execution of the CALL statement. For
calls to stored procedures that are on DB2 for z/OS data sources, the parameters
can be parameter markers or literals, but not expressions. The following types of
literals are supported:
v Integer
v Double
v Decimal
v Character
v Hexadecimal
v Graphic
For calls to stored procedures that are on IBM Informix data sources, the
PreparedStatement object can be a CALL statement or an EXECUTE PROCEDURE
statement.
When you execute an SQL statement many times, you can get better performance
by creating the SQL statement as a PreparedStatement.
For example, the following UPDATE statement lets you update the employee table
for only one phone number and one employee number:
UPDATE EMPLOYEE SET PHONENO=’4657’ WHERE EMPNO=’000010’
Suppose that you want to generalize the operation to update the employee table
for any set of phone numbers and employee numbers. You need to replace the
constant phone number and employee number with variables:
UPDATE EMPLOYEE SET PHONENO=? WHERE EMPNO=?
Variables of this form are called parameter markers. To execute an SQL statement
with parameter markers, you need to perform these steps:
1. Invoke the Connection.prepareStatement method to create a PreparedStatement
object.
2. Invoke the PreparedStatement.setXXX methods to pass values to the input
variables.
This step assumes that you use standard parameter markers. Alternatively, if
you use named parameter markers, you useIBM Data Server Driver for JDBC
and SQLJ-only methods to pass values to the input parameters.
3. Invoke the PreparedStatement.executeUpdate method to update the table with
the variable values.
4. Invoke the PreparedStatement.close method to close the PreparedStatement
object when you have finished using that object.
The following code performs the previous steps to update the phone number to
'4657' for the employee with employee number '000010'. The numbers to the right
of selected statements correspond to the previously-described steps.
You can also use the PreparedStatement.executeUpdate method for statements that
have no parameter markers. The steps for executing a PreparedStatement object
with no parameter markers are similar to executing a PreparedStatement object
with parameter markers, except you skip step 2 on page 39. The following example
demonstrates these steps.
Connection con;
PreparedStatement pstmt;
int numUpd;
...
pstmt = con.prepareStatement(
"UPDATE EMPLOYEE SET PHONENO=’4657’ WHERE EMPNO=’000010’");
// Create a PreparedStatement object 1
numUpd = pstmt.executeUpdate(); // Perform the update 3
pstmt.close(); // Close the PreparedStatement object 4
For executeUpdate statements against a DB2 for z/OS server, the value that is
returned depends on the type of SQL statement that is being executed:
v For an SQL statement that can have an update count, such as an INSERT,
UPDATE, DELETE, or MERGE statement, the returned value is the number of
affected rows. It can be:
– A positive number, if a positive number of rows are affected by the operation,
and the operation is not a mass delete on a segmented table space.
– 0, if no rows are affected by the operation.
– -1, if the operation is a mass delete on a segmented table space.
v For an SQL CALL statement, a value of -1 is returned, because the data source
cannot determine the number of affected rows. Calls to getUpdateCount or
getMoreResults for a CALL statement also return -1.
v For any other SQL statement, a value of -1 is returned.
If a statement has input parameters or host expressions, you can include that
statement only in a batch that has other instances of the same statement. This type
of batch is known as a homogeneous batch. If a statement has no input parameters,
you can include that statement in a batch only if the other statements in the batch
have no input parameters or host expressions. This type of batch is known as a
heterogeneous batch. Two statements that can be included in the same batch are
known as batch compatible.
Use the following Statement methods for creating, executing, and removing a batch
of SQL updates:
v addBatch
v executeBatch
v clearBatch
To make batch updates using several statements with no input parameters, follow
these basic steps:
1. For each SQL statement that you want to execute in the batch, invoke the
addBatch method.
2. Invoke the executeBatch method to execute the batch of statements.
3. Check for errors. If no errors occurred:
a. Get the number of rows that were affect by each SQL statement from the
array that the executeBatch invocation returns. This number does not
include rows that were affected by triggers or by referential integrity
enforcement.
b. If AutoCommit is disabled for the Connection object, invoke the commit
method to commit the changes.
If AutoCommit is enabled for the Connection object, the IBM Data Server
Driver for JDBC and SQLJ adds a commit method at the end of the batch.
To make batch updates using a single statement with several sets of input
parameters, follow these basic steps:
1. If the batched statement is a searched UDPATE, searched DELETE, or MERGE
statement, set the autocommit mode for the connection to false.
2. Invoke the prepareStatement method to create a PreparedStatement object.
In the following code fragment, two sets of parameters are batched. An UPDATE
statement that takes two input parameters is then executed twice, once with each
set of parameters. The numbers to the right of selected statements correspond to
the previously-described steps.
try {
...
PreparedStatement preps = conn.prepareStatement(
"UPDATE DEPT SET MGRNO=? WHERE DEPTNO=?"); 2
ps.setString(1,mgrnum1); 3a
ps.setString(2,deptnum1);
ps.addBatch(); 3b
ps.setString(1,mgrnum2);
ps.setString(2,deptnum2);
ps.addBatch();
int [] numUpdates=ps.executeBatch(); 4
for (int i=0; i < numUpdates.length; i++) { 5a
if (numUpdates[i] == SUCCESS_NO_INFO)
System.out.println("Execution " + i +
": unknown number of rows updated");
else
Connection con;
ParameterMetaData pmtadta;
int mtadtacnt;
String sqlType;
...
pstmt = con.prepareStatement(
"UPDATE EMPLOYEE SET PHONENO=? WHERE EMPNO=?");
// Create a PreparedStatement object 1
pmtadta = pstmt.getParameterMetaData(); 2
// Create a ParameterMetaData object
mtadtacnt = pmtadta.getParameterCount(); 3
// Determine the number of parameters
System.out.println("Number of statement parameters: " + mtadtacnt);
for (int i = 1; i <= mtadtacnt; i++) {
sqlType = pmtadta.getParameterTypeName(i); 4
// Get SQL type for each parameter
System.out.println("SQL type of parameter " + i " is " + sqlType);
}
...
pstmt.close(); // Close the PreparedStatement
This method returns a result table in a ResultSet object. After you obtain the result
table, you need to use ResultSet methods to move through the result table and
obtain the individual column values from each row.
This topic discusses the simplest kind of ResultSet, which is a read-only ResultSet
in which you can only move forward, one row at a time. The IBM Data Server
Driver for JDBC and SQLJ also supports updatable and scrollable ResultSets.
The following code demonstrates how to retrieve all rows from the employee table.
The numbers to the right of selected statements correspond to the
previously-described steps.
String empNo;
Connection con;
Statement stmt;
ResultSet rs;
...
stmt = con.createStatement(); // Create a Statement object 1
rs = stmt.executeQuery("SELECT EMPNO FROM EMPLOYEE"); 2
// Get the result table from the query
while (rs.next()) { // Position the cursor 3
empNo = rs.getString(1); // Retrieve only the first column value
System.out.println("Employee number = " + empNo);
// Print the column value
}
rs.close(); // Close the ResultSet 4
stmt.close(); // Close the Statement 5
This method returns a result table in a ResultSet object. After you obtain the result
table, you need to use ResultSet methods to move through the result table and
obtain the individual column values from each row.
With the IBM Data Server Driver for JDBC and SQLJ, you can also use the
PreparedStatement.executeQuery method to retrieve a result set from a stored
procedure call, if that stored procedure returns only one result set and has only
input parameters. If the stored procedure returns multiple result sets, you need to
use the PreparedStatement.execute method.
To retrieve rows from a table using a SELECT statement with parameter markers,
you need to perform these steps:
1. Invoke the Connection.prepareStatement method to create a PreparedStatement
object.
2. Invoke PreparedStatement.setXXX methods to pass values to the input
parameters.
3. Invoke the PreparedStatement.executeQuery method to obtain the result table
from the SELECT statement in a ResultSet object.
4. In a loop, position the cursor using the ResultSet.next method, and retrieve
data from each column of the current row of the ResultSet object using getXXX
methods.
5. Invoke the ResultSet.close method to close the ResultSet object.
6. Invoke the PreparedStatement.close method to close the PreparedStatement
object when you have finished using that object.
The following code demonstrates how to retrieve rows from the employee table for
a specific employee. The numbers to the right of selected statements correspond to
the previously-described steps.
To make batch queries using a single statement with several sets of input
parameters, follow these basic steps:
1. Invoke the prepareStatement method to create a PreparedStatement object for
the SQL statement with input parameters.
2. For each set of input parameter values:
Example: In the following code fragment, two sets of parameters are batched. A
SELECT statement that takes one input parameter is then executed twice, once
with each parameter value. The numbers to the right of selected statements
correspond to the previously described steps.
java.sql.Connection con = java.sql.DriverManager.getConnection(url, properties);
java.sql.Statement s = con.createStatement();
// Clean up from previous executions
try {
s.executeUpdate ("drop table TestQBatch");
}
catch (Exception e) {
}
try {
PreparedStatement pstmt = 1
con.prepareStatement("Select * from TestQBatch where col1 = ?");
pstmt.setInt(1,1); 2a
pstmt.addBatch(); 2b
// Add some more values to the batch
pstmt.setInt(1,2);
pstmt.addBatch();
pstmt.setInt(1,3);
pstmt.addBatch();
pstmt.setInt(1,4);
pstmt.addBatch();
((com.ibm.db2.jcc.DB2PreparedStatement)pstmt).executeDB2QueryBatch();
3
} catch(BatchUpdateException b) {
// process BatchUpdateException
}
ResultSet rs;
while(pstmt.getMoreResults()) { 4
rs = pstmt.getResultSet(); 4a
while (rs.next()) { 4b
System.out.print (rs.getInt (1) + " ");
System.out.println (rs.getString (2));
}
System.out.println();
rs.close ();
}
When you write programs that retrieve unknown ResultSets, you need to use
ResultSetMetaData methods to determine the characteristics of the ResultSets
before you can retrieve data from them.
After you invoke the executeQuery method to generate a ResultSet for a query on
a table, follow these basic steps to determine the contents of the ResultSet:
1. Invoke the getMetaData method on the ResultSet object to create a
ResultSetMetaData object.
2. Invoke the getColumnCount method to determine how many columns are in
the ResultSet.
3. For each column in the ResultSet, execute ResultSetMetaData methods to
determine column characteristics.
The results of ResultSetMetaData.getColumnName call reflects the column
name information that is stored in the DB2 catalog for that data source.
The following code demonstrates how to determine the data types of all the
columns in the employee table. The numbers to the right of selected statements
correspond to the previously-described steps.
In addition to moving forward, one row at a time, through a ResultSet, you might
want to do the following things:
v Move backward or go directly to a specific row
v Update, delete, or insert rows in a ResultSet
v Leave the ResultSet open after a COMMIT
If a JDBC ResultSet is static, the size of the result table and the order of the rows in
the result table do not change after the cursor is opened. This means that if you
insert rows into the underlying table, the result table for a static ResultSet does not
change. If you delete a row of a result table, a delete hole occurs. You cannot
update or delete a delete hole.
By default, ResultSet objects are not scrollable and not updatable. The default
holdability depends on the data source, and can be determined from the
DatabaseMetaData.getResultSetHoldability method. To change the scrollability,
updatability, and holdability attributes for a ResultSet, follow these steps:
1. If the SELECT statement that defines the ResultSet has no input parameters,
invoke the createStatement method to create a Statement object. Otherwise,
invoke the prepareStatement method to create a PreparedStatement object. You
need to specify forms of the createStatement or prepareStatement methods that
include the resultSetType, resultSetConcurrency, or resultSetHoldability parameters.
The form of the createStatement method that supports scrollability and
updatability is:
createStatement(int resultSetType, int resultSetConcurrency);
b. If you need to know the current cursor position, use the getRow, isFirst,
isLast, isBeforeFirst, or isAfterLast method to obtain this information.
c. If you specified a resultSetType value of TYPE_SCROLL_SENSITIVE in step 1 on
page 51, and you need to see the latest values of the current row, invoke the
refreshRow method.
Recommendation: Because refreshing the rows of a ResultSet can have a
detrimental effect on the performance of your applications, you should
invoke refreshRow only when you need to see the latest data.
d. Perform one or more of the following operations:
v To retrieve data from each column of the current row of the ResultSet
object, use getXXX methods.
v To update the current row from the underlying table, use updateXXX
methods to assign column values to the current row of the ResultSet.
Then use updateRow to update the corresponding row of the underlying
table. If you decide that you do not want to update the underlying table,
invoke the cancelRowUpdates method instead of the updateRow method.
The resultSetConcurrency value for the ResultSet must be
CONCUR_UPDATABLE for you to use these methods.
v To delete the current row from the underlying table, use the deleteRow
method. Invoking deleteRow causes the driver to replace the current row
of the ResultSet with a hole.
The resultSetConcurrency value for the ResultSet must be
CONCUR_UPDATABLE for you to use this method.
5. Invoke the close method to close the ResultSet object.
6. Invoke the close method to close the Statement or PreparedStatement object.
The following code demonstrates how to retrieve all rows from the employee table
in reverse order, and update the phone number for employee number "000010".
The numbers to the right of selected statements correspond to the
previously-described steps.
The IBM Data Server Driver for JDBC and SQLJ supports multi-row INSERT,
UPDATE, and FETCH for connections to data sources that support these
operations.
Multi-row INSERT
In JDBC applications, when you execute INSERT or MERGE statements that use
parameter markers in a batch, if the data server supports multi-row INSERT, the
IBM Data Server Driver for JDBC and SQLJ can transform the batch INSERT or
MERGE operations into multi-row INSERT statements. Multi-row INSERT
operations can provide better performance in the following ways:
v For local applications, multi-row INSERTs result in fewer accesses of the data
server.
v For distributed applications, multi-row INSERTs result in fewer network
operations.
Multi-row INSERT is used by default. You can use the Connection or DataSource
property enableMultiRowInsertSupport to control whether multi-row INSERT is
used. Multi-row INSERT cannot be used for INSERT FROM SELECT statements
that are executed in a batch.
Multi-row FETCH can provide better performance than retrieving one row with
each FETCH statement. For IBM Data Server Driver for JDBC and SQLJ type 2
connectivity on DB2 for z/OS, multi-row FETCH can be used for forward-only
cursors and scrollable cursors. For IBM Data Server Driver for JDBC and SQLJ type
4 connectivity, multi-row FETCH can be used only for scrollable cursors.
When you retrieve data in your applications, the IBM Data Server Driver for JDBC
and SQLJ determines whether to use multi-row FETCH, depending on several
factors:
v The settings of the enableRowsetSupport and useRowsetCursor properties
v The type of IBM Data Server Driver for JDBC and SQLJ connectivity that is
being used
v The version of the IBM Data Server Driver for JDBC and SQLJ
For IBM Data Server Driver for JDBC and SQLJ type 4 connectivity to DB2 for
z/OS, one of the following sets of conditions must be true for multi-row FETCH to
be used.
v First set of conditions:
– The IBM Data Server Driver for JDBC and SQLJ version is 3.51 or later.
– The enableRowsetSupport property value is
com.ibm.db2.jcc.DB2BaseDataSource.YES (1), or the enableRowsetSupport
property value is com.ibm.db2.jcc.DB2BaseDataSource.NOT_SET (0) and the
useRowsetCursor property value is com.ibm.db2.jcc.DB2BaseDataSource.YES
(1).
– The FETCH operation uses a scrollable cursor.
For forward-only cursors, fetching of multiple rows might occur through
DRDA block FETCH. However, this behavior does not utilize the data
source's multi-row FETCH capability.
v Second set of conditions:
– The IBM Data Server Driver for JDBC and SQLJ version is 3.1.
– The useRowsetCursor property value is
com.ibm.db2.jcc.DB2BaseDataSource.YES (1).
– The FETCH operation uses a scrollable cursor.
For forward-only cursors, fetching of multiple rows might occur through
DRDA block FETCH. However, this behavior does not utilize the data
source's multi-row FETCH capability.
For IBM Data Server Driver for JDBC and SQLJ type 2 connectivity to DB2 for
z/OS the following conditions must be true for multi-row FETCH to be used.
v The IBM Data Server Driver for JDBC and SQLJ version is 3.51 or later.
v The enableRowsetSupport property value is
com.ibm.db2.jcc.DB2BaseDataSource.YES (1).
v The FETCH operation uses a scrollable cursor or a forward-only cursor.
For IBM Data Server Driver for JDBC and SQLJ type 2 connectivity on DB2 for
z/OS, you can control the maximum size of a rowset for each statement by setting
the maxRowsetSize property.
The IBM Data Server Driver for JDBC and SQLJ supports a technique for
performing positioned update or delete operations that follows the JDBC 1
standard. That technique involves using the ResultSet.getCursorName method to
obtain the name of the cursor for the ResultSet, and defining a positioned UPDATE
or positioned DELETE statement of the following form:
UPDATE table SET col1=value1,...coln=valueN WHERE CURRENT OF cursorname
DELETE FROM table WHERE CURRENT OF cursorname
Multi-row UPDATE or DELETE when useRowsetCursor is set to true: If you use the
JDBC 1 technique to update or delete data on a database server that supports
multi-row FETCH, and multi-row FETCH is enabled through the useRowsetCursor
property, the positioned UPDATE or DELETE statement might update or delete
multiple rows, when you expect it to update or delete a single row. To avoid
unexpected updates or deletes, you can take one of the following actions:
v Use an updatable ResultSet to retrieve and update one row at a time, as shown
in the previous example.
v Set useRowsetCursor to false.
Testing whether the current row of a ResultSet is a delete hole or update hole in
a JDBC application:
After a SENSITIVE STATIC ResultSet is opened, it does not change size. This
means that deleted rows are replaced by placeholders, which are also called holes.
If updated rows no longer fit the criteria for the ResultSet, those rows also become
holes. You cannot retrieve rows that are holes.
To test whether the current row in a ResultSet is a delete hole or update hole,
follow these steps:
1. Call the DatabaseMetaData.deletesAreDetected or
DatabaseMetaData.updatesAreDetected method with the
TYPE_SCROLL_SENSITIVE argument to determine whether the data source
creates holes for a TYPE_SCROLL_SENSITIVE ResultSet.
2. If DatabaseMetaData.deletesAreDetected or
DatabaseMetaData.updatesAreDetected returns true, which means that the data
source can create holes, call the ResultSet.rowDeleted or ResultSet.rowUpdated
method to determine whether the current row is a delete or update hole. If the
method returns true, the current row is a hole.
The following code tests whether the current row is a delete hole.
Example: The following code illustrates inserting a row into a ResultSet that
consists of all rows in the sample DEPARTMENT table. After the row is inserted,
the code places the cursor where it was located in the ResultSet before the insert
operation. The numbers to the right of selected statements correspond to the
previously-described steps.
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM DEPARTMENT");
rs.moveToInsertRow(); 1a
rs.updateString("DEPT_NO", "M13"); 1b
rs.updateString("DEPTNAME", "TECHNICAL SUPPORT");
rs.updateString("MGRNO", "000010");
rs.updateString("ADMRDEPT", "A00");
rs.insertRow(); 1c
rs.moveToCurrentRow(); 2
Testing whether the current row was inserted into a ResultSet in a JDBC
application:
If a ResultSet is dynamic, you can insert rows into it. After you insert rows into a
ResultSet you might need to know which rows were inserted.
To test whether the current row in a ResultSet was inserted, follow these steps:
1. Call the DatabaseMetaData.ownInsertsAreVisible and
DatabaseMetaData.othersInsertsAreVisible methods to determine whether
inserts can be visible to the given type of ResultSet.
2. If inserts can be visible to the ResultSet, call the
DatabaseMetaData.insertsAreDetected method to determine whether the given
type of ResultSet can detect inserts.
3. If the ResultSet can detect inserts, call the ResultSet.rowInserted method to
determine whether the current row was inserted.
The basic steps for calling a stored procedures using standard CallableStatement
methods are:
1. Invoke the Connection.prepareCall method with the CALL statement as its
argument to create a CallableStatement object.
You can represent parameters with standard parameter markers (?) or named
parameter markers. You cannot mix named parameter markers with standard
parameter markers in the same CALL statement.
Restriction: The parameter types that are permitted depend on whether the
data source supports dynamic execution of the CALL statement. DB2 for z/OS
does not support dynamic execution of the CALL statement. For a call to a
stored procedure that is on a DB2 for z/OS database server, the parameters can
be parameter markers or literals, but not expressions. The following table lists
the types of literals that are supported, and the JDBC types to which they map.
Restriction: If the data source does not support dynamic execution of the
CALL statement, you must specify the data types for CALL statement input
parameters exactly as they are specified in the stored procedure definition.
3. Invoke the CallableStatement.registerOutParameter method to register
parameters that are defined as OUT in the CREATE PROCEDURE statement
with specific data types.
This step assumes that you use standard parameter markers. Alternatively, if
you use named parameter markers, you use IBM Data Server Driver for JDBC
and SQLJ-only methods to register OUT parameters with specific data types.
Restriction: If the data source does not support dynamic execution of the
CALL statement, you must specify the data types for CALL statement OUT, IN,
or INOUT parameters exactly as they are specified in the stored procedure
definition.
4. Invoke one of the following methods to call the stored procedure:
CallableStatement.executeUpdate
Invoke this method if the stored procedure does not return result sets.
CallableStatement.executeQuery
Invoke this method if the stored procedure returns one result set.
You can invoke CallableStatement.executeQuery for a stored procedure that
returns no result sets if you set property
allowNullResultSetForExecuteQuery to DB2BaseDataSource.YES (1). In that
case, CallableStatement.executeQuery returns null. This behavior does not
conform to the JDBC standard.
CallableStatement.execute
Invoke this method if the stored procedure returns multiple result sets, or
an unknown number of result sets.
Example: The following code illustrates calling a stored procedure that has one
input parameter, four output parameters, and no returned ResultSets. The numbers
to the right of selected statements correspond to the previously-described steps.
int ifcaret;
int ifcareas;
int xsbytes;
String errbuff;
Connection con;
CallableStatement cstmt;
ResultSet rs;
...
cstmt = con.prepareCall("CALL DSN8.DSN8ED2(?,?,?,?,?)"); 1
// Create a CallableStatement object
cstmt.setString (1, "DISPLAY THREAD(*)"); 2
// Set input parameter (DB2 command)
cstmt.registerOutParameter (2, Types.INTEGER); 3
// Register output parameters
cstmt.registerOutParameter (3, Types.INTEGER);
cstmt.registerOutParameter (4, Types.INTEGER);
cstmt.registerOutParameter (5, Types.VARCHAR);
cstmt.executeUpdate(); // Call the stored procedure 4
ifcaret = cstmt.getInt(2); // Get the output parameter values 6
ifcareas = cstmt.getInt(3);
xsbytes = cstmt.getInt(4);
errbuff = cstmt.getString(5);
cstmt.close(); 7
You can use named parameters in either or both of the following places in a JDBC
application:
v In the CALL statement
With named parameters, you do not need to specify parameters in the CALL
statement in the same order that they appear in the stored procedure definition.
In addition, you do not need to specify all parameters in the CALL statement.
Unspecified parameters take the default values that are specified in the stored
procedure definition.
v In CallableStatement.setXXX, CallableStatement.getXXX, and
CallableStatement.registerOutParameter methods
You can make your programs easier to read by specifying parameter names as
they appear in the stored procedure definition, rather than the positions of the
parameters in the definition.
The following code illustrates calling a stored procedure that has the following
definition:
CREATE PROCEDURE SALS (
OUT retcode INTEGER,
IN lowsal DOUBLE,
IN medsal DOUBLE,
IN highsal DOUBLE DEFAULT 100000,
IN department CHAR(3) DEFAULT ’---’)
SPECIFIC JDBC_SALS
DYNAMIC RESULT SETS 0
DETERMINISTIC
LANGUAGE JAVA
PARAMETER STYLE JAVA
NO DBINFO
cstmt = con.prepareCall(
"CALL SALS(retcode=>?,lowsal=>?,medsal=>?,highsal=>DEFAULT)"); 1
// Prepare the Call statement.
// Implicitly use the default
// value for the last parameter
// by omitting it.
cstmt.setDouble ("lowsal", 10000); 2
cstmt.setDouble ("medsal", 50000);
cstmt.registerOutParameter ("retcode", Types.INTEGER); 3
// Register output parameter
cstmt.executeUpdate(); // Call the stored procedure 4
hvRetCode = cstmt.getInt("retcode"); 6
System.out.println("Return code from SALS call: " + hvRetCode);
cstmt.close(); 7
The steps that you take depend on whether you know how many result sets are
returned, and whether you know the contents of those result sets.
To retrieve result sets when you know the number of result sets and their contents,
follow these steps:
1. Invoke the Statement.execute method, the PreparedStatement.execute method,
or the CallableStatement.execute method to call the stored procedure.
Use PreparedStatement.execute if the stored procedure has input parameters.
2. Invoke the getResultSet method to obtain the first result set, which is in a
ResultSet object.
3. In a loop, position the cursor using the next method, and retrieve data from
each column of the current row of the ResultSet object using getXXX methods.
4. If there are n result sets, repeat the following steps n-1 times:
a. Invoke the getMoreResults method to close the current result set and point
to the next result set.
Example: The following code illustrates retrieving two result sets. The first result
set contains an INTEGER column, and the second result set contains a CHAR
column. The numbers to the right of selected statements correspond to the
previously described steps.
CallableStatement cstmt;
ResultSet rs;
int i;
String s;
...
cstmt.execute(); // Call the stored procedure 1
rs = cstmt.getResultSet(); // Get the first result set 2
while (rs.next()) { // Position the cursor 3
i = rs.getInt(1); // Retrieve current result set value
System.out.println("Value from first result set = " + i);
// Print the value
}
cstmt.getMoreResults(); // Point to the second result set 4a
// and close the first result set
rs = cstmt.getResultSet(); // Get the second result set 4b
while (rs.next()) { // Position the cursor 4c
s = rs.getString(1); // Retrieve current result set value
System.out.println("Value from second result set = " + s);
// Print the value
}
rs.close(); // Close the result set
cstmt.close(); // Close the statement
To retrieve result sets when you do not know the number of result sets or their
contents, you need to retrieve ResultSets, until no more ResultSets are returned.
For each ResultSet, use ResultSetMetaData methods to determine its contents.
After you call a stored procedure, follow these basic steps to retrieve the contents
of an unknown number of result sets.
1. Check the value that was returned from the execute statement that called the
stored procedure.
If the returned value is true, there is at least one result set, so you need to go
to the next step.
2. Repeat the following steps in a loop:
a. Invoke the getResultSet method to obtain a result set, which is in a
ResultSet object. Invoking this method closes the previous result set.
b. Use ResultSetMetaData methods to determine the contents of the ResultSet,
and retrieve data from the ResultSet.
c. Invoke the getMoreResults method to determine whether there is another
result set. If getMoreResults returns true, go to step 1 to get the next result
set.
Keeping result sets open when retrieving multiple result sets from a stored
procedure in a JDBC application:
The getMoreResults method has a form that lets you leave the current ResultSet
open when you open the next ResultSet.
When you call getMoreResults to check for the next ResultSet, use this form:
CallableStatement.getMoreResults(int current);
v To keep the current ResultSet open when you check for the next ResultSet,
specify a value of Statement.KEEP_CURRENT_RESULT for current.
v To close the current ResultSet when you check for the next ResultSet, specify a
value of Statement.CLOSE_CURRENT_RESULT for current.
v To close all ResultSet objects, specify a value of Statement.CLOSE_ALL_RESULTS
for current.
Example: The following code keeps all ResultSets open until the final ResultSet has
been retrieved, and then closes all ResultSets.
CallableStatement cstmt;
...
boolean resultsAvailable = cstmt.execute(); // Call the stored procedure
if (resultsAvailable==true) { // Test for result set
ResultSet rs1 = cstmt.getResultSet(); // Get a result set
...
resultsAvailable = cstmt.getMoreResults(Statement.KEEP_CURRENT_RESULT);
// Check for next result set
// but do not close
// previous result set
if (resultsAvailable==true) { // Test for another result set
ResultSet rs2 = cstmt.getResultSet(); // Get next result set
... // Process either ResultSet
}
}
resultsAvailable = cstmt.getMoreResults(Statement.CLOSE_ALL_RESULTS);
// Close the result sets
Progressive streaming with the IBM Data Server Driver for JDBC
and SQLJ
If the data source supports progressive streaming, also known as dynamic data
format, the IBM Data Server Driver for JDBC and SQLJ can use progressive
streaming to retrieve data in LOB or XML columns.
DB2 for z/OS Version 9.1 and later supports progressive streaming for LOBs and
XML objects. DB2 Database for Linux, UNIX, and Windows Version 9.5 and later,
IBM Informix (IDS) Version 11.50 and later, and DB2 for i V6R1 and later support
progressive streaming for LOBs.
With progressive streaming, the data source dynamically determines the most
efficient mode in which to return LOB or XML data, based on the size of the LOBs
or XML objects.
You set the progressive streaming behavior on new connections using the IBM
Data Server Driver for JDBC and SQLJ progressiveStreaming property.
For DB2 for z/OS Version 9.1 and later data sources, or DB2 Database for Linux,
UNIX, and Windows Version 9.5 and later data sources, you can set the
progressive streaming behavior for existing connections with the
DB2Connection.setDBProgressiveStreaming(DB2BaseDataSource.YES) method. If
you call DB2Connection.setDBProgressiveStreaming(DB2BaseDataSource.YES),
all ResultSet objects that are created on the connection use progressive streaming
behavior.
Important: With progressive streaming, when you retrieve a LOB or XML value
from a ResultSet into an application variable, you can manipulate the contents of
that application variable until you move the cursor or close the cursor on the
ResultSet. After that, the contents of the application variable are no longer
available to you. If you perform any actions on the LOB in the application variable,
you receive an SQLException. For example, suppose that progressive streaming is
enabled, and you execute statements like this:
...
ResultSet rs = stmt.executeQuery("SELECT CLOBCOL FROM MY_TABLE");
rs.next(); // Retrieve the first row of the ResultSet
Clob clobFromRow1 = rs.getClob(1);
// Put the CLOB from the first column of
// the first row in an application variable
String substr1Clob = clobFromRow1.getSubString(1,50);
// Retrieve the first 50 bytes of the CLOB
rs.next(); // Move the cursor to the next row.
// clobFromRow1 is no longer available.
// String substr2Clob = clobFromRow1.getSubString(51,100);
// This statement would yield an SQLException
Clob clobFromRow2 = rs.getClob(1);
// Put the CLOB from the first column of
// the second row in an application variable
rs.close(); // Close the ResultSet.
// clobFromRow2 is also no longer available.
After you execute rs.next() to position the cursor at the second row of the
ResultSet, the CLOB value in clobFromRow1 is no longer available to you.
Similarly, after you execute rs.close() to close the ResultSet, the values in
clobFromRow1 and clobFromRow2 are no longer available.
If you disable progressive streaming, the way in which the IBM Data Server Driver
for JDBC and SQLJ handles LOBs depends on the value of the
fullyMaterializeLobData property.
LOB locators with the IBM Data Server Driver for JDBC and
SQLJ
The IBM Data Server Driver for JDBC and SQLJ can use LOB locators to retrieve
data in LOB columns.
To cause JDBC to use LOB locators to retrieve data from LOB columns, you need
to set the fullyMaterializeLobData property to false and set the
progressiveStreaming property to NO (DB2BaseDataSource.NO in an application
program).
LOB operations with the IBM Data Server Driver for JDBC and
SQLJ
The IBM Data Server Driver for JDBC and SQLJ supports methods for updating
and retrieving data from BLOB, CLOB, and DBCLOB columns in a table, and for
calling stored procedures or user-defined functions with BLOB or CLOB
parameters.
Among the operations that you can perform on LOB data under the IBM Data
Server Driver for JDBC and SQLJ are:
v Specify a BLOB or column as an argument of the following ResultSet methods to
retrieve data from a BLOB or CLOB column:
For BLOB columns:
– getBinaryStream
– getBlob
– getBytes
For CLOB columns:
– getAsciiStream
– getCharacterStream
– getClob
– getString
v Call the following ResultSet methods to update a BLOB or CLOB column in an
updatable ResultSet:
For BLOB columns:
– updateBinaryStream
– updateBlob
For CLOB columns:
– updateAsciiStream
– updateCharacterStream
– updateClob
If you specify -1 for the length parameter in any of the previously listed
methods, the IBM Data Server Driver for JDBC and SQLJ reads the input data
until it is exhausted.
v Use the following PreparedStatement methods to set the values for parameters
that correspond to BLOB or CLOB columns:
For BLOB columns:
– setBytes
– setBlob
Restriction: With IBM Data Server Driver for JDBC and SQLJ type 2 connectivity,
you cannot call a stored procedure that has DBCLOB OUT or INOUT parameters.
If you are using the IBM Data Server Driver for JDBC and SQLJ version 4.0 or
later, you can perform the following additional operations:
v Use ResultSet.updateXXX or PreparedStatement.setXXX methods to update a
BLOB or CLOB with a length value of up to 2GB for a BLOB or CLOB. For
example, these methods are defined for BLOBs:
ResultSet.updateBlob(int columnIndex, InputStream x, long length)
ResultSet.updateBlob(String columnLabel, InputStream x, long length)
ResultSet.updateBinaryStream(int columnIndex, InputStream x, long length)
ResultSet.updateBinaryStream(String columnLabel, InputStream x, long length)
PreparedStatement.setBlob(int columnIndex, InputStream x, long length)
PreparedStatement.setBlob(String columnLabel, InputStream x, long length)
PreparedStatement.setBinaryStream(int columnIndex, InputStream x, long length)
PreparedStatement.setBinaryStream(String columnLabel, InputStream x, long length)
v Use ResultSet.updateXXX or PreparedStatement.setXXX methods without the
length parameter when you update a BLOB or CLOB, to cause the IBM Data
Server Driver for JDBC and SQLJ to read the input data until it is exhausted. For
example:
ResultSet.updateBlob(int columnIndex, InputStream x)
ResultSet.updateBlob(String columnLabel, InputStream x)
ResultSet.updateBinaryStream(int columnIndex, InputStream x)
ResultSet.updateBinaryStream(String columnLabel, InputStream x)
PreparedStatement.setBlob(int columnIndex, InputStream x)
PreparedStatement.setBlob(String columnLabel, InputStream x)
PreparedStatement.setBinaryStream(int columnIndex, InputStream x)
PreparedStatement.setBinaryStream(String columnLabel, InputStream x)
v Create a Blob or Clob object that contains no data, using the
Connection.createBlob or Connection.createClob method.
v Materialize a Blob or Clob object on the client, when progressive streaming or
locators are in use, using the Blob.getBinaryStream or Clob.getCharacterStream
method.
v Free the resources that a Blob or Clob object holds, using the Blob.free or
Clob.free method.
For IN parameters for BLOB columns, or INOUT parameters that are used for
input to BLOB columns, you can use one of the following techniques:
v Use a java.sql.Blob input variable, which is an exact match for a BLOB column:
cstmt.setBlob(parmIndex, blobData);
v Use a CallableStatement.setObject call that specifies that the target data type is
BLOB:
byte[] byteData = {(byte)0x1a, (byte)0x2b, (byte)0x3c};
cstmt.setObject(parmInd, byteData, java.sql.Types.BLOB);
v Use an input parameter of type of java.io.ByteArrayInputStream with a
CallableStatement.setBinaryStream call. A java.io.ByteArrayInputStream object is
compatible with a BLOB data type. For this call, you need to specify the exact
length of the input data:
java.io.ByteArrayInputStream byteStream =
new java.io.ByteArrayInputStream(byteData);
int numBytes = byteData.length;
cstmt.setBinaryStream(parmIndex, byteStream, numBytes);
For OUT parameters for BLOB columns, or INOUT parameters that are used for
output from BLOB columns, you can use the following technique:
v Use the CallableStatement.registerOutParameter call to specify that an output
parameter is of type BLOB. Then you can retrieve the parameter value into any
variable that has a data type that is compatible with a BLOB data type. For
example, the following code lets you retrieve a BLOB value into a byte[]
variable:
cstmt.registerOutParameter(parmIndex, java.sql.Types.BLOB);
cstmt.execute();
byte[] byteData = cstmt.getBytes(parmIndex);
For IN parameters for CLOB columns, or INOUT parameters that are used for
input to CLOB columns, you can use one of the following techniques:
v Use a java.sql.Clob input variable, which is an exact match for a CLOB column:
cstmt.setClob(parmIndex, clobData);
v Use a CallableStatement.setObject call that specifies that the target data type is
CLOB:
String charData = "CharacterString";
cstmt.setObject(parmInd, charData, java.sql.Types.CLOB);
v Use one of the following types of stream input parameters:
– A java.io.StringReader input parameter with a cstmt.setCharacterStream call:
java.io.StringReader reader = new java.io.StringReader(charData);
cstmt.setCharacterStream(parmIndex, reader, charData.length);
– A java.io.ByteArrayInputStream parameter with a cstmt.setAsciiStream call,
for ASCII data:
If the length of the data is greater than 32KB, and the JDBC driver has no
DESCRIBE information about the parameter data type, the JDBC driver assigns
the CLOB data type to the input data.
v Use a String input parameter with a cstmt.setObject call, and specify the target
data type as VARCHAR or LONGVARCHAR:
cstmt.setObject(parmIndex, charData, java.sql.Types.VARCHAR);
If the length of the data is greater than 32KB, and the JDBC driver has no
DESCRIBE information about the parameter data type, the JDBC driver assigns
the CLOB data type to the input data.
For OUT parameters for CLOB columns, or INOUT parameters that are used for
output from CLOB columns, you can use one of the following techniques:
v Use the CallableStatement.registerOutParameter call to specify that an output
parameter is of type CLOB. Then you can retrieve the parameter value into a
Clob variable. For example:
cstmt.registerOutParameter(parmIndex, java.sql.Types.CLOB);
cstmt.execute();
Clob clobData = cstmt.getClob(parmIndex);
v Use the CallableStatement.registerOutParameter call to specify that an output
parameter is of type VARCHAR or LONGVARCHAR:
cstmt.registerOutParameter(parmIndex, java.sql.Types.VARCHAR);
cstmt.execute();
String charData = cstmt.getString(parmIndex);
This technique should be used only if you know that the length of the retrieved
data is less than or equal to 32KB. Otherwise, the data is truncated.
ROWIDs in JDBC with the IBM Data Server Driver for JDBC
and SQLJ
DB2 for z/OS and DB2 for i support the ROWID data type for a column in a
database table. A ROWID is a value that uniquely identifies a row in a table.
Although IBM Informix (IDS) also supports rowids, those rowids have the
INTEGER data type. You can select an IDS rowid column into a variable with a
four-byte integer data type.
You can use the following ResultSet methods to retrieve data from a ROWID
column:
v getRowId (JDBC 4.0 and later)
v getBytes
v getObject
If you are using JDBC 3.0, for getObject, the IBM Data Server Driver for JDBC and
SQLJ returns an instance of the IBM Data Server Driver for JDBC and SQLJ-only
class com.ibm.db2.jcc.DB2RowID.
If you are using JDBC 4.0, for getObject, the IBM Data Server Driver for JDBC and
SQLJ returns an instance of the class java.sql.RowId.
You can use the following PreparedStatement methods to set a value for a
parameter that is associated with a ROWID column:
v setRowId (JDBC 4.0 and later)
v setBytes
v setObject
If you are using JDBC 3.0, for setObject, use the IBM Data Server Driver for JDBC
and SQLJ-only type com.ibm.db2.jcc.Types.ROWID or an instance of the
com.ibm.db2.jcc.DB2RowID class as the target type for the parameter.
If you are using JDBC 4.0, for setObject, use the type java.sql.Types.ROWID or an
instance of the java.sql.RowId class as the target type for the parameter.
You can use the following CallableStatement methods to retrieve a ROWID column
as an output parameter from a stored procedure call:
v getRowId (JDBC 4.0 and later)
v getObject
To call a stored procedure that is defined with a ROWID output parameter, register
that parameter to be of the java.sql.Types.ROWID type.
ROWID values are valid for different periods of time, depending on the data
source on which those ROWID values are defined. Use the
DatabaseMetaData.getRowIdLifetime method to determine the time period for
which a ROWID value is valid. The values that are returned for the data sources
are listed in the following table.
Table 13. DatabaseMetaData.getRowIdLifetime values for supported data sources
Database server DatabaseMetaData.getRowIdLifetime
DB2 for z/OS ROWID_VALID_TRANSACTION
DB2 Database for Linux, UNIX, and Windows ROWID_UNSUPPORTED
DB2 for i ROWID_VALID_FOREVER
IDS ROWID_VALID_FOREVER
In a JDBC program, you can create a distinct type using the executeUpdate method
to execute the CREATE DISTINCT TYPE statement. You can also use
executeUpdate to create a table that includes a column of that type. When you
retrieve data from a column of that type, or update a column of that type, you use
Java identifiers with data types that correspond to the built-in types on which the
distinct types are based.
The following example creates a distinct type that is based on an INTEGER type,
creates a table with a column of that type, inserts a row into the table, and
retrieves the row from the table:
Connection con;
Statement stmt;
ResultSet rs;
String empNumVar;
int shoeSizeVar;
...
stmt = con.createStatement(); // Create a Statement object
stmt.executeUpdate(
"CREATE DISTINCT TYPE SHOESIZE AS INTEGER");
// Create distinct type
stmt.executeUpdate(
"CREATE TABLE EMP_SHOE (EMPNO CHAR(6), EMP_SHOE_SIZE SHOESIZE)");
// Create table with distinct type
stmt.executeUpdate("INSERT INTO EMP_SHOE " +
"VALUES (’000010’, 6)"); // Insert a row
rs=stmt.executeQuery("SELECT EMPNO, EMP_SHOE_SIZE FROM EMP_SHOE);
// Create ResultSet for query
while (rs.next()) {
empNumVar = rs.getString(1); // Get employee number
shoeSizeVar = rs.getInt(2); // Get shoe size (use int
// because underlying type
// of SHOESIZE is INTEGER)
System.out.println("Employee number = " + empNumVar +
" Shoe size = " + shoeSizeVar);
}
rs.close(); // Close ResultSet
stmt.close(); // Close Statement
You can use java.sql.Array objects as IN, OUT, or INOUT parameters in a stored
procedure.
You can register an OUT ARRAY parameter for a stored procedure call by
specifying java.sql.Types.ARRAY as the parameter type in a
CallableStatement.registerOutParameter call.
There are two ways to retrieve data from an ARRAY output parameter:
v Use the CallableStatement.getArray method to retrieve the data into a
java.sql.Array object, and use the java.sql.Array.getArray method to retrieve the
contents of the java.sql.Array object into a Java array.
v Use the CallableStatement.getArray method to retrieve the data into a
java.sql.Array object. Use the java.sql.Array.getResultSet() method to retrieve the
data into a ResultSet object. Use ResultSet methods to retrieve elements of the
array. Each row of the ResultSet contains two columns:
– An index into the array, which starts at 1
– The array element
The IBM Data Server Driver for JDBC and SQLJ supports the following methods
for using savepoints:
Connection.setSavepoint() or Connection.setSavepoint(String name)
Sets a savepoint. These methods return a Savepoint object that is used in later
releaseSavepoint or rollback operations.
When you execute either of these methods, DB2 executes the form of the
SAVEPOINT statement that includes ON ROLLBACK RETAIN CURSORS.
Connection.releaseSavepoint(Savepoint savepoint)
Releases the specified savepoint, and all subsequently established savepoints.
Connection.rollback(Savepoint savepoint)
Rolls back work to the specified savepoint.
DatabaseMetaData.supportsSavepoints()
Indicates whether a data source supports savepoints.
You can indicate whether savepoints are unique by calling the method
DB2Connection.setSavePointUniqueOption. If you call this method with a value of
true, the application cannot set more than one savepoint with the same name
within the same unit of recovery. If you call this method with a value of false (the
default), multiple savepoints with the same name can be created within the same
unit of recovery, but creation of a savepoint destroys a previously created
savepoint with the same name.
The following example demonstrates how to set a savepoint, roll back to the
savepoint, and release the savepoint.
Figure 17. Setting, rolling back to, and releasing a savepoint in a JDBC application
An automatically generated key is any value that is generated by the data server,
instead of being specified by the user. One type of automatically generated key is
the contents of an identity column. An identity column is a table column that
provides a way for the data source to automatically generate a numeric value for
each row. You define an identity column in a CREATE TABLE or ALTER TABLE
statement by specifying the AS IDENTITY clause when you define a column that
has an exact numeric type with a scale of 0 (SMALLINT, INTEGER, BIGINT,
DECIMAL with a scale of zero, or a distinct type based on one of these types).
For connections to DB2 for z/OS or DB2 Database for Linux, UNIX, and Windows,
the IBM Data Server Driver for JDBC and SQLJ supports the return of
automatically generated keys for INSERT statements, for searched UPDATE or
searched DELETE statements, or for MERGE statements. For UPDATE, DELETE, or
MERGE statements, you can identify any columns as automatically generated keys,
even if they are not generated by the data server. In this case, the column values
that are returned are the column values for the rows that are modified by the
UPDATE, DELETE, or MERGE statement.
Restriction: For IBM Data Server Driver for JDBC and SQLJ version 3.57 or
later, the following form is not valid for inserting rows into a view on a DB2
for z/OS data server.
Connection.prepareStatement(sql-statement,
Statement.RETURN_GENERATED_KEYS);
The following forms are valid only if the data source supports INSERT
within SELECT statements. sql-statement can be a single-row INSERT
statement or a multiple-row INSERT statement. With the first form, you
specify the names of the columns for which you want automatically
generated keys. With the second form, you specify the positions in the table
of the columns for which you want automatically generated keys.
Connection.prepareStatement(sql-statement, String [] columnNames);
Connection.prepareStatement(sql-statement, int [] columnIndexes);
v If you use the Statement.executeUpdate method to insert rows, invoke one of
these forms of the Statement.executeUpdate method:
The following form is valid for a table on any data source that supports
identity columns. sql-statement must be a single-row INSERT statement.
Restriction: For IBM Data Server Driver for JDBC and SQLJ version 3.57 or
later, the following form is not valid for inserting rows into a view on a DB2
for z/OS data server.
Statement.executeUpdate(sql-statement, Statement.RETURN_GENERATED_KEYS);
The following forms are valid only if the data source supports INSERT
within SELECT statements. sql-statement can be a single-row INSERT
statement or a multiple-row INSERT statement. With the first form, you
specify the names of the columns for which you want automatically
generated keys. With the second form, you specify the positions in the table
of the columns for which you want automatically generated keys.
Statement.executeUpdate(sql-statement, String [] columnNames);
Statement.executeUpdate(sql-statement, int [] columnIndexes);
2. Invoke the PreparedStatement.getGeneratedKeys method or the
Statement.getGeneratedKeys method to retrieve a ResultSet object that contains
the automatically generated key values.
The following code creates a table with an identity column, inserts a row into the
table, and retrieves the automatically generated key value for the identity column.
The numbers to the right of selected statements correspond to the previously
described steps.
import java.sql.*;
import java.math.*;
import com.ibm.db2.jcc.*;
Connection con;
Statement stmt;
ResultSet rs;
java.math.BigDecimal iDColVar;
...
stmt = con.createStatement(); // Create a Statement object
stmt.executeUpdate(
"CREATE TABLE EMP_PHONE (EMPNO CHAR(6), PHONENO CHAR(4), " +
"IDENTCOL INTEGER GENERATED ALWAYS AS IDENTITY)");
// Create table with identity column
stmt.executeUpdate("INSERT INTO EMP_PHONE (EMPNO, PHONENO) " + 1
"VALUES (’000010’, ’5555’)", // Insert a row
Statement.RETURN_GENERATED_KEYS); // Indicate you want automatically
// generated keys
rs = stmt.getGeneratedKeys(); // Retrieve the automatically 2
// generated key value in a ResultSet.
// Only one row is returned.
// Create ResultSet for query
while (rs.next()) {
java.math.BigDecimal idColVar = rs.getBigDecimal(1);
// Get automatically generated key
// value
System.out.println("automatically generated key value = " + idColVar);
}
rs.close(); // Close ResultSet
stmt.close(); // Close Statement
The following code creates a table with an identity column, inserts two rows into
the table using a multiple-row INSERT statement, and retrieves the automatically
generated key values for the identity column. The numbers to the right of selected
statements correspond to the previously-described steps.
import java.sql.*;
import java.math.*;
import com.ibm.db2.jcc.*;
Connection con;
Statement stmt;
ResultSet rs;
...
stmt = con.createStatement();
stmt.executeUpdate(
"CREATE TABLE EMP_PHONE (EMPNO CHAR(6), PHONENO CHAR(4), " +
"IDENTCOL INTEGER GENERATED ALWAYS AS IDENTITY)");
// Create table with identity column
String[] id_col = {"IDENTCOL"};
int updateCount = 1
stmt.executeUpdate("INSERT INTO EMP_PHONE (EMPNO, PHONENO)" +
"VALUES (’000010’, ’5555’), (’000020’, ’5556’)", id_col);
// Insert two rows
// Indicate you want automatically
Suppose that a table is defined like this and has thirty rows:
CREATE TABLE EMP_BONUS
(EMPNO CHAR(6),
BONUS DECIMAL(9,2))
The following code names the EMPNO column as an automatically generated key,
updates the thirty rows in the EMP_BONUS table, and retrieves the values of
EMPNO for the updated rows. The numbers to the right of selected statements
correspond to the previously described steps.
import java.sql.*;
...
Connection conn;
...
String[] agkNames = {"EMPNO"}; 1
int updateCount = 0;
conn.setAutoCommit(false); 2
SQL strings that contain the following SQL elements can include named parameter
markers:
v CALL
v DELETE
v INSERT
v MERGE
v PL/SQL block
v SELECT
v SET
v UPDATE
Named parameter markers make your JDBC applications more readable. If you
have named parameter markers in an application, set the IBM Data Server Driver
for JDBC and SQLJ Connection or DataSource property
enableNamedParameterMarkers to DB2BaseDataSource.YES (1) to direct the driver
to accept named parameter markers and send them to the data source as standard
parameter markers.
Recommendation: Do not use the same named parameter marker more than
once in the same SQL statement string if the input to that parameter marker is
a stream. Doing so can cause unexpected results.
The following code uses named parameter markers to update the phone number to
'4657' for the employee with employee number '000010'. The numbers to the right
of selected statements correspond to the previously described steps.
Connection con;
PreparedStatement pstmt;
int numUpd;
...
pstmt = con.prepareStatement(
"UPDATE EMPLOYEE SET PHONENO=:phonenum WHERE EMPNO=:empnum");
// Create a PreparedStatement object 1
((com.ibm.db2.jcc.DB2PreparedStatement)pstmt).setJccStringAtName
("phonenum", "4567");
// Assign a value to phonenum parameter 2
((com.ibm.db2.jcc.DB2PreparedStatement)pstmt).setJccStringAtName
("empnum", "000010");
// Assign a value to empnum parameter
numUpd = pstmt.executeUpdate(); // Perform the update 3
pstmt.close(); // Close the PreparedStatement object
The following code uses named parameter markers to update values in a PL/SQL
block. The numbers to the right of selected statements correspond to the previously
described steps.
Connection con;
PreparedStatement pstmt;
int numUpd;
...
String sql =
"BEGIN " +
" UPDATE EMPLOYEE SET PHONENO = :phonenum WHERE EMPNO = :empnum; " +
"END;";
pstmt = con.prepareStatement(sql); // Create a PreparedStatement object 1
((com.ibm.db2.jcc.DB2PreparedStatement)pstmt).setJccStringAtName
("phonenum", "4567");
// Assign a value to phonenum parameter 2
((com.ibm.db2.jcc.DB2PreparedStatement)pstmt).setJccStringAtName
("empnum", "000010");
// Assign a value to empnum parameter
numUpd = pstmt.executeUpdate(); // Perform the update 3
pstmt.close(); // Close the PreparedStatement object
Recommendation: Do not use the same named parameter marker more than
once in the same SQL statement string if the input to that parameter marker is
a stream. Doing so can cause unexpected results.
5. Execute the CallableStatement.
6. Call CallableStatement.getXXX methods or
DB2CallableStatement.getJccXXXAtName methods to retrieve output parameter
values.
The following code illustrates calling a stored procedure that has one input
VARCHAR parameter and one output INTEGER parameter, which are represented
Extended client information is sent to the database server when the application
performs an action that accesses the server, such as executing SQL.
In the IBM Data Server Driver for JDBC and SQLJ version 4.0 or later, the IBM
Data Server Driver for JDBC and SQLJ-only methods are deprecated. You should
use java.sql.Connection.setClientInfo instead.
The IBM Data Server Driver for JDBC and SQLJ-only methods are listed in the
following table.
Table 14. Methods that provide client information to theDB2 server
Method Information provided
setDB2ClientAccountingInformation Accounting information
setDB2ClientApplicationInformation Name of the application that is working with
a connection
setDB2ClientDebugInfo The CLIENT DEBUGINFO connection
attribute for the Unified debugger
setDB2ClientProgramId A caller-specified string that helps the caller
identify which program is associated with a
particular SQL statement.
setDB2ClientProgramId does not apply to DB2
Database for Linux, UNIX, and Windows data
servers.
setDB2ClientUser User name for a connection
setDB2ClientWorkstation Client workstation name for a connection
Extended client information is sent to the database server when the application
performs an action that accesses the server, such as executing SQL.
The application can also use the Connection.getClientInfo method to retrieve client
information from the database server, or execute the
DatabaseMetaData.getClientInfoProperties method to determine which client
information the driver supports.
The JDBC 4.0 client info properties should be used instead IBM Data Server Driver
for JDBC and SQLJ-only methods, which are deprecated.
The following code performs the previous steps to pass a client's user name and
host name to theDB2 server. The numbers to the right of selected statements
correspond to the previously-described steps.
Client info properties support by the IBM Data Server Driver for
JDBC and SQLJ
JDBC 4.0 includes client info properties, which contain information about a
connection to a data source. The DatabaseMetaData.getClientInfoProperties method
returns a list of client info properties that the IBM Data Server Driver for JDBC
and SQLJ supports.
The following table lists the client info property values that the IBM Data Server
Driver for JDBC and SQLJ returns for DB2 Database for Linux, UNIX, and
Windows and for DB2 for i.
Table 15. Client info property values for DB2 Database for Linux, UNIX, and Windows and for DB2 for i
MAX_LEN
NAME (bytes) DEFAULT_VALUE DESCRIPTION
ApplicationName 255 Empty string The name of the application
that is currently using the
connection. This value is stored
in DB2 special register
CURRENT
CLIENT_APPLNAME.
ClientAccountingInformation 255 Empty string The value of the accounting
string from the client
information that is specified for
the connection. This value is
stored in DB2 special register
CURRENT CLIENT_ACCTNG.
The following table lists the client info property values that the IBM Data Server
Driver for JDBC and SQLJ returns for DB2 for z/OS when the connection uses
type 4 connectivity.
Table 16. Client info property values for type 4 connectivity to DB2 for z/OS
MAX_LEN
NAME (bytes) DEFAULT_VALUE DESCRIPTION
ApplicationName 32 clientProgramName property value, if set. The name of the application that is
"db2jcc_application" otherwise. currently using the connection. This
value is stored in DB2 special
register CURRENT
CLIENT_APPLNAME.
ClientAccountingInformation 200 A string that is the concatenation of the The value of the accounting string
following values: from the client information that is
v "JCCnnnnn", where nnnnn is the driver specified for the connection. This
level, such as 04000. value is stored in DB2 special
v The value that is set by register CURRENT
DB2Connection.setDB2ClientWorkstation. CLIENT_ACCTNG.
If the value is not set, the default is the
host name of the local host.
v applicationName property value, if set. 20
blanks otherwise.
v clientUser property value, if set. Eight
blanks otherwise.
ClientHostname 18 The value that is set by The host name of the computer on
DB2Connection.setDB2ClientWorkstation. If which the application that is using
the value is not set, the default is the host the connection is running. This
name of the local host. value is stored in DB2 special
register CURRENT
CLIENT_WRKSTNNAME.
ClientUser 16 The value that is set by The name of the user on whose
DB2Connection.setDB2ClientUser. If the behalf the application that is using
value is not set, the default is the current the connection is running. This
user ID that is used to connect to the value is stored in DB2 special
database. register CURRENT
CLIENT_USERID.
The following table lists the client info property values that the IBM Data Server
Driver for JDBC and SQLJ returns for DB2 for z/OS when the connection uses
type 2 connectivity.
The following table lists the client info property values that the IBM Data Server
Driver for JDBC and SQLJ returns for IBM Informix
Table 18. Client info property values for IBM Informix
MAX_LEN
NAME (bytes) DEFAULT_VALUE DESCRIPTION
ApplicationName 20 Empty string The name of the application
that is currently using the
connection.
ClientAccountingInformation 199 Empty string The value of the accounting
string from the client
information that is specified for
the connection.
ClientHostname 20 The value that is set by The host name of the computer
DB2Connection.setDB2ClientWorkstation. If on which the application that is
the value is not set, the default is the host using the connection is
name of the local host. running.
ClientUser 1024 Empty string The name of the user on whose
behalf the application that is
using the connection is
running.
Optimistic locking is a technique that applications can use to release locks between
SELECT and UPDATE or DELETE operations. If the selected rows change before
that application updates or deletes them, the UPDATE or DELETE operation fails.
Optimistic locking minimizes the time during which a given resource is
unavailable for use by other transactions.
For connections to a DB2 for i data source, use of optimistic locking requires DB2
for i V6R1 or later.
To check whether the row has changed, the application queries the row change
token. The row change token is not always a completely accurate indicator of
whether the row has changed. If you create a table with a row change timestamp
column, the row change token is completely accurate. If you create the table
without a row change timestamp column, or alter a table to add a row change
timestamp column, the row change token might not accurately reflect updates to a
row. This means that the row change token might indicate that a row has changed,
even though it has not. This condition is called a false negative condition.
When you write a JDBC application to perform optimistic locking you follow
similar steps:
1. Prepare and execute a query.
Indicate whether you want optimistic locking information, and whether that
information can include false negatives.
2. Determine whether the ResultSet has optimistic locking information, and
whether that information can produce false negatives.
Based on the type of optimistic locking information, you can decide whether to
continue with optimistic locking.
3. Release locks on the table.
4. Update the selected rows, if the row change token indicates that they have not
changed.
The following code demonstrates how a JDBC application can perform optimistic
locking. The numbers in the example correspond to the previously listed steps.
com.ibm.db2.jcc.DB2Statement s1 =
(com.ibm.db2.jcc.DB2Statement)conn.createStatement();
ResultSet rs =
((com.ibm.db2.jcc.DB2Statement)s1).executeDB2OptimisticLockingQuery
("SELECT EMPNO, SALARY FROM EMP WHERE EMP.LASTNAME = ’HAAS’",
com.ibm.db2.jcc.DB2Statement.RETURN_OPTLOCK_COLUMN_NO_FALSE_NEGATIVES); 1
// Indicate that you plan to do
// optimistic locking, and that you
// want optimistic locking information
// that does not generate
// false negatives
ResultSetMetaData rsmd = rs.getMetaData();
int optColumns = 2
((com.ibm.db2.jcc.DB2ResultSetMetaData)rsmd).getDB2OptimisticLockingColumns();
// Retrieve the optimistic locking
// information.
boolean optColumnsReturned = false;
long rowChangeToken = 0;
Object rid = null;
if (optColumnsReturned) {
rowChangeToken = // Get the row change token.
((com.ibm.db2.jcc.DB2ResultSet)rs).getDB2RowChangeToken();
rid = ((com.ibm.db2.jcc.DB2ResultSet)rs).getDB2RID();
// Get the RID, which uniquely identifies
// the row.
int type = ((com.ibm.db2.jcc.DB2ResultSet)rs).getDB2RIDType ();
// Get the data type of the RID.
}
// ***************************************************
// Release the locks or disconnect from the database.
// Perform some work on the retrieved data.
// Reconnect to the data source.
// ***************************************************
...
PreparedStatement s2 =
conn.prepareStatement ("UPDATE EMP SET SALARY = ? " +
"WHERE EMPNO = ? AND ROW CHANGE TOKEN FOR EMP = ? and " +
"RID_BIT(EMP) = ?");
// Statement for updating the
// previously selected rows that
// have not changed.
s2.setDouble(1, salary+10000);
s2.setInt(2, emp_id);
// Set the new row values.
s2.setLong(3, rowChangeToken);
// Set the row change token of the
// previously retrieved row.
if (type == java.sql.Types.BIGINT)
s2.setLong (4, ((Long)rid).longValue());
else if (type == java.sql.Types.VARBINARY)
s2.setBytes (4, (byte[])rid);
// Set the RID of the previously
// retrieved row.
// Use the correct setXXX method
// for the data type of the RID.
int updateCount = s2.executeUpdate(); 3
// Perform the update.
if (updateCount == 1); // Update is successful.
else // Update failed.
...
In database tables, the XML built-in data type is used to store XML data in a
column as a structured set of nodes in a tree format.
JDBC applications can send XML data to the data server or retrieve XML data from
the data server as textual XML data.
JDBC 4.0 java.sql.SQLXML objects can be used to retrieve and update data in XML
columns. Invocations of metadata methods, such as
ResultSetMetaData.getColumnTypeName return the integer value
java.sql.Types.SQLXML for an XML column type.
The following table lists the methods and corresponding input data types that you
can use to put data in XML columns.
Table 19. Methods and data types for updating XML columns
Method Input data type
PreparedStatement.setAsciiStream InputStream
PreparedStatement.setBinaryStream InputStream
PreparedStatement.setBlob Blob
PreparedStatement.setBytes byte[]
PreparedStatement.setCharacterStream Reader
PreparedStatement.setClob Clob
PreparedStatement.setObject byte[], Blob, Clob, SQLXML, DB2Xml (deprecated), InputStream,
Reader, String
PreparedStatement.setSQLXML1 SQLXML
PreparedStatement.setString String
Note:
1. This method requires JDBC 4.0 or later.
The encoding of XML data can be derived from the data itself, which is known as
internally encoded data, or from external sources, which is known as externally
encoded data. XML data that is sent to the database server as binary data is treated
as internally encoded data. XML data that is sent to the data source as character
data is treated as externally encoded data.
Externally encoded data can have internal encoding. That is, the data might be sent
to the data source as character data, but the data contains encoding information.
The data source handles incompatibilities between internal and external encoding
as follows:
v If the data source is DB2 Database for Linux, UNIX, and Windows, the database
source generates an error if the external and internal encoding are incompatible,
unless the external and internal encoding are Unicode. If the external and
internal encoding are Unicode, the database source ignores the internal
encoding.
v If the database source is DB2 for z/OS, the database source ignores the internal
encoding.
}
}
Example: The following example demonstrates inserting data from a file into an
XML column. The data is inserted as binary data, so the database server honors the
internal encoding.
public void insertBinStream(Connection conn)
{
PreparedStatement insertStmt = null;
String sqls = null;
int cid = 0;
Statement stmt=null;
try {
sqls = "INSERT INTO CUSTOMER (CID, INFO) VALUES (?, ?)";
insertStmt = conn.prepareStatement(sqls);
insertStmt.setInt(1, cid);
File file = new File(fn);
insertStmt.setBinaryStream(2,
new FileInputStream(file), (int)file.length());
if (insertStmt.executeUpdate() != 1) {
System.out.println("insertBinStream: No record inserted.");
}
}
catch (IOException ioe) {
}
}
When you retrieve data from XML columns of a DB2 table, the output data is in
the serialized string format. This is true whether you retrieve the entire contents of
an XML column or a sequence from the column.
You can use one of the following techniques to retrieve XML data:
v Use the ResultSet.getSQLXML method to retrieve the data. Then use a
SQLXML.getXXX method to retrieve the data into a compatible output data
type. This technique requires JDBC 4.0 or later.
For example, you can retrieve data by using the SQLXML.getBinaryStream
method or the SQLXML.getSource method.
v Use a ResultSet.getXXX method other than ResultSet.getObject to retrieve the
data into a compatible data type.
v Use the ResultSet.getObject method to retrieve the data, and then cast it to the
DB2Xml type and assign it to a DB2Xml object. Then use a DB2Xml.getDB2XXX
or DB2Xml.getDB2XmlXXX method to retrieve the data into a compatible output
data type.
You need to use this technique if you are not using a version of the IBM Data
Server Driver for JDBC and SQLJ that supports JDBC 4.0.
The following table lists the ResultSet methods and corresponding output data
types for retrieving XML data.
Table 20. ResultSet methods and data types for retrieving XML data
Method Output data type
ResultSet.getAsciiStream InputStream
ResultSet.getBinaryStream InputStream
ResultSet.getBytes byte[]
ResultSet.getCharacterStream Reader
ResultSet.getObject Object
ResultSet.getSQLXML SQLXML
ResultSet.getString String
The following table lists the methods that you can call to retrieve data from a
java.sql.SQLXML or a com.ibm.db2.jcc.DB2Xml object, and the corresponding
output data types and type of encoding in the XML declarations.
try{
sqls = "SELECT info FROM customer WHERE cid = " + cid;
selectStmt = conn.prepareStatement(sqls);
rs = selectStmt.executeQuery();
// Get metadata
// Column type for XML column is the integer java.sql.Types.OTHER
ResultSetMetaData meta = rs.getMetaData();
int colType = meta.getColumnType(1);
System.out.println("fetchToSQLXML: Column type = " + colType);
while (rs.next()) {
// Retrieve the XML data with getSQLXML.
// Then write it to a string with
// explicit internal ISO-10646-UCS-2 encoding.
try{
sqls = "SELECT info FROM customer WHERE cid = " + cid;
selectStmt = conn.prepareStatement(sqls);
rs = selectStmt.executeQuery();
// Get metadata
// Column type for XML column is the integer java.sql.Types.OTHER
ResultSetMetaData meta = rs.getMetaData();
int colType = meta.getColumnType(1);
System.out.println("fetchToString: Column type = " + colType);
while (rs.next()) {
stringDoc = rs.getString(1);
System.out.println("Document contents:");
System.out.println(stringDoc);
}
catch (SQLException sqle) {
System.out.println("fetchToString: SQL Exception: " +
sqle.getMessage());
System.out.println("fetchToString: SQL State: " +
sqle.getSQLState());
System.out.println("fetchToString: SQL Error Code: " +
sqle.getErrorCode());
}
}
try{
sqls = "SELECT info FROM customer WHERE cid = " + cid;
// Get metadata
// Column type for XML column is the integer java.sql.Types.OTHER
ResultSetMetaData meta = rs.getMetaData();
int colType = meta.getColumnType(1);
System.out.println("fetchToDB2Xml: Column type = " + colType);
while (rs.next()) {
// Retrieve the XML data with getObject, and cast the object
// as a DB2Xml object. Then write it to a string with
// explicit internal ISO-10646-UCS-2 encoding.
com.ibm.db2.jcc.DB2Xml xml =
(com.ibm.db2.jcc.DB2Xml) rs.getObject(1);
System.out.println (xml.getDB2XmlString());
}
rs.close();
}
catch (SQLException sqle) {
System.out.println("fetchToDB2Xml: SQL Exception: " +
sqle.getMessage());
System.out.println("fetchToDB2Xml: SQL State: " +
sqle.getSQLState());
System.out.println("fetchToDB2Xml: SQL Error Code: " +
sqle.getErrorCode());
}
}
For native SQL procedures, XML parameters in the stored procedure definition
have the XML type. For external stored procedures and user-defined functions on
DB2 Database for Linux, UNIX, and Windows data sources, XML parameters in the
routine definition have the XML AS CLOB type. When you call a stored procedure
or user-defined function that has XML parameters, you need to use a compatible
data type in the invoking statement.
To call a routine with XML input parameters from a JDBC program, use
parameters of the java.sql.SQLXML or com.ibm.db2.jcc.DB2Xml type. To register
XML output parameters, register the parameters as the java.sql.Types.SQLXML or
com.ibm.db2.jcc.DB2Types.XML type. (The com.ibm.db2.jcc.DB2Xml and
com.ibm.db2.jcc.DB2Types.XML types are deprecated.)
Example: JDBC program that calls a stored procedure that takes three XML
parameters: an IN parameter, an OUT parameter, and an INOUT parameter. This
example requires JDBC 4.0.
java.sql.SQLXML in_xml = xmlvar;
java.sql.SQLXML out_xml = null;
java.sql.SQLXML inout_xml = xmlvar;
// Declare an input, output, and
// INOUT XML parameter
Connection con;
CallableStatement cstmt;
ResultSet rs;
...
cstmt = con.prepareCall("CALL SP_xml(?,?,?)");
// Create a CallableStatement object
cstmt.setObject (1, in_xml); // Set input parameter
To call a routine with XML parameters from an SQLJ program, use parameters of
the java.sql.SQLXML or com.ibm.db2.jcc.DB2Xml type.
Example: SQLJ program that calls a stored procedure that takes three XML
parameters: an IN parameter, an OUT parameter, and an INOUT parameter. This
example requires JDBC 4.0.
java.sql.SQLXML in_xml = xmlvar;
java.sql.SQLXML out_xml = null;
java.sql.SQLXML inout_xml = xmlvar;
// Declare an input, output, and
// INOUT XML parameter
...
#sql [myConnCtx] {CALL SP_xml(:IN in_xml,
:OUT out_xml,
:INOUT inout_xml)};
// Call the stored procedure
System.out.println("Parameter values from SP_xml call: ");
System.out.println("Output parameter value ");
MyUtilities.printString(out_xml.getString());
// Use the SQLXML.getString
// method toconvert the out_xml value
// to a string for printing.
// Call a user-defined method called
// printString (not shown) to print
// the value.
System.out.println("INOUT parameter value ");
MyUtilities.printString(inout_xml.getString());
// Use the SQLXML.getString
// method to convert the inout_xml
// value to a string for printing.
// Call a user-defined method called
// printString (not shown) to print
// the value.
Before you can invoke these methods, the stored procedures that support these
methods must be installed on the DB2 database server.
Example: Removal of an XML schema: The following example demonstrates the use of
deregisterDB2XmlObject to remove an XML schema from DB2. The SQL schema
name for the registered schema is SYSXSR.
public static void deregisterSchema(
Connection con,
String schemaName)
throws SQLException {
// Define and assign values to the deregisterDB2XmlObject parameters
String xmlSchemaNameQualifier = "SYSXSR";
String xmlSchemaName = schemaName;
DB2Connection ds = (DB2Connection) con;
// Invoke deregisterDB2XmlObject
ds.deregisterDB2XmlObject(
xmlSchemaNameQualifier,
xmlSchemaName);
}
JDBC isolation levels can be set for a unit of work within a JDBC program, using
the Connection.setTransactionIsolation method. The default isolation level can be
set with the defaultIsolationLevel property.
The following table shows the values of level that you can specify in the
Connection.setTransactionIsolation method and their DB2 database server
equivalents.
Table 22. Equivalent JDBC and DB2 isolation levels
JDBC value DB2 isolation level
java.sql.Connection.TRANSACTION_SERIALIZABLE Repeatable read
java.sql.Connection.TRANSACTION_REPEATABLE_READ Read stability
java.sql.Connection.TRANSACTION_READ_COMMITTED Cursor stability
java.sql.Connection.TRANSACTION_READ_UNCOMMITTED Uncommitted read
The following table shows the values of level that you can specify in the
Connection.setTransactionIsolation method and their IBM Informix (IDS)
equivalents.
Table 23. Equivalent JDBC and IDS isolation levels
JDBC value IDS isolation level
java.sql.Connection.TRANSACTION_SERIALIZABLE Repeatable read
java.sql.Connection.TRANSACTION_REPEATABLE_READ Repeatable read
java.sql.Connection.TRANSACTION_READ_COMMITTED Committed read
java.sql.Connection.TRANSACTION_READ_UNCOMMITTED Dirty read
com.ibm.db2.jcc.DB2Connection.TRANSACTION_IDS_CURSOR_STABILITY IDS cursor stability
com.ibm.db2.jcc.DB2Connection.TRANSACTION_IDS_LAST_COMMITTED Committed read, last committed
For example:
Connection con;
...
con.commit();
For connections to DB2 data sources, the default autocommit mode is true.
For connections to IDS data sources, the default autocommit mode depends on the
type of data source. The following table shows the defaults.
Table 24. Default autocommit modes for IDS data sources
Default autocommit mode for local Default autocommit mode for global
Type of data source transactions transactions
ANSI-compliant database true false
Non-ANSI-compliant database false not applicable
without logging
Non-ANSI-compliant database with true false
logging
Exceptions and warnings under the IBM Data Server Driver for JDBC
and SQLJ
In JDBC applications, SQL errors throw exceptions, which you handle using
try/catch blocks. SQL warnings do not throw exceptions, so you need to invoke
methods to check whether warnings occurred after you execute SQL statements.
The IBM Data Server Driver for JDBC and SQLJ provides the following classes and
interfaces, which provide information about errors and warnings.
SQLException
The SQLException class for handling errors. All JDBC methods throw an instance
of SQLException when an error occurs during their execution. According to the
JDBC specification, an SQLException object contains the following information:
v An int value that contains an error code. SQLException.getErrorCode retrieves
this value.
v A String object that contains the SQLSTATE, or null. SQLException.getSQLState
retrieves this value.
v A String object that contains a description of the error, or null.
SQLException.getMessage retrieves this value.
v A pointer to the next SQLException, or null. SQLException.getNextException
retrieves this value.
DB2Diagnosable
The IBM Data Server Driver for JDBC and SQLJ-only interface
com.ibm.db2.jcc.DB2Diagnosable extends the SQLException class. The
DB2Diagnosable interface gives you more information about errors that occur
when the data source is accessed. If the JDBC driver detects an error,
DB2Diagnosable gives you the same information as the standard SQLException
class. However, if the database server detects the error, DB2Diagnosable adds the
following methods, which give you additional information about the error:
getSqlca
Returns an DB2Sqlca object with the following information:
v An SQL error code
v The SQLERRMC values
v The SQLERRP value
v The SQLERRD values
v The SQLWARN values
v The SQLSTATE
getThrowable
Returns a java.lang.Throwable object that caused the SQLException, or null, if
no such object exists.
printTrace
Prints diagnostic information.
SQLException subclasses
If you are using JDBC 4.0 or later, you can obtain more specific information than
an SQLException provides by catching the following exception classes:
v SQLNonTransientException
An SQLNonTransientException is thrown when an SQL operation that failed
previously cannot succeed when the operation is retried, unless some corrective
action is taken. The SQLNonTransientException class has these subclasses:
– SQLFeatureNotSupportedException
– SQLNonTransientConnectionException
– SQLDataException
– SQLIntegrityConstraintViolationException
– SQLInvalidAuthorizationSpecException
– SQLSyntaxException
v SQLTransientException
An SQLTransientException is thrown when an SQL operation that failed
previously might succeed when the operation is retried, without intervention
from the application. A connection is still valid after an SQLTransientException is
thrown. The SQLTransientException class has these subclasses:
– SQLTransientConnectionException
– SQLTransientRollbackException
– SQLTimeoutException
v SQLRecoverableException
BatchUpdateException
SQLWarning
The IBM Data Server Driver for JDBC and SQLJ accumulates warnings when SQL
statements return positive SQLCODEs, and when SQL statements return 0
SQLCODEs with non-zero SQLSTATEs.
When a call to ResultSet.next returns no rows, the IBM Data Server Driver for
JDBC and SQLJ does not generate an SQLWarning.
The basic steps for handling an SQLException in a JDBC program that runs under
the IBM Data Server Driver for JDBC and SQLJ are:
1. Give the program access to the com.ibm.db2.jcc.DB2Diagnosable interface and
the com.ibm.db2.jcc.DB2Sqlca class. You can fully qualify all references to them,
or you can import them:
import com.ibm.db2.jcc.DB2Diagnosable;
import com.ibm.db2.jcc.DB2Sqlca;
2. Optional: During a connection to a data server, set the
retrieveMessagesFromServerOnGetMessage property to true if you want full
message text from an SQLException.getMessage call.
3. Optional: During a IBM Data Server Driver for JDBC and SQLJ type 2
connectivity connection to a DB2 for z/OS data source, set the
extendedDiagnosticLevel property to EXTENDED_DIAG_MESSAGE_TEXT (241) if you
want extended diagnostic information similar to the information that is
provided by the SQL GET DIAGNOSTICS statement from an
SQLException.getMessage call.
4. Put code that can generate an SQLException in a try block.
5. In the catch block, perform the following steps in a loop:
a. Test whether you have retrieved the last SQLException. If not, continue to
the next step.
b. Optional: For an SQL statement that executes on an IDS data source,
execute the com.ibm.db2.jcc.DB2Statement.getIDSSQLStatementOffSet
method to determine which columns have syntax errors.
DB2Statement.getIDSSQLStatementOffSet returns the offset into the SQL
statement of the first syntax error.
c. Optional: For an SQL statement that executes on an IDS data source, execute
the SQLException.getCause method to retrieve any ISAM error messages.
1) If the Throwable that is returned by SQLException.getCause is not null,
perform one of the following sets of steps:
v Issue SQLException.printStackTrace to print an error message that
includes the ISAM error message text. The ISAM error message text is
preceded by the string "Caused by:".
v Retrieve the error code and message text for the ISAM message:
a) Test whether the Throwable is an instance of an SQLException. If
so, retrieve the SQL error code from that SQLException.
b) Execute the Throwable.getMessage method to retrieve the text of
the ISAM message.
d. Check whether any IBM Data Server Driver for JDBC and SQLJ-only
information exists by testing whether the SQLException is an instance of
DB2Diagnosable. If so:
The following code demonstrates how to obtain IBM Data Server Driver for JDBC
and SQLJ-specific information from an SQLException that is provided with the
IBM Data Server Driver for JDBC and SQLJ. The numbers to the right of selected
statements correspond to the previously-described steps.
Figure 20. Processing an SQLException under the IBM Data Server Driver for JDBC and
SQLJ
...
try { 4
// Code that could generate SQLExceptions
...
} catch(SQLException sqle) {
while(sqle != null) { // Check whether there are more 5a
// SQLExceptions to process
The following code illustrates how to obtain generic SQLWarning information. The
numbers to the right of selected statements correspond to the previously-described
steps.
The DB2 JDBC Type 2 Driver for Linux, UNIX, and Windows uses the
SQLException class for handling errors. All JDBC methods throw an instance of
SQLException when an error occurs during their execution. According to the JDBC
specification, an SQLException object contains the following information:
v A String object that contains a description of the error, or null
v A String object that contains the SQLSTATE, or null
v An int value that contains an error code
v A pointer to the next SQLException, or null
The basic steps for handling an SQLException in a JDBC program that runs under
the DB2 JDBC Type 2 Driver for Linux, UNIX and Windows (DB2 JDBC Type 2
Driver) are:
1. Put code that can generate an SQLException in a try block.
2. In the catch block, perform the following steps in a loop:
a. Test whether you have retrieved the last SQLException. If not, continue to
the next step.
b. Retrieve error information from the SQLException.
c. Invoke the SQLException.getNextException method to retrieve the next
SQLException.
The following code illustrates a catch block that uses the DB2 version of
SQLException that is provided with the DB2 JDBC Type 2 Driver. The numbers to
the right of selected statements correspond to the previously-described steps.
Figure 22. Processing an SQLException under the IBM Data Server Driver for JDBC and
SQLJ
The following code illustrates how to obtain generic SQLWarning information. The
numbers to the right of selected statements correspond to the previously-described
steps.
Connection con;
Statement stmt;
ResultSet rs;
SQLWarning sqlwarn;
...
stmt = con.createStatement(); // Create a Statement object
rs = stmt.executeQuery("SELECT * FROM EMPLOYEE");
// Get the result table from the query
sqlwarn = stmt.getWarnings(); // Get any warnings generated 1
while (sqlwarn != null) { // While there are warnings, get and 2a
// print warning information
System.out.println ("Warning description: " + sqlwarn.getMessage()); 2b
System.out.println ("SQLSTATE: " + sqlwarn.getSQLState()); 2c
System.out.println ("Error code: " + sqlwarn.getErrorCode()); 2d
sqlwarn=sqlwarn.getNextWarning(); // Get next SQLWarning 2e
}
To close the connection to the data source, use the close method. For example:
Connection con;
...
con.close();
Although the tasks that you need to perform are similar to those in other
languages, the way that you execute those tasks, and the order in which you
execute those tasks, is somewhat different.
try
{
Step 3b (loading the JDBC driver) is not necessary if you use JDBC 4.0.
4a , 4b, 4c, These statements demonstrate how to execute SQL statements in SQLJ.
and 4d Statement 4a demonstrates the SQLJ equivalent of declaring an SQL cursor.
Statements 4b and 4c show one way of doing the SQLJ equivalent of executing
an SQL OPEN CURSOR and SQL FETCHes. Statement 4d shows how to do the
SQLJ equivalent of performing an SQL UPDATE. For more information, see
"SQL statements in an SQLJ application".
5 This try/catch block demonstrates the use of the SQLException class for SQL
error handling. For more information on handling SQL errors, see "Handling
SQL errors in an SQLJ application". For more information on handling SQL
warnings, see "Handling SQL warnings in an SQLJ application".
6 This is an example of a comment. For rules on including comments in SQLJ
programs, see "Comments in an SQLJ application".
7 This statement closes the connection to the data source. See "Closing the
connection to the data source in an SQLJ application".
You can use one of six techniques to connect to a data source in an SQLJ program.
Two use the JDBC DriverManager interface, two use the JDBC DataSource
interface, one uses a previously created connection context, and one uses the
default connection.
connection-context-class connection-context-object=
new connection-context-class(String url, String user,
String password, boolean autocommit);
connection-context-class connection-context-object=
new connection-context-class(String url, Properties info,
boolean autocommit);
The meanings of the parameters are:
url A string that specifies the location name that is associated with the data
source. That argument has one of the forms that are specified in "Connect
to a data source using the DriverManager interface with the IBM Data
Server Driver for JDBC and SQLJ". The form depends on which JDBC
driver you are using.
user and password
Specify a user ID and password for connection to the data source, if the
data source to which you are connecting requires them.
info
Specifies an object of type java.util.Properties that contains a set of driver
properties for the connection. For the DB2 JDBC Type 2 Driver for Linux,
UNIX and Windows (DB2 JDBC Type 2 Driver), you should specify only
the user and password properties. For the IBM Data Server Driver for JDBC
and SQLJ, you can specify any of the properties listed in "Properties for the
IBM Data Server Driver for JDBC and SQLJ".
autocommit
Specifies whether you want the database manager to issue a COMMIT after
every statement. Possible values are true or false. If you specify false,
you need to do explicit commit operations.
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
...
#sql context CtxSqlj; // Create connection context class CtxSqlj 1
Context ctx=new InitialContext(); 2b
DataSource ds=(DataSource)ctx.lookup("jdbc/sampledb"); 2c
Connection con=ds.getConnection(); 3
String empname; // Declare a host variable
...
con.setAutoCommit(false); // Do not autocommit 4
CtxSqlj myConnCtx=new CtxSqlj(con); 5
// Create connection context object myConnCtx
#sql [myConnCtx] {SELECT LASTNAME INTO :empname FROM EMPLOYEE
WHERE EMPNO=’000010’};
// Use myConnCtx for executing an SQL statement
The connection context must be declared as public and static. logical-name is the
data source name that you obtained in step 1.
3. Invoke the constructor for the connection context class that you created in step
2.
Doing this creates a connection context object that you specify in each SQL
statement that you execute at the associated data source. The constructor
invocation statement needs to be in one of the following forms:
connection-context-class connection-context-object=
new connection-context-class();
connection-context-class connection-context-object=
new connection-context-class (String user,
String password);
The meanings of the user and password parameters are:
user and password
Specify a user ID and password for connection to the data source, if the
data source to which you are connecting requires them.
Program CtxGen.sqlj declares connection context Ctx and creates instance oldCtx:
#sql context Ctx;
...
// Create connection context object oldCtx
Program test.sqlj receives oldCtx as a parameter and uses oldCtx as the argument
of its connection context constructor:
void useContext(sqlj.runtime.ConnectionContext oldCtx)
// oldCtx was created in CtxGen.sqlj
{
Ctx myConnCtx=
new Ctx(oldCtx); // Create connection context object myConnCtx
// from oldCtx
#sql [myConnCtx] {SELECT LASTNAME INTO :empname FROM EMPLOYEE
WHERE EMPNO=’000010’};
// Use myConnCtx for executing an SQL statement
...
}
You use the default connection by specifying your SQL statements without a
connection context object. When you use this technique, you do not need to load a
JDBC driver unless you explicitly use JDBC interfaces in your program.
The following SQLJ execution clause does not have a connection context, so it uses
the default connection context.
#sql {SELECT LASTNAME INTO :empname FROM EMPLOYEE
WHERE EMPNO=’000010’}; // Use default connection for
// executing an SQL statement
You can do that either by importing the packages or specific classes, or by using
fully-qualified class names. You might need the following packages or classes for
your SQLJ program:
A host expression begins with a colon (:). The colon is followed by an optional
parameter mode identifier (IN, OUT, or INOUT), which is followed by a
parenthesized expression clause.
In this example, the statement that begins with #sql has the same function as a
SELECT statement in other languages. This statement assigns the last name of the
employee with employee number 000010 to Java identifier empname.
String empname;
...
#sql [ctxt]
{SELECT LASTNAME INTO :empname FROM EMPLOYEE WHERE EMPNO=’000010’};
In this example, the statement that begins with #sql has the same function as an
SQL CALL statement in other languages. This statement uses Java identifier empno
as an input parameter to stored procedure A. The keyword IN, which precedes
empno, specifies that empno is an input parameter. For a parameter in a CALL
statement, IN is the default. The explicit or default qualifier that indicates how the
parameter is used (IN, OUT, or INOUT) must match the corresponding value in
the parameter definition that you specified in the CREATE PROCEDURE statement
for the stored procedure.
String empno = "0000010";
...
#sql [ctxt] {CALL A (:IN empno)};
SQLJ performs the following actions when it processes a complex host expression:
v Evaluates each of the host expressions in the statement, from left to right, before
assigning their respective values to the database.
v Evaluates side effects, such as operations with postfix operators, according to
normal Java rules. All host expressions are fully evaluated before any of their
values are passed to DB2.
v Uses Java rules for rounding and truncation.
Therefore, if the value of yearsEmployed is 6 before the UPDATE statement is
executed, the value that is assigned to column BONUS by the UPDATE statement
is ((int)6/5)*500, or 500. After 500 is assigned to BONUS, the value of
yearsEmployed is incremented.
You can include Java comments outside SQLJ clauses, wherever the Java language
permits them. Within an SQLJ clause, you can use Java comments in the following
places:
v Within a host expression (/* */ or //).
v Within an SQL statement in an executable clause, if the data source supports a
comment within the SQL statement (/* */ or --).
/* and */ pairs in an SQL statement can be nested.
The following code shows how to declare a positioned iterator and use it for
positioned UPDATEs. The numbers to the right of selected statements correspond
to the previously described steps.
Then, in another file, use UpdByPos for a positioned UPDATE, as shown in the
following code fragment:
The following code shows how to declare a named iterator and use it for
positioned UPDATEs. The numbers to the right of selected statements correspond
to the previously described steps.
Then, in another file, use UpdByName for a positioned UPDATE, as shown in the
following code fragment:
doUpdate ( iter1 );
}
In this example, only one iterator is declared. Two instances of that iterator are
declared, and each is associated with a different SELECT statement that retrieves
data from a different table. During customization and binding with
-staticpositioned YES, SQLJ creates two DECLARE CURSOR statements, one for
each SELECT statement, and attempts to bind an UPDATE statement for each
cursor. However, the bind process fails with SQLCODE -509 when UPDATE TABLE1
... WHERE CURRENT OF :iter is bound for the cursor for SELECT CHAR_COL2 FROM
TABLE2 because the table for the UPDATE does not match the table for the cursor.
You can avoid a bind time error for a program like the one in Figure 33 by
specifying the bind option SQLERROR(CONTINUE). However, this technique has
the drawback that it causes the DB2 database manager to build a package,
regardless of the SQL errors that are in the program. A better technique is to write
the program so that there is a one-to-one mapping between tables in positioned
UPDATE or DELETE statements and iterator classes. Figure 34 on page 129 shows
an example of how to do this.
doUpdate(iter1);
With this method of coding, each iterator class is associated with only one table.
Therefore, the DB2 bind process can always associate the positioned UPDATE
statement with a valid iterator.
Unlike JDBC, SQLJ allows heterogeneous batches that contain statements with
input parameters or host expressions. You can therefore combine any of the
following items in an SQLJ batch:
v Instances of the same statement
v Different statements
v Statements with different numbers of input parameters or host expressions
v Statements with different data types for input parameters or host expressions
v Statements with no input parameters or host expressions
For all cases except homogeneous batches of INSERT statements, when an error
occurs during execution of a statement in a batch, the remaining statements are
executed, and a BatchUpdateException is thrown after all the statements in the
batch have executed.
When a batch is executed implicitly because the program contains a statement that
cannot be added to the batch, the batch is executed before the new statement is
processed. If an error occurs during execution of the batch, the statement that
caused the batch to execute does not execute.
The basic steps for creating, executing, and deleting a batch of statements are:
1. Disable AutoCommit for the connection.
Do this so that you can control whether to commit changes to already-executed
statements when an error occurs during batch execution.
2. Acquire an execution context.
All statements that execute in a batch must use this execution context.
3. Invoke the ExecutionContext.setBatching(true) method to create a batch.
Subsequent batchable statements that are associated with the execution context
that you created in step 2 are added to the batch for later execution.
If you want to batch sets of statements that are not batch compatible in parallel,
you need to create an execution context for each set of batch compatible
statements.
4. Include SQLJ executable clauses for SQL statements that you want to batch.
These clauses must include the execution context that you created in step 2.
If an SQLJ executable clause has input parameters or host expressions, you can
include the statement in the batch multiple times with different values for the
input parameters or host expressions.
To determine whether a statement was added to an existing batch, was the first
statement in a new batch, or was executed inside or outside a batch, invoke the
ExecutionContext.getUpdateCount method. This method returns one of the
following values:
ExecutionContext.ADD_BATCH_COUNT
This is a constant that is returned if the statement was added to an existing
batch.
ExecutionContext.NEW_BATCH_COUNT
This is a constant that is returned if the statement was the first statement in
a new batch.
ExecutionContext.EXEC_BATCH_COUNT
This is a constant that is returned if the statement was part of a batch, and
the batch was executed.
Example
Also suppose that the table already has a row with the values 2 and "val2".
Because of the uniqueness constraint on INTCOL, when the following code is
executed, the second INSERT statement in the batch fails.
If the target data server is DB2 for z/OS, and this application is customized
without atomicMultiRowInsert set to DB2BaseDataSource.YES, the batch INSERT is
Just as in DB2 applications in other languages, if you want to retrieve a single row
from a table in an SQLJ application, you can write a SELECT INTO statement with
a WHERE clause that defines a result table that contains only that row:
#sql [myConnCtx] {SELECT DEPTNO INTO :hvdeptno
FROM DEPARTMENT WHERE DEPTNAME="OPERATIONS"};
However, most SELECT statements that you use create result tables that contain
many rows. In DB2 applications in other languages, you use a cursor to select the
individual rows from the result table. That cursor can be non-scrollable, which
means that when you use it to fetch rows, you move the cursor serially, from the
beginning of the result table to the end. Alternatively, the cursor can be scrollable,
which means that when you use it to fetch rows, you can move the cursor
forward, backward, or to any row in the result table.
A result set iterator is a Java object that you use to retrieve rows from a result
table. Unlike a cursor, a result set iterator can be passed as a parameter to a
method.
There are two types of iterators: positioned iterators and named iterators. Postitioned
iterators extend the interface sqlj.runtime.PositionedIterator. Positioned iterators
identify the columns of a result table by their position in the result table. Named
iterators extend the interface sqlj.runtime.NamedIterator. Named iterators identify
the columns of the result table by result table column names.
The following code demonstrates how to declare and use a named iterator. The
numbers to the right of selected statements correspond to the previously-described
steps.
The following code demonstrates how to declare and use a positioned iterator. The
numbers to the right of selected statements correspond to the previously-described
steps.
When you use concurrently open iterators in an application, you should close
iterators when you no longer need them to prevent excessive storage consumption
in the Java heap.
Without the capability for multiple, concurrently open iterators for a single SQL
statement, if you want to select employee and salary values for a specific employee
number, you need to define a different SQL statement for each employee number,
as shown in Figure 37 on page 139.
Figure 37. Example of concurrent table operations using iterators with different SQL
statements
Figure 38 demonstrates how you can perform the same operations when you have
the capability for multiple, concurrently open iterators for a single SQL statement.
...
MultiIter iter1 = openIter("000100"); // Invoke openIter to assign the result table
// (for employee 100) to the first iterator
MultiIter iter2 = openIter("000200"); // Invoke openIter to assign the result
// table to the second iterator
// iter1 stays open when iter2 is opened
// Process with iter1
// Process with iter2
...
iter1.close(); // Close the iterators
iter2.close();
...
public MultiIter openIter(String EmpNo)
// Method to assign a result table
// to an iterator instance
{
MultiIter iter;
#sql [ctxt] iter =
{SELECT EMPNO, SALARY FROM EMPLOYEE WHERE EMPNO = :EmpNo};
return iter; // Method returns an iterator instance
}
Figure 38. Example of concurrent table operations using iterators with the same SQL
statement
The following example shows an application with two concurrently open instances
of an iterator.
Figure 39. Example of opening more than one instance of an iterator in a single application
As with any other iterator, you need to remember to close this iterator after the last
time you use it to prevent excessive storage consumption.
If a scrollable iterator is static, the size of the result table and the order of the rows
in the result table do not change after the iterator is opened. This means that you
cannot insert into result tables, and if you delete a row of a result table, a delete
hole occurs. If you update a row of the result table so that the row no longer
qualifies for the result table, an update hole occurs. Fetching from a hole results in
an SQLException.
If a scrollable iterator is dynamic, the size of the result table and the order of the
rows in the result table can change after the iterator is opened. Rows that are
inserted or deleted with INSERT and DELETE statements that are executed by the
same application process are immediately visible. Rows that are inserted or deleted
with INSERT and DELETE statements that are executed by other application
processes are visible after the changes are committed.
Important: DB2 Database for Linux, UNIX, and Windows servers do not support
dynamic scrollable cursors. You can use dynamic scrollable iterators in your SQLJ
applications only if those applications access data on DB2 for z/OS servers, at
Version 9 or later.
Important:
To create and use a scrollable iterator, you need to follow these steps:
Restriction: You cannot use a scrollable iterator to select columns with the
following data types from a table on a DB2 Database for Linux, UNIX, and
Windows server:
v LONG VARCHAR
v LONG VARGRAPHIC
v BLOB
v CLOB
v XML
v A distinct type that is based on any of the previous data types in this list
v A structured type
2. Create an iterator object, which is an instance of your iterator class.
3. If you want to give the SQLJ runtime environment a hint about the initial fetch
direction, use the setFetchDirection(int direction) method. direction can be
FETCH_FORWARD or FETCH_REVERSE. If you do not invoke setFetchDirection, the
fetch direction is FETCH_FORWARD.
4. For each row that you want to access:
For a named iterator, perform the following steps:
a. Position the cursor using one of the methods listed in the following table.
Table 25. sqlj.runtime.Scrollable methods for positioning a scrollable cursor
Method Positions the cursor
1
first On the first row of the result table
1
last On the last row of the result table
1,2
previous On the previous row of the result table
next On the next row of the result table
1,3
absolute(int n) If n>0, on row n of the result table. If n<0, and m is
the number of rows in the result table, on row m+n+1
of the result table.
b. If you need to know the current cursor position, use the getRow, isFirst,
isLast, isBeforeFirst, or isAfterLast method to obtain this information.
If you need to know the current fetch direction, invoke the
getFetchDirection method.
c. Use accessor methods to retrieve the current row of the result table.
d. If update or delete operations by the iterator or by other means are visible
in the result table, invoke the getWarnings method to check whether the
current row is a hole.
For a positioned iterator, perform the following steps:
a. Use a FETCH statement with a fetch orientation clause to position the
iterator and retrieve the current row of the result table. Table 26 lists the
clauses that you can use to position the cursor.
Table 26. FETCH clauses for positioning a scrollable cursor
Method Positions the cursor
1
FIRST On the first row of the result table
1
LAST On the last row of the result table
1,2
PRIOR On the previous row of the result table
NEXT On the next row of the result table
1,3
ABSOLUTE(n) If n>0, on row n of the result table. If n<0, and m is
the number of rows in the result table, on row m+n+1
of the result table.
RELATIVE(n)1,4 If n>0, on the row that is n rows after the current row.
If n<0, on the row that is n rows before the current
row. If n=0, on the current row.
AFTER1,5 After the last row in the result table
1,5
BEFORE Before the first row in the result table
The following code demonstrates how to use a named iterator to retrieve the
employee number and last name from all rows from the employee table in reverse
order. The numbers to the right of selected statements correspond to the
previously-described steps.
#sql context Ctx; // Create connection context class Ctx
#sql iterator ScrollIter implements sqlj.runtime.Scrollable 1
(String EmpNo, String LastName);
{
...
Ctx ctxt =
new Ctx("jdbc:db2://sysmvs1.stl.ibm.com:5021/NEWYORK",
userid,password,false); // Create connection context object ctxt
// for the connection to NEWYORK
ScrollIter scrliter; 2
#sql [ctxt]
scrliter={SELECT EMPNO, LASTNAME FROM EMPLOYEE};
scrliter.afterLast();
while (scrliter.previous()) 4a
{
System.out.println(scrliter.EmpNo() + " " 4c
+ scrliter.LastName());
}
scrliter.close(); 5
}
You can execute the CALL statement with host identifier parameters. You can
execute the CALL statement with literal parameters only if the DB2 server on
which the CALL statement runs supports execution of the CALL statement
dynamically.
The following code illustrates calling a stored procedure that has three input
parameters and three output parameters. The numbers to the right of selected
statements correspond to the previously-described steps.
To retrieve the rows from those result sets, you execute these steps:
1. Acquire an execution context for retrieving the result set from the stored
procedure.
2. Associate the execution context with the CALL statement for the stored
procedure.
Do not use this execution context for any other purpose until you have
retrieved and processed the last result set.
3. For each result set:
a. Use the ExecutionContext method getNextResultSet to retrieve the result set.
b. If you do not know the contents of the result set, use ResultSetMetaData
methods to retrieve this information.
c. Use an SQLJ result set iterator or JDBC ResultSet to retrieve the rows from
the result set.
Result sets are returned to the calling program in the same order that their cursors
are opened in the stored procedure. When there are no more result sets to retrieve,
getNextResultSet returns a null value.
The following code calls a stored procedure that returns multiple result sets. For
this example, it is assumed that the caller does not know the number of result sets
to be returned or the contents of those result sets. It is also assumed that
autoCommit is false. The numbers to the right of selected statements correspond to
the previously-described steps.
LOBs in SQLJ applications with the IBM Data Server Driver for
JDBC and SQLJ
With the IBM Data Server Driver for JDBC and SQLJ, you can retrieve LOB data
into Clob or Blob host expressions or update CLOB, BLOB, or DBCLOB columns
from Clob or Blob host expressions. You can also declare iterators with Clob or
Blob data types to retrieve data from CLOB, BLOB, or DBCLOB columns.
Retrieving or updating LOB data: To retrieve data from a BLOB column, declare
an iterator that includes a data type of Blob or byte[]. To retrieve data from a
CLOB or DBCLOB column, declare an iterator in which the corresponding column
has a Clob data type.
To update data in a BLOB column, use a host expression with data type Blob. To
update data in a CLOB or DBCLOB column, use a host expression with data type
Clob.
When the JDBC driver cannot immediately determine the data type of a parameter
that is used with a LOB column, you need to choose a parameter data type that is
compatible with the LOB data type.
For input parameters for BLOB columns, you can use either of the following
techniques:
v Use a java.sql.Blob input variable, which is an exact match for a BLOB column:
java.sql.Blob blobData;
#sql {CALL STORPROC(:IN blobData)};
Before you can use a java.sql.Blob input variable, you need to create a
java.sql.Blob object, and then populate that object.
v Use an input parameter of type of sqlj.runtime.BinaryStream. A
sqlj.runtime.BinaryStream object is compatible with a BLOB data type. For
example:
java.io.ByteArrayInputStream byteStream =
new java.io.ByteArrayInputStream(byteData);
int numBytes = byteData.length;
sqlj.runtime.BinaryStream binStream =
new sqlj.runtime.BinaryStream(byteStream, numBytes);
#sql {CALL STORPROC(:IN binStream)};
For output or INOUT parameters for BLOB columns, you can use the following
technique:
v Declare the output parameter or INOUT variable with a java.sql.Blob data type:
java.sql.Blob blobData = null;
#sql CALL STORPROC (:OUT blobData)};
java.sql.Blob blobData = null;
#sql CALL STORPROC (:INOUT blobData)};
For input parameters for CLOB columns, you can use one of the following
techniques:
v Use a java.sql.Clob input variable, which is an exact match for a CLOB column:
#sql CALL STORPROC(:IN clobData)};
Before you can use a java.sql.Clob input variable, you need to create a
java.sql.Clob object, and then populate that object.
146 Developing Java Applications
v Use one of the following types of stream IN parameters:
– A sqlj.runtime.CharacterStream input parameter:
java.lang.String charData;
java.io.StringReader reader = new java.io.StringReader(charData);
sqlj.runtime.CharacterStream charStream =
new sqlj.runtime.CharacterStream (reader, charData.length);
#sql {CALL STORPROC(:IN charStream)};
– A sqlj.runtime.UnicodeStream parameter, for Unicode UTF-16 data:
byte[] charDataBytes = charData.getBytes("UnicodeBigUnmarked");
java.io.ByteArrayInputStream byteStream =
new java.io.ByteArrayInputStream(charDataBytes);
sqlj.runtime.UnicodeStream uniStream =
new sqlj.runtime.UnicodeStream(byteStream, charDataBytes.length );
#sql {CALL STORPROC(:IN uniStream)};
– A sqlj.runtime.AsciiStream parameter, for ASCII data:
byte[] charDataBytes = charData.getBytes("US-ASCII");
java.io.ByteArrayInputStream byteStream =
new java.io.ByteArrayInputStream (charDataBytes);
sqlj.runtime.AsciiStream asciiStream =
new sqlj.runtime.AsciiStream (byteStream, charDataBytes.length);
#sql {CALL STORPROC(:IN asciiStream)};
For these calls, you need to specify the exact length of the input data. You
cannot use this technique for INOUT parameters.
v Use a java.lang.String input parameter:
java.lang.String charData;
#sql {CALL STORPROC(:IN charData)};
For output or INOUT parameters for CLOB columns, you can use one of the
following techniques:
v Use a java.sql.Clob output variable, which is an exact match for a CLOB column:
java.sql.Clob clobData = null;
#sql CALL STORPROC(:OUT clobData)};
v Use a java.lang.String output variable:
java.lang.String charData = null;
#sql CALL STORPROC(:OUT charData)};
This technique should be used only if you know that the length of the retrieved
data is less than or equal to 32KB. Otherwise, the data is truncated.
DBCLOB output or INOUT parameters for stored procedures are not supported.
See "Connect to a data source using SQLJ" for more information on SQLJ
connections.
Retrieving JDBC result sets using SQLJ iterators: Use the iterator conversion
statement to manipulate a JDBC result set as an SQLJ iterator. The general form of
an iterator conversion statement is:
#sql iterator={CAST :result-set};
Before you can successfully cast a result set to an iterator, the iterator must
conform to the following rules:
v The iterator must be declared as public.
v If the iterator is a positioned iterator, the number of columns in the result set
must match the number of columns in the iterator. In addition, the data type of
each column in the result set must match the data type of the corresponding
column in the iterator.
v If the iterator is a named iterator, the name of each accessor method must match
the name of a column in the result set. In addition, the data type of the object
that an accessor method returns must match the data type of the corresponding
column in the result set.
The code in Figure 42 on page 149 builds and executes a query using a JDBC call,
executes an iterator conversion statement to convert the JDBC result set to an SQLJ
iterator, and retrieves rows from the result table using the iterator.
}
nameiter.close(); 5
stmt.close();
}
Note Description
1 This SQLJ clause creates the named iterator class ByName, which has accessor
methods LastName() and HireDate() that return the data from result table columns
LASTNAME and HIREDATE.
2 This statement and the following two statements build and prepare a query for
dynamic execution using JDBC.
3 This JDBC statement executes the SELECT statement and assigns the result table
to result set rs.
4 This iterator conversion clause converts the JDBC ResultSet rs to SQLJ iterator
nameiter, and the following statements use nameiter to retrieve values from the
result table.
5 The nameiter.close() method closes the SQLJ iterator and JDBC ResultSet rs.
Generating JDBC ResultSets from SQLJ iterators: Use the getResultSet method to
generate a JDBC ResultSet from an SQLJ iterator. Every SQLJ iterator has a
getResultSet method. After you access the ResultSet that underlies an iterator, you
need to fetch rows using only the ResultSet.
The code in Figure 43 on page 150 generates a positioned iterator for a query,
converts the iterator to a result set, and uses JDBC methods to fetch rows from the
table.
Note Description
1 This SQLJ clause executes the SELECT statement, constructs an iterator object that
contains the result table for the SELECT statement, and assigns the iterator object
to variable iter.
2 The getResultSet() method accesses the ResultSet that underlies iterator iter.
3 The JDBC getString() and getDate() methods retrieve values from the ResultSet.
The next() method moves the cursor to the next row in the ResultSet.
4 The rs.close() method closes the SQLJ iterator as well as the ResultSet.
Rules and restrictions for using JDBC ResultSets in SQLJ applications: When you
write SQLJ applications that include JDBC result sets, observe the following rules
and restrictions:
v You cannot cast a ResultSet to an SQLJ iterator if the ResultSet and the iterator
have different holdability attributes.
A JDBC ResultSet or an SQLJ iterator can remain open after a COMMIT
operation. For a JDBC ResultSet, this characteristic is controlled by the IBM Data
Server Driver for JDBC and SQLJ property resultSetHoldability. For an SQLJ
iterator, this characteristic is controlled by the with holdability parameter of
the iterator declaration. Casting a ResultSet that has holdability to an SQLJ
iterator that does not, or casting a ResultSet that does not have holdability to an
SQLJ iterator that does, is not supported.
v Close the iterator or the underlying ResultSet object as soon as the program no
longer uses the iterator or ResultSet, and before the end of the program.
Closing the iterator also closes the ResultSet object. Closing the ResultSet object
also closes the iterator object. In general, it is best to close the object that is used
last.
v For the IBM Data Server Driver for JDBC and SQLJ, which supports scrollable
iterators and scrollable and updatable ResultSet objects, the following restrictions
apply:
– Scrollable iterators have the same restrictions as their underlying JDBC
ResultSet objects.
– You cannot cast a JDBC ResultSet that is not updatable to an SQLJ iterator
that is updatable.
The following code demonstrates how to acquire an execution context, and then
use the getUpdateCount method on that execution context to determine the
number of rows that were deleted by a DELETE statement. The numbers to the
right of selected statements correspond to the previously-described steps.
ExecutionContext execCtx=new ExecutionContext(); 1
#sql [connCtx, execCtx] {DELETE FROM EMPLOYEE WHERE SALARY > 10000}; 2
System.out.println("Deleted " + execCtx.getUpdateCount() + " rows"); 3
ROWIDs in SQLJ with the IBM Data Server Driver for JDBC
and SQLJ
DB2 for z/OS and DB2 for i support the ROWID data type for a column in a table.
A ROWID is a value that uniquely identifies a row in a table.
Although IBM Informix (IDS) also supports rowids, those rowids have the
INTEGER data type. You can select an IDS rowid column into a variable with a
four-byte integer data type.
If you use columns with the ROWID data type in SQLJ programs, you need to
customize those programs.
JDBC 4.0 includes interface java.sql.RowId that you can use in iterators and in
CALL statement parameters. If you do not have JDBC 4.0, you can use the IBM
Data Server Driver for JDBC and SQLJ-only class com.ibm.db2.jcc.DB2RowID. For
an iterator, you can also use the byte[] object type to retrieve ROWID values.
The following code shows an example of an iterator that is used to select values
from a ROWID column:
The following code shows an example of calling a stored procedure that takes
three ROWID parameters: an IN parameter, an OUT parameter, and an INOUT
parameter.
You can also use CREATE TABLE in an executable clause to create a table that
includes a column of that type. When you retrieve data from a column of that
type, or update a column of that type, you use Java host variables or expressions
with data types that correspond to the built-in types on which the distinct types
are based.
The following example creates a distinct type that is based on an INTEGER type,
creates a table with a column of that type, inserts a row into the table, and
retrieves the row from the table:
String empNumVar;
int shoeSizeVar;
...
#sql [myConnCtx] {CREATE DISTINCT TYPE SHOESIZE AS INTEGER WITH COMPARISONS};
// Create distinct type
#sql [myConnCtx] {COMMIT}; // Commit the create
#sql [myConnCtx] {CREATE TABLE EMP_SHOE
(EMPNO CHAR(6), EMP_SHOE_SIZE SHOESIZE)};
// Create table using distinct type
#sql [myConnCtx] {COMMIT}; // Commit the create
#sql [myConnCtx] {INSERT INTO EMP_SHOE
VALUES(’000010’,6)}; // Insert a row in the table
#sql [myConnCtx] {COMMIT}; // Commit the INSERT
#sql [myConnCtx] {SELECT EMPNO, EMP_SHOE_SIZE
INTO :empNumVar, :shoeSizeVar
FROM EMP_SHOE}; // Retrieve the row
System.out.println("Employee number: " + empNumVar +
" Shoe size: " + shoeSizeVar);
You can use java.sql.Array objects as IN, OUT, or INOUT parameters in a stored
procedure.
There are two ways to retrieve data from an ARRAY output stored procedure
parameter:
v Use the java.sql.Array.getArray method to retrieve the contents of output
parameter into a Java array.
v Use a java.sql.Array.getResultSet method to retrieve the output parameter data
into a ResultSet object. Then use ResultSet methods to retrieve elements of the
array. Each row of the ResultSet contains two columns:
– An index into the array, which starts at 1
– The array element
An SQL savepoint represents the state of data and schemas at a particular point in
time within a unit of work. SQL statements exist to set a savepoint, release a
savepoint, and restore data and schemas to the state that the savepoint represents.
The following example demonstrates how to set a savepoint, roll back to the
savepoint, and release the savepoint.
Figure 47. Setting, rolling back to, and releasing a savepoint in an SQLJ application
In DB2 tables, the XML built-in data type is used to store XML data in a column as
a structured set of nodes in a tree format.
SQLJ applications can send XML data to the data server or retrieve XML data from
the data server as textual XML data.
JDBC 4.0 java.sql.SQLXML objects can be used to retrieve and update data in XML
columns. Invocations of metadata methods, such as
ResultSetMetaData.getColumnType return the integer value java.sql.Types.SQLXML
for an XML column type.
The host expression data types that you can use to update XML columns are:
v java.sql.SQLXML (requires an SDK for Java Version 6 or later, and the IBM Data
Server Driver for JDBC and SQLJ version 4.0 or later)
v com.ibm.db2.jcc.DB2Xml (deprecated)
v String
v byte
v Blob
v Clob
v sqlj.runtime.AsciiStream
v sqlj.runtime.BinaryStream
v sqlj.runtime.CharacterStream
The encoding of XML data can be derived from the data itself, which is known as
internally encoded data, or from external sources, which is known as externally
encoded data. XML data that is sent to the database server as binary data is treated
as internally encoded data. XML data that is sent to the data source as character
data is treated as externally encoded data. The external encoding is the default
encoding for the JVM.
Externally encoded data can have internal encoding. That is, the data might be sent
to the data source as character data, but the data contains encoding information.
The data source handles incompatibilities between internal and external encoding
as follows:
v If the data source is DB2 Database for Linux, UNIX, and Windows, the data
source generates an error if the external and internal encoding are incompatible,
unless the external and internal encoding are Unicode. If the external and
internal encoding are Unicode, the data source ignores the internal encoding.
v If the data source is DB2 for z/OS, the data source ignores internal encoding.
Example: Suppose that you use the following statement to insert data from String
host expression xmlString into an XML column in a table. xmlString is a character
type, so its external encoding is used, whether or not it has an internal encoding
specification.
#sql [ctx] {INSERT INTO CUSTACC VALUES (1, :xmlString)};
Example: Suppose that you copy the data from xmlString into a byte array with
CP500 encoding. The data contains an XML declaration with an encoding
declaration for CP500. Then you insert the data from the byte[] host expression
into an XML column in a table.
byte[] xmlBytes = xmlString.getBytes("CP500");
#sql[ctx] {INSERT INTO CUSTACC VALUES (4, :xmlBytes)};
Example: Suppose that you retrieve a document from an XML column into a
java.sql.SQLXML host expression, and insert the data into an XML column in a
table.
java.sql.ResultSet rs = s.executeQuery ("SELECT * FROM CUSTACC");
rs.next();
java.sql.SQLXML xmlObject = (java.sql.SQLXML)rs.getObject(2);
#sql [ctx] {INSERT INTO CUSTACC VALUES (6, :xmlObject)};
After you retrieve the data it is still in UTF-8 encoding, so when you insert the
data into another XML column, no conversion occurs.
Example: Suppose that you retrieve a document from an XML column into a
com.ibm.db2.jcc.DB2Xml host expression, and insert the data into an XML column
in a table.
java.sql.ResultSet rs = s.executeQuery ("SELECT * FROM CUSTACC");
rs.next();
com.ibm.db2.jcc.DB2Xml xmlObject = (com.ibm.db2.jcc.DB2Xml)rs.getObject(2);
#sql [ctx] {INSERT INTO CUSTACC VALUES (6, :xmlObject)};
After you retrieve the data it is still in UTF-8 encoding, so when you insert the
data into another XML column, no conversion occurs.
The host expression or iterator data types that you can use to retrieve data from
XML columns are:
v java.sql.SQLXML (requires an SDK for Java Version 6 or later, and the IBM Data
Server Driver for JDBC and SQLJ version 4.0 or later)
If the application does not call the XMLSERIALIZE function before data retrieval,
the data is converted from UTF-8 to the external application encoding for the
character data types, or the internal encoding for the binary data types. No XML
declaration is added. If the host expression is an object of the java.sql.SQLXML or
com.ibm.db2.jcc.DB2Xml type, you need to call an additional method to retrieve
the data from this object. The method that you call determines the encoding of the
output data and whether an XML declaration with an encoding specification is
added.
The following table lists the methods that you can call to retrieve data from a
java.sql.SQLXML or a com.ibm.db2.jcc.DB2Xml object, and the corresponding
output data types and type of encoding in the XML declarations.
Table 27. SQLXML and DB2Xml methods, data types, and added encoding specifications
Method Output data type Type of XML internal encoding declaration added
SQLXML.getBinaryStream InputStream None
SQLXML.getCharacterStream Reader None
SQLXML.getSource Source None
SQLXML.getString String None
DB2Xml.getDB2AsciiStream InputStream None
DB2Xml.getDB2BinaryStream InputStream None
DB2Xml.getDB2Bytes byte[] None
DB2Xml.getDB2CharacterStream Reader None
DB2Xml.getDB2String String None
DB2Xml.getDB2XmlAsciiStream InputStream US-ASCII
DB2Xml.getDB2XmlBinaryStream InputStream Specified by getDB2XmlBinaryStream targetEncoding
parameter
DB2Xml.getDB2XmlBytes byte[] Specified by DB2Xml.getDB2XmlBytes targetEncoding
parameter
DB2Xml.getDB2XmlCharacterStream Reader ISO-10646-UCS-2
DB2Xml.getDB2XmlString String ISO-10646-UCS-2
Example: Suppose that you retrieve data from an XML column into a String host
expression.
#sql iterator XmlStringIter (int, String);
#sql [ctx] siter = {SELECT C1, CADOC from CUSTACC};
#sql {FETCH :siter INTO :row, :outString};
Example: Suppose that you retrieve data from an XML column into a byte[] host
expression.
#sql iterator XmlByteArrayIter (int, byte[]);
XmlByteArrayIter biter = null;
#sql [ctx] biter = {SELECT c1, CADOC from CUSTACC};
#sql {FETCH :biter INTO :row, :outBytes};
The byte[] type is a binary type, so no data conversion from UTF-8 encoding
occurs, and the data is returned without any XML declaration.
Example: Suppose that you retrieve a document from an XML column into a
java.sql.SQLXML host expression, but you need the data in a binary stream.
#sql iterator SqlXmlIter (int, java.sql.SQLXML);
SqlXmlIter SQLXMLiter = null;
java.sql.SQLXML outSqlXml = null;
#sql [ctx] SqlXmlIter = {SELECT c1, CADOC from CUSTACC};
#sql {FETCH :SqlXmlIter INTO :row, :outSqlXml};
java.io.InputStream XmlStream = outSqlXml.getBinaryStream();
The FETCH statement retrieves the data into the SQLXML object in UTF-8
encoding. The SQLXML.getBinaryStream stores the data in a binary stream.
Example: Suppose that you retrieve a document from an XML column into a
com.ibm.db2.jcc.DB2Xml host expression, but you need the data in a byte string
with an XML declaration that includes an internal encoding specification for
UTF-8.
#sql iterator DB2XmlIter (int, com.ibm.db2.jcc.DB2Xml);
DB2XmlIter db2xmliter = null;
com.ibm.db2.jcc.DB2Xml outDB2Xml = null;
#sql [ctx] db2xmliter = {SELECT c1, CADOC from CUSTACC};
#sql {FETCH :db2xmliter INTO :row, :outDB2Xml};
byte[] byteArray = outDB2XML.getDB2XmlBytes("UTF-8");
The FETCH statement retrieves the data into the DB2Xml object in UTF-8
encoding. The getDB2XmlBytes method with the UTF-8 argument adds an XML
declaration with a UTF-8 encoding specification and stores the data in a byte array.
Static import
The static import construct lets you access static members without qualifying those
members with the name of the class to which they belong. For SQLJ applications,
this means that you can use static members in host expressions without qualifying
them.
Example: Suppose that you want to declare a host expression of this form:
double r = cos(PI * E);
cos, PI, and E are members of the java.lang.Math class. To declare r without
explicitly qualifying cos, PI, and E, include the following static import statement in
your program:
import static java.lang.Math.*;
Annotations
Java annotations are a means for adding metadata to Java programs that can also
affect the way that those programs are treated by tools and libraries. Annotations
are declared with annotation type declarations, which are similar to interface
declarations. Java annotations can appear in the following types of classes or
interfaces:
v Class declaration
v Interface declaration
v Nested class declaration
v Nested interface declaration
You cannot include Java annotations directly in SQLJ programs, but you can
include annotations in Java source code, and then include that source code in your
SQLJ programs.
Example: Suppose that you declare the following marker annotation in a program
called MyAnnot.java:
public @interface MyAnot { }
Enumerated types
An enumerated type is a data type that consists of a set of ordered values. The
SDK for Java version 5 introduces the enum type for enumerated types.
Generics
You can use generics in your Java programs to assign a type to a Java collection.
The SQLJ translator tolerates Java generic syntax. Examples of generics that you
can use in SQLJ programs are:
v A List of List objects:
List <List<String>> strList2 = new ArrayList<List<String>>();
v A HashMap in which the key/value pair has the String type:
Map <String,String> map = new HashMap<String,String>();
v A method that takes a List with elements of any type:
public void mthd(List <?> obj) {
...
}
Although you can use generics in SQLJ host variables, the value of doing so is
limited because the SQLJ translator cannot determine the types of those host
variables.
The enhanced for lets you specify that a set of operations is performed on each
member of a collection or array. You can use the iterator in the enhanced for loop
in host expressions.
Example: INSERT each of the items in array names into table TAB.
String[] names = {"ABC","DEF","GHI"};
for (String n : names)
{
#sql {INSERT INTO TAB (VARCHARCOL) VALUES(:n) };
}
Varargs
The following table shows the values that you can specify in the SET
TRANSACTION ISOLATION LEVEL clause and their DB2 equivalents.
Table 28. Equivalent SQLJ and DB2 isolation levels
SET TRANSACTION value DB2 isolation level
SERIALIZABLE Repeatable read
REPEATABLE READ Read stability
READ COMMITTED Cursor stability
READ UNCOMMITTED Uncommitted read
The isolation level affects the underlying JDBC connection as well as the SQLJ
connection.
You do this using execution clauses that contain the SQL COMMIT or ROLLBACK
statements.
The following code prints out the SQL error that occurred if a SELECT statement
fails.
try {
#sql [ctxt] {SELECT LASTNAME INTO :empname
FROM EMPLOYEE WHERE EMPNO=’000010’};
To close the connection to the data source, use one of the ConnectionContext.close
methods.
v If you execute ConnectionContext.close() or
ConnectionContext.close(ConnectionContext.CLOSE_CONNECTION), the
connection context, as well as the connection to the data source, are closed.
v If you execute
ConnectionContext.close(ConnectionContext.KEEP_CONNECTION) the
connection context is closed, but the connection to the data source is not.
The following code closes the connection context, but does not close the connection
to the data source.
You can determine the security mechanism that is in effect for a connection by
calling the DB2Connection.getDB2SecurityMechanism method.
The following table lists the security mechanisms that the IBM Data Server Driver
for JDBC and SQLJ supports, and the data sources that support those security
mechanisms.
Table 29. Database server support for IBM Data Server Driver for JDBC and SQLJ security mechanisms
Security mechanism Supported by
DB2 Database for DB2 for z/OS IBM Informix DB2 for i
Linux, UNIX, and
Windows
User ID and password Yes Yes Yes Yes
User ID only Yes Yes Yes Yes
User ID and encrypted Yes Yes Yes Yes2
password
Encrypted user ID Yes Yes No No
Encrypted user ID and Yes Yes Yes Yes2
encrypted password
Encrypted user ID and No Yes No No
encrypted security-sensitive
data
Encrypted user ID, Yes Yes No No
encrypted password, and
encrypted security-sensitive
data
Kerberos1 Yes Yes No Yes
1
Plugin Yes No No No
Note:
1. Available for IBM Data Server Driver for JDBC and SQLJ type 4 connectivity only.
2. The version of the data source must be DB2 for i V6R1 or later.
The following table shows possible DB2 Database for Linux, UNIX, and Windows
server authentication types and the compatible IBM Data Server Driver for JDBC
and SQLJ securityMechanism property values.
Table 31. Compatible DB2 Database for Linux, UNIX, and Windows server authentication types and IBM Data Server
Driver for JDBC and SQLJ securityMechanism values
DB2 Database for Linux, UNIX, and
Windows server authentication type securityMechanism setting
CLIENT USER_ONLY_SECURITY
SERVER CLEAR_TEXT_PASSWORD_SECURITY
SERVER_ENCRYPT CLEAR_TEXT_PASSWORD_SECURITY,
ENCRYPTED_PASSWORD_SECURITY, or
ENCRYPTED_USER_AND_PASSWORD_SECURITY
DATA_ENCRYPT ENCRYPTED_USER_PASSWORD_AND_DATA_SECURITY
KERBEROS KERBEROS_SECURITY or PLUGIN_SECURITY2
KRB_SERVER_ENCRYPT KERBEROS_SECURITY , PLUGIN_SECURITY1,
ENCRYPTED_PASSWORD_SECURITY, or
ENCRYPTED_USER_AND_PASSWORD_SECURITY
GSSPLUGIN PLUGIN_SECURITY1 or KERBEROS_SECURITY
User ID and password security under the IBM Data Server Driver for
JDBC and SQLJ
With the IBM Data Server Driver for JDBC and SQLJ, one of the available security
methods is user ID and password security.
To specify user ID and password security for a JDBC connection, use one of the
following techniques.
For the DriverManager interface: You can specify the user ID and password
directly in the DriverManager.getConnection invocation. For example:
import java.sql.*; // JDBC base
...
String id = "dbadm"; // Set user ID
String pw = "dbadm"; // Set password
String url = "jdbc:db2://mvs1.sj.ibm.com:5021/san_jose";
// Set URL for the data source
Another method is to set the user ID and password directly in the URL string. For
example:
import java.sql.*; // JDBC base
...
String url =
"jdbc:db2://mvs1.sj.ibm.com:5021/san_jose:user=dbadm;password=dbadm;";
Alternatively, you can set the user ID and password by setting the user and
password properties in a Properties object, and then invoking the form of the
getConnection method that includes the Properties object as a parameter.
Optionally, you can set the securityMechanism property to indicate that you are
using user ID and password security. For example:
import java.sql.*; // JDBC base
import com.ibm.db2.jcc.*; // IBM Data Server Driver for JDBC
// and SQLJ implementation of JDBC
...
Properties properties = new java.util.Properties();
// Create Properties object
Chapter 5. Security under the IBM Data Server Driver for JDBC and SQLJ 169
properties.put("user", "dbadm"); // Set user ID for the connection
properties.put("password", "dbadm"); // Set password for the connection
properties.put("securityMechanism",
new String("" + com.ibm.db2.jcc.DB2BaseDataSource.CLEAR_TEXT_PASSWORD_SECURITY +
""));
// Set security mechanism to
// user ID and password
String url = "jdbc:db2://mvs1.sj.ibm.com:5021/san_jose";
// Set URL for the data source
Connection con = DriverManager.getConnection(url, properties);
// Create connection
For the DataSource interface: you can specify the user ID and password directly in
the DataSource.getConnection invocation. For example:
import java.sql.*; // JDBC base
import com.ibm.db2.jcc.*; // IBM Data Server Driver for JDBC
// and SQLJ implementation of JDBC
...
Context ctx=new InitialContext(); // Create context for JNDI
DataSource ds=(DataSource)ctx.lookup("jdbc/sampledb");
// Get DataSource object
String id = "dbadm"; // Set user ID
String pw = "dbadm"; // Set password
Connection con = ds.getConnection(id, pw);
// Create connection
Alternatively, if you create and deploy the DataSource object, you can set the user
ID and password by invoking the DataSource.setUser and DataSource.setPassword
methods after you create the DataSource object. Optionally, you can invoke the
DataSource.setSecurityMechanism method property to indicate that you are using
user ID and password security. For example:
...
com.ibm.db2.jcc.DB2SimpleDataSource ds = // Create DB2SimpleDataSource object
new com.ibm.db2.jcc.DB2SimpleDataSource();
ds.setDriverType(4); // Set driver type
ds.setDatabaseName("san_jose"); // Set location
ds.setServerName("mvs1.sj.ibm.com"); // Set server name
ds.setPortNumber(5021); // Set port number
ds.setUser("dbadm"); // Set user ID
ds.setPassword("dbadm"); // Set password
ds.setSecurityMechanism(
com.ibm.db2.jcc.DB2BaseDataSource.CLEAR_TEXT_PASSWORD_SECURITY);
// Set security mechanism to
// user ID and password
User ID-only security under the IBM Data Server Driver for JDBC and
SQLJ
With the IBM Data Server Driver for JDBC and SQLJ, one of the available security
methods is user-ID only security.
To specify user ID security for a JDBC connection, use one of the following
techniques.
For the DriverManager interface: Set the user ID and security mechanism by
setting the user and securityMechanism properties in a Properties object, and then
invoking the form of the getConnection method that includes the Properties object
as a parameter. For example:
import java.sql.*; // JDBC base
import com.ibm.db2.jcc.*; // IBM Data Server Driver
// for JDBC and SQLJ
For the DataSource interface: If you create and deploy the DataSource object, you
can set the user ID and security mechanism by invoking the DataSource.setUser
and DataSource.setSecurityMechanism methods after you create the DataSource
object. For example:
import java.sql.*; // JDBC base
import com.ibm.db2.jcc.*; // IBM Data Server Driver
// for JDBC and SQLJ
// implementation of JDBC
...
com.ibm.db2.jcc.DB2SimpleDataSource db2ds =
new com.ibm.db2.jcc.DB2SimpleDataSource();
// Create DB2SimpleDataSource object
db2ds.setDriverType(4); // Set the driver type
db2ds.setDatabaseName("san_jose"); // Set the location
db2ds.setServerName("mvs1.sj.ibm.com");
// Set the server name
db2ds.setPortNumber(5021); // Set the port number
db2ds.setUser("db2adm"); // Set the user ID
db2ds.setSecurityMechanism(
com.ibm.db2.jcc.DB2BaseDataSource.USER_ONLY_SECURITY);
// Set security mechanism to
// user ID only
The IBM Data Server Driver for JDBC and SQLJ supports 56-bit DES (weak)
encryption or 256-bit AES (strong) encryption. AES encryption is available with
IBM Data Server Driver for JDBC and SQLJ type 4 connectivity only. You set the
encryptionAlgorithm driver property to choose between 56-bit DES encryption
(encryptionAlgorithm value of 1) and 256-bit AES encryption (encryptionAlgorithm
value of 2). 256-bit AES encryption is used for a connection only if the database
server supports it and is configured to use it.
The IBM JCE needs to use 56-bit DES or 256-bit AES encrypted client/server
communication from the IBM Data Server Driver for JDBC and SQLJ driver to DB2
Database for Linux, UNIX, and Windows servers.
Chapter 5. Security under the IBM Data Server Driver for JDBC and SQLJ 171
For AES encryption, you need to get the unrestricted policy file for JCE. It is
available at the following URL: https://www14.software.ibm.com/webapp/iwm/
web/preLogin.do?source=jcesdk
Connections to DB2 for i V6R1 or later servers can use encrypted password
security or encrypted user ID and encrypted password security. For encrypted
password security or encrypted user ID and encrypted password security, the IBM
Java Cryptography Extension (ibmjceprovidere.jar) must be installed on your client.
The IBM JCE is part of the IBM SDK for Java, Version 1.4.2 or later.
You can also use encrypted security-sensitive data in addition to encrypted user ID
security or encrypted user ID and encrypted password security. You specify
encryption of security-sensitive data through the
ENCRYPTED_USER_AND_DATA_SECURITY or
ENCRYPTED_USER_PASSWORD_AND_DATA_SECURITY securityMechanism value.
ENCRYPTED_USER_AND_DATA_SECURITY is valid for connections to DB2 for z/OS
servers only, and only for DES encryption (encryptionAlgorithm value of 1).
DB2 for z/OS or DB2 Database for Linux, UNIX, and Windows database servers
encrypt the following data when you specify encryption of security-sensitive data:
v SQL statements that are being prepared, executed, or bound into a package
v Input and output parameter information
v Result sets
v LOB data
v XML data
v Results of describe operations
Before you can use encrypted security-sensitive data, the z/OS Integrated
Cryptographic Services Facility needs to be installed and enabled on the z/OS
operating system.
For the DriverManager interface: Set the user ID, password, and security
mechanism by setting the user, password, and securityMechanism properties in a
Properties object, and then invoking the form of the getConnection method that
includes the Properties object as a parameter. For example, use code like this to set
the user ID and encrypted password security mechanism, with AES encryption:
import java.sql.*; // JDBC base
import com.ibm.db2.jcc.*; // IBM Data Server Driver for JDBC
// and SQLJ implementation of JDBC
...
Properties properties = new Properties(); // Create a Properties object
properties.put("user", "dbadm"); // Set user ID for the connection
properties.put("password", "dbadm"); // Set password for the connection
properties.put("securityMechanism", "2");
new String("" + com.ibm.db2.jcc.DB2BaseDataSource.ENCRYPTED_PASSWORD_SECURITY +
""));
// Set security mechanism to
// user ID and encrypted password
properties.put("encryptionAlgorithm", "2");
// Request AES security
String url = "jdbc:db2://mvs1.sj.ibm.com:5021/san_jose";
// Set URL for the data source
Connection con = DriverManager.getConnection(url, properties);
// Create the connection
Kerberos security under the IBM Data Server Driver for JDBC and
SQLJ
JDBC support for Kerberos security is available for IBM Data Server Driver for
JDBC and SQLJ type 4 connectivity only.
To enable JDBC support for Kerberos security, you also need to enable the
following components of your software development kit (SDK) for Java:
v Java Cryptography Extension
v Java Generic Security Service (JGSS)
v Java Authentication and Authorization Service (JAAS)
See the documentation for your SDK for Java for information on how to enable
these components.
For this case, Kerberos uses the specified user ID and password to obtain a
ticket-granting ticket (TGT) that lets you authenticate to the database server.
Chapter 5. Security under the IBM Data Server Driver for JDBC and SQLJ 173
For the DriverManager interface: Set the user ID, password, Kerberos server, and
security mechanism by setting the user, password, kerberosServerPrincipal, and
securityMechanism properties in a Properties object, and then invoking the form of
the getConnection method that includes the Properties object as a parameter. For
example, use code like this to set the Kerberos security mechanism with a user ID
and password:
import java.sql.*; // JDBC base
import com.ibm.db2.jcc.*; // IBM Data Server Driver for JDBC
// and SQLJ implementation of JDBC
...
Properties properties = new Properties(); // Create a Properties object
properties.put("user", "db2adm"); // Set user ID for the connection
properties.put("password", "db2adm"); // Set password for the connection
properties.put("kerberosServerPrincipal",
"sample/[email protected]");
// Set the Kerberos server
properties.put("securityMechanism",
new String("" +
com.ibm.db2.jcc.DB2BaseDataSource.KERBEROS_SECURITY + ""));
// Set security mechanism to
// Kerberos
String url = "jdbc:db2://mvs1.sj.ibm.com:5021/san_jose";
// Set URL for the data source
Connection con = DriverManager.getConnection(url, properties);
// Create the connection
For the DataSource interface: If you create and deploy the DataSource object, set
the Kerberos server and security mechanism by invoking the
DataSource.setKerberosServerPrincipal and DataSource.setSecurityMechanism
methods after you create the DataSource object. For example:
import java.sql.*; // JDBC base
import com.ibm.db2.jcc.*; // IBM Data Server Driver for JDBC
// and SQLJ implementation of JDBC
...
com.ibm.db2.jcc.DB2SimpleDataSource db2ds =
new com.ibm.db2.jcc.DB2SimpleDataSource();
// Create the DataSource object
db2ds.setDriverType(4); // Set the driver type
db2ds.setDatabaseName("san_jose"); // Set the location
db2ds.setUser("db2adm"); // Set the user
db2ds.setPassword("db2adm"); // Set the password
db2ds.setServerName("mvs1.sj.ibm.com");
// Set the server name
db2ds.setPortNumber(5021); // Set the port number
db2ds.setKerberosServerPrincipal(
"sample/[email protected]");
// Set the Kerberos server
db2ds.setSecurityMechanism(
com.ibm.db2.jcc.DB2BaseDataSource.KERBEROS_SECURITY);
// Set security mechanism to
// Kerberos
For this case, the Kerberos default credentials cache must contain a ticket-granting
ticket (TGT) that lets you authenticate to the database server.
For the DataSource interface: If you create and deploy the DataSource object, set
the Kerberos server and security mechanism by invoking the
DataSource.setKerberosServerPrincipal and DataSource.setSecurityMechanism
methods after you create the DataSource object. For example:
import java.sql.*; // JDBC base
import com.ibm.db2.jcc.*; // IBM Data Server Driver for JDBC
// and SQLJ implementation of JDBC
...
DB2SimpleDataSource db2ds =
new com.ibm.db2.jcc.DB2SimpleDataSource();
// Create the DataSource object
db2ds.setDriverType(4); // Set the driver type
db2ds.setDatabaseName("san_jose"); // Set the location
db2ds.setServerName("mvs1.sj.ibm.com");
// Set the server name
db2ds.setPortNumber(5021); // Set the port number
db2ds.setKerberosServerPrincipal(
"sample/[email protected]");
// Set the Kerberos server
db2ds.setSecurityMechanism(
com.ibm.db2.jcc.DB2BaseDataSource.KERBEROS_SECURITY);
// Set security mechanism to
// Kerberos
For this case, you authenticate to the database server using a delegated credential
that another principal passes to you.
For the DriverManager interface: Set the Kerberos server, delegated credential, and
security mechanism by setting the kerberosServerPrincipal, and
securityMechanism properties in a Properties object. Then invoke the form of the
Chapter 5. Security under the IBM Data Server Driver for JDBC and SQLJ 175
getConnection method that includes the Properties object as a parameter. For
example, use code like this to set the Kerberos security mechanism without a user
ID and password:
import java.sql.*; // JDBC base
import com.ibm.db2.jcc.*; // IBM Data Server Driver for JDBC
// and SQLJ implementation of JDBC
...
Properties properties = new Properties(); // Create a Properties object
properties.put("kerberosServerPrincipal",
“sample/[email protected]");
// Set the Kerberos server
properties.put("gssCredential",delegatedCredential);
// Set the delegated credential
properties.put("securityMechanism",
new String("" +
com.ibm.db2.jcc.DB2BaseDataSource.KERBEROS_SECURITY + ""));
// Set security mechanism to
// Kerberos
String url = "jdbc:db2://mvs1.sj.ibm.com:5021/san_jose";
// Set URL for the data source
Connection con = DriverManager.getConnection(url, properties);
// Create the connection
For the DataSource interface: If you create and deploy the DataSource object, set
the Kerberos server, delegated credential, and security mechanism by invoking the
DataSource.setKerberosServerPrincipal, DataSource.setGssCredential, and
DataSource.setSecurityMechanism methods after you create the DataSource object.
For example:
DB2SimpleDataSource db2ds = new com.ibm.db2.jcc.DB2SimpleDataSource();
// Create the DataSource object
db2ds.setDriverType(4); // Set the driver type
db2ds.setDatabaseName("san_jose"); // Set the location
db2ds.setServerName("mvs1.sj.ibm.com"); // Set the server name
db2ds.setPortNumber(5021); // Set the port number
db2ds.setKerberosServerPrincipal(
"sample/[email protected]");
// Set the Kerberos server
db2ds.setGssCredential(delegatedCredential);
// Set the delegated credential
db2ds.setSecurityMechanism(
com.ibm.db2.jcc.DB2BaseDataSource.KERBEROS_SECURITY);
// Set security mechanism to
// Kerberos
IBM Data Server Driver for JDBC and SQLJ security plugin support
You can create your own authentication mechanisms in the form of loadable
libraries, or plugins, that DB2 Database for Linux, UNIX, and Windows loads to
perform user authentication. To support development of security plugins in Java,
the IBM Data Server Driver for JDBC and SQLJ provides security plugin support.
IBM Data Server Driver for JDBC and SQLJ security plugin support is available for
IBM Data Server Driver for JDBC and SQLJ type 4 connectivity to DB2 Database
for Linux, UNIX, and Windows servers only.
To use plugin security, you need a security plugin on the client and another plugin
on the server.
Chapter 5. Security under the IBM Data Server Driver for JDBC and SQLJ 177
Table 32. Connection or DataSource property settings for Java security plugin use (continued)
Property Setting
com.ibm.db2.jcc.DB2BaseDataSource.securityMechanism com.ibm.db2.jcc.DB2BaseDataSource.PLUGIN_SECURITY
com.ibm.db2.jcc.DB2BaseDataSource.pluginName The name of the plugin module for a server-side security
plugin
com.ibm.db2.jcc.DB2BaseDataSource.plugin The plugin object for a client-side security plugin
Example: The following code sets the properties for a connection that uses GSS-API
plugin security. The connection uses the JCCSimpleGSSPlugin sample plugin on
the client side, and the gssapi_simple sample plugin on the server side.
java.util.Properties properties = new java.util.Properties();
properties.put("user", "db2admin");
properties.put("password", "admindb2");
properties.put("pluginName", "gssapi_simple");
properties.put("securityMechanism",
new String(""+com.ibm.db2.jcc.DB2BaseDataSource.PLUGIN_SECURITY+""));
com.ibm.db2.jcc.DB2JCCPlugin plugin =
new com.ibm.db2.jcc.samples.plugins.JCCSimpleGSSplugin();
properties.put("plugin", plugin);
Connection con = java.sql.DriverManager.getConnection(url,
properties);
The following table lists the IBM Data Server Driver for JDBC and SQLJ security
mechanisms, and the alternative security mechanisms that are used when the
original connection has an authorization failure.
Table 33. Original and alternative IBM Data Server Driver for JDBC and SQLJ security mechanisms
IBM Data Server Driver for JDBC and SQLJ authentication type for the IBM Data Server Driver for JDBC and SQLJ authentication type
Server authentication type original connection for retrying the connection
CLIENT USER_ONLY_SECURITY
v CLEAR_TEXT_PASSWORD_SECURITY
v ENCRYPTED_PASSWORD_SECURITY
v ENCRYPTED_USER_AND_PASSWORD_SECURITY
v KERBEROS_SECURITY
v ENCRYPTED_USER_AND_DATA_SECURITY
v ENCRYPTED_USER_PASSWORD_AND_DATA_SECURITY
v PLUGIN_SECURITY
v ENCRYPTED_USER_ONLY_SECURITY
USER_ONLY_SECURITY None. USER_ONLY_SECURITY does not fail on the original
connection.
v ENCRYPTED_PASSWORD_SECURITY
v ENCRYPTED_USER_AND_PASSWORD_SECURITY
v KERBEROS_SECURITY
v ENCRYPTED_USER_AND_DATA_SECURITY
v ENCRYPTED_USER_PASSWORD_AND_DATA_SECURITY
v PLUGIN_SECURITY
v ENCRYPTED_USER_ONLY_SECURITY
CLEAR_TEXT_PASSWORD_SECURITY None. CLEAR_TEXT_PASSWORD_SECURITY does not fail on the
original connection.
SERVER_ENCRYPT for DB2 ENCRYPTED_USER_AND_PASSWORD_SECURITY
v CLEAR_TEXT_PASSWORD_SECURITY
Database for Linux, UNIX,
and Windows Version 8 Fix v USER_ONLY_SECURITY
Pack 9 or earlier
v KERBEROS_SECURITY
v ENCRYPTED_USER_AND_DATA_SECURITY
v ENCRYPTED_USER_PASSWORD_AND_DATA_SECURITY
v PLUGIN_SECURITY
v ENCRYPTED_USER_ONLY_SECURITY
v USER_ONLY_SECURITY
v ENCRYPTED_PASSWORD_SECURITY
v ENCRYPTED_USER_AND_PASSWORD_SECURITY
v ENCRYPTED_USER_AND_DATA_SECURITY
v ENCRYPTED_USER_PASSWORD_AND_DATA_SECURITY
v PLUGIN_SECURITY
v ENCRYPTED_USER_ONLY_SECURITY
KERBEROS_SECURITY None. KERBEROS_SECURITY does not fail on the original
connection.
Chapter 5. Security under the IBM Data Server Driver for JDBC and SQLJ 179
Table 33. Original and alternative IBM Data Server Driver for JDBC and SQLJ security mechanisms (continued)
IBM Data Server Driver for JDBC and SQLJ authentication type for the IBM Data Server Driver for JDBC and SQLJ authentication type
Server authentication type original connection for retrying the connection
GSSPLUGIN v CLEAR_TEXT_PASSWORD_SECURITY
PLUGIN_SECURITY
v USER_ONLY_SECURITY
v ENCRYPTED_PASSWORD_SECURITY
v ENCRYPTED_USER_AND_PASSWORD_SECURITY
v KERBEROS_SECURITY
v ENCRYPTED_USER_AND_DATA_SECURITY
v ENCRYPTED_USER_PASSWORD_AND_DATA_SECURITY
v ENCRYPTED_USER_ONLY_SECURITY
PLUGIN_SECURITY None. PLUGIN_SECURITY does not fail on the original
connection.
KRB_SERVER_ENCRYPT v USER_ONLY_SECURITY
KERBEROS_SECURITY
v ENCRYPTED_USER_AND_DATA_SECURITY
v ENCRYPTED_USER_PASSWORD_AND_DATA_SECURITY
v ENCRYPTED_USER_ONLY_SECURITY
None. CLEAR_TEXT_PASSWORD_SECURITY,
v CLEAR_TEXT_PASSWORD_SECURITY
ENCRYPTED_PASSWORD_SECURITY,
v ENCRYPTED_PASSWORD_SECURITY ENCRYPTED_USER_AND_PASSWORD_SECURITY,
KERBEROS_SECURITY, and PLUGIN_SECURITY do not fail on
v ENCRYPTED_USER_AND_PASSWORD_SECURITY
the original connection.
v KERBEROS_SECURITY
v PLUGIN_SECURITY
GSS_SERVER_ENCRYPT v USER_ONLY_SECURITY
KERBEROS_SECURITY
v ENCRYPTED_USER_AND_DATA_SECURITY
v ENCRYPTED_USER_PASSWORD_AND_DATA_SECURITY
v ENCRYPTED_USER_ONLY_SECURITY
None. CLEAR_TEXT_PASSWORD_SECURITY,
v CLEAR_TEXT_PASSWORD_SECURITY
ENCRYPTED_PASSWORD_SECURITY,
v ENCRYPTED_PASSWORD_SECURITY ENCRYPTED_USER_AND_PASSWORD_SECURITY,
KERBEROS_SECURITY, and PLUGIN_SECURITY do not fail on
v ENCRYPTED_USER_AND_PASSWORD_SECURITY
the original connection.
v KERBEROS_SECURITY
v PLUGIN_SECURITY
IBM Data Server Driver for JDBC and SQLJ trusted context support
The IBM Data Server Driver for JDBC and SQLJ provides methods that allow you
to establish and use trusted connections in Java programs.
A trusted context is an object that the database administrator defines that contains
a system authorization ID and a set of trust attributes. Currently, for DB2 database
servers, a database connection is the only type of context that is supported. The
trust attributes identify a set of characteristics of a connection that are required for
After a trusted context is defined, and an initial trusted connection to the data
server is made, the middleware server can use that database connection under a
different user without reauthenticating the new user at the database server.
Chapter 5. Security under the IBM Data Server Driver for JDBC and SQLJ 181
Example: Reuse an existing trusted connection:
// The first item that was obtained from the previous getDB2TrustedPooledConnection
// call is a connection object. Cast it to a PooledConnection object.
javax.sql.PooledConnection pooledCon =
(javax.sql.PooledConnection)objects[0];
properties = new java.util.Properties();
// Set new properties for the reused object using
// properties.put("property", "value");
// The second item that was obtained from the previous getDB2TrustedPooledConnection
// call is the cookie for the connection. Cast it as a byte array.
byte[] cookie = ((byte[])(objects[1]);
// Supply the user ID for the new connection.
String newuser = "newuser";
// Supply the name of a mapping service that maps a workstation user
// ID to a z/OS RACF ID
String userRegistry = "registry";
// Do not supply any security token data to be traced.
byte[] userSecTkn = null;
// Do not supply a previous user ID.
String originalUser = null;
// Call getDB2Connection to get the connection object for the new
// user.
java.sql.Connection con =
((com.ibm.db2.jcc.DB2PooledConnection)pooledCon).getDB2Connection(
cookie,newuser,password,userRegistry,userSecTkn,originalUser,properties);
IBM Data Server Driver for JDBC and SQLJ support for SSL
The IBM Data Server Driver for JDBC and SQLJ provides support for the Secure
Sockets Layer (SSL) through the Java Secure Socket Extension (JSSE).
You can use SSL support in your Java applications if you use IBM Data Server
Driver for JDBC and SQLJ type 4 connectivity to DB2 for z/OS Version 9 or later,
to DB2 Database for Linux, UNIX, and Windows Version 9.1, Fix Pack 2 or later, or
to IBM Informix (IDS) Version 11.50 or later.
If you use SSL support for a connection to a DB2 for z/OS data source, and the
z/OS version is V1.8, V1.9, or V1.10, the appropriate PTF for APAR PK72201 must
be applied to Communication Server for z/OS IP Services.
Prerequisite: Before a connection to a data source can use SSL, the port to which
the application connects must be configured in the database server as the SSL
listener port.
1. Set DB2BaseDataSource.sslConnection on a Connection or DataSource instance.
2. Optional: Set DB2BaseDataSource.sslTrustStoreLocation on a Connection or
DataSource instance to identify the location of the truststore. Setting the
sslTrustStoreLocation property is an alternative to setting the Java
Before you can configure your Java Runtime Environment for SSL, you need to
satisfy the following prerequisites:
v The Java Runtime Environment must include a Java security provider. The IBM
JSSE provider or the Sun JSSE provider must be installed. The IBM JSSE
provider is automatically installed with the IBM SDK for Java.
Restriction: You can only use the Sun JSSE provider only with a Sun Java
Runtime Environment. The Sun JSSE provider does not work with an IBM Java
Runtime Environment.
v SSL support must be configured on the database server.
To configure your Java Runtime Environment to use SSL, follow these steps.
1. Import a certificate from the database server to a Java truststore on the client.
Use the Java keytool utility to import the certificate into the truststore.
For example, suppose that the server certificate is stored in a file named
jcc.cacert. Issue the following keytool utility statement to read the certificate
from file jcc.cacert, and store it in a truststore named cacerts.
keytool -import -file jcc.cacert -keystore cacerts
2. Configure the Java Runtime Environment for the Java security providers by
adding entries to the java.security file.
The format of a security provider entry is:
security.provider.n=provider-package-name
A provider with a lower value of n takes precedence over a provider with a
higher value of n.
The Java security provider entries that you add depend on whether you use the
IBM JSSE provider or the Sun JSSE provider.
v If you use the Sun JSSE provider, add entries for the Sun security providers
to your java.security file.
v If you use the IBM JSSE provider, use one of the following methods:
– Use the IBMJSSE2 provider (supported for the IBM SDK for Java 1.4.2
and later):
Chapter 5. Security under the IBM Data Server Driver for JDBC and SQLJ 183
Recommendation: Use the IBMJSSE2 provider, and use it in FIPS mode.
- If you do not need to operate in FIPS-compliant mode:
v For the IBM SDK for Java 1.4.2, add an entry for the
IBMJSSE2Provider to the java.security file. Ensure that an entry for
the IBMJCE provider is in the java.security file. The java.security file
that is shipped with the IBM SDK for Java contains an entry for
entries for IBMJCE.
v For later versions of the IBM SDK for Java, ensure that entries for the
IBMJSSE2Provider and the IBMJCE provider are in the java.security
file. The java.security file that is shipped with the IBM SDK for Java
contains entries for those providers.
- If you need to operate in FIPS-compliant mode:
v Add an entry for the IBMJCEFIPS provider to your java.security file
before the entry for the IBMJCE provider. Do not remove the entry
for the IBMJCE provider.
v Enable FIPS mode in the IBMJSSE2 provider. See step 3 on page 185.
– Use the IBMJSSE provider (supported for the IBM SDK for Java 1.4.2
only):
- If you do not need to operate in FIPS-compliant mode, ensure that
entries for the IBMJSSEProvider and the IBMJCE provider are in the
java.security file. The java.security file that is shipped with the IBM
SDK for Java contains entries for those providers.
- If you need to operate in FIPS-compliant mode, add entries for the
FIPS-approved provider IBMJSSEFIPSProvider and the IBMJCEFIPS
provider to your java.security file, before the entry for the IBMJCE
provider.
Restriction: When the IBMJSSE2 provider runs in FIPS mode, it cannot use
hardware cryptography.
4. Configure the Java Runtime Environment for the SSL socket factory providers
by adding entries to the java.security file.
The format of SSL socket factory provider entries are:
ssl.SocketFactory.provider=provider-package-name
ssl.ServerSocketFactory.provider=provider-package-name
Specify the SSL socket factory provider for the Java security provider that you
are using.
Example: Include SSL socket factory provider entries like these in the
java.security file when you enable FIPS mode in the IBMJSSE2 provider:
# Set the SSL socket factory provider
ssl.SocketFactory.provider=com.ibm.jsse2.SSLSocketFactoryImpl
ssl.ServerSocketFactory.provider=com.ibm.jsse2.SSLServerSocketFactoryImpl
Example: Include SSL socket factory provider entries like these in the
java.security file when you enable FIPS mode in the IBMJSSE provider:
# Set the SSL socket factory provider
ssl.SocketFactory.provider=com.ibm.fips.jsse.JSSESocketFactory
ssl.ServerSocketFactory.provider=com.ibm.fips.jsse.JSSEServerSocketFactory
Example: Include SSL socket factory provider entries like these when you use
the Sun JSSE provider:
# Set the SSL socket factory provider
ssl.SocketFactory.provider=com.sun.net.ssl.internal.ssl.SSLSocketFactoryImpl
ssl.ServerSocketFactory.provider=com.sun.net.ssl.internal.ssl.SSLServerSocketFactoryImpl
5. Configure Java system properties to use the truststore.
To do that, set the following Java system properties:
javax.net.ssl.trustStore
Specifies the name of the truststore that you specified with the
-keystore parameter in the keytool utility in step 1 on page 183.
If the IBM Data Server Driver for JDBC and SQLJ property
DB2BaseDataSource.sslTrustStoreLocation is set, its value overrides the
javax.net.ssl.trustStore property value.
javax.net.ssl.trustStorePassword (optional)
Specifies the password for the truststore. You do not need to set a
truststore password. However, if you do not set the password, you
cannot protect the integrity of the truststore.
If the IBM Data Server Driver for JDBC and SQLJ property
DB2BaseDataSource.sslTrustStorePassword is set, its value overrides the
javax.net.ssl.trustStorePassword property value.
Example: One way that you can set Java system properties is to specify them as
the arguments of the -D option when you run a Java application. Suppose that
you want to run a Java application named MySSL.java, which accesses a data
source using an SSL connection. You have defined a truststore named cacerts.
The following command sets the truststore name when you run the application.
Chapter 5. Security under the IBM Data Server Driver for JDBC and SQLJ 185
java -Djavax.net.ssl.trustStore=cacerts MySSL
Security for preparing SQLJ applications with the IBM Data Server
Driver for JDBC and SQLJ
Two ways to provide security during SQLJ application preparation are to allow
users to customize applications only, and to limit access to a specific set of tables
during customization.
You can use one of the following techniques to allow a set of users to customize
SQLJ applications, but not to bind or run those applications:
v Create a database system for customization only (recommended solution):
Follow these steps:
1. Create a new database manager instance. This is the customization-only
system.
2. On the customization-only system, define all the tables and views that are
accessed by the SQLJ applications. The table or view definitions must be the
same as the definitions on the database manager instance where the
application will be bound and will run (the bind-and-run system). Executing
the DESCRIBE statement on the tables or views must give the same results
on the customization-only system and the bind-and-run system.
3. On the customization-only system, grant the necessary table or view
privileges to users who will customize SQLJ applications.
4. On the customization-only system, users run the sqlj command with the
-compile=true option to create Java byte codes and serialized profiles for
their programs. Then they run the db2sqljcustomize command with the
-automaticbind NO option to create customized serialized profiles.
5. Copy the java byte code files and customized serialized profiles to the
bind-and-run system.
6. A user with authority to bind packages on the bind-and-run system runs the
db2sqljbind command on the customized serialized profiles that were copied
from the customization-only system.
v Use a stored procedure to do customization: Write a Java stored procedure that
customizes serialized profiles and binds packages for SQLJ applications on
behalf of the end user. This Java stored procedure needs to use a JDBC driver
package that was bound with one of the DYNAMICRULES options that causes
dynamic SQL to be performed under a different user ID from the end user's
authorization ID. For example, you might use the DYNAMICRULES option
DEFINEBIND or DEFINERUN to execute dynamic SQL under the authorization
ID of the creator of the Java stored procedure. You need to grant EXECUTE
authority on the stored procedure to users who need to do SQLJ customization.
The stored does the following things:
1. Receives the compiled SQLJ program and serialized profiles in BLOB input
parameters
2. Copies the input parameters to its file system
3. Runs db2sqljcustomize to customize the serialized profiles and bind the
packages for the SQLJ program
4. Returns the customized serialized profiles in output parameters
v Use a stand-alone program to do customization: This technique involves
writing a program that performs the same steps as a Java stored procedure that
When you customize serialized profiles, you should do online checking, to give the
application program information about the data types and lengths of table columns
that the program accesses. By default, customization includes online checking.
Online checking requires that the user who customizes a serialized profile has
authorization to execute PREPARE and DESCRIBE statements against SQL
statements in the SQLJ program. That authorization includes the SELECT privilege
on tables and views that are accessed by the SQL statements. If SQL statements
contain unqualified table names, the qualifier that is used during online checking
is the value of the db2sqljcustomize -qualifier parameter. Therefore, for online
checking of tables and views with unqualified names in an SQLJ application, you
can grant the SELECT privilege only on tables and views with a qualifier that
matches the value of the -qualifier parameter.
Chapter 5. Security under the IBM Data Server Driver for JDBC and SQLJ 187
188 Developing Java Applications
Chapter 6. Security under the DB2 JDBC Type 2 Driver
The DB2 JDBC Type 2 Driver for Linux, UNIX and Windows (DB2 JDBC Type 2
Driver) supports user ID and password security.
You must set the user ID and the password, or set neither. If you do not set a user
ID and password, the driver uses the user ID and password of the user who is
currently logged on to the operating system.
To specify user ID and password security for a JDBC connection, use one of the
following techniques.
For the DriverManager interface: you can specify the user ID and password
directly in the DriverManager.getConnection invocation. For example:
import java.sql.*; // JDBC base
...
String id = "db2adm"; // Set user ID
Sring pw = "db2adm"; // Set password
String url = "jdbc:db2:toronto";
// Set URL for the data source
Connection con = DriverManager.getConnection(url, id, pw);
// Create connection
Alternatively, you can set the user ID and password by setting the user and
password properties in a Properties object, and then invoking the form of the
getConnection method that includes the Properties object as a parameter. For
example:
import java.sql.*; // JDBC base
import COM.ibm.db2.jdbc.*; // DB2 JDBC Type 2 driver
// implementation of JDBC
...
Properties properties = new java.util.Properties();
// Create Properties object
properties.put("user", "db2adm"); // Set user ID for the connection
properties.put("password", "db2adm"); // Set password for the connection
String url = "jdbc:db2:toronto";
// Set URL for the data source
Connection con = DriverManager.getConnection(url, properties);
// Create connection
For the DataSource interface: you can specify the user ID and password directly in
the DataSource.getConnection invocation. For example:
import java.sql.*; // JDBC base
import COM.ibm.db2.jdbc.*; // DB2 JDBC Type 2 driver
// implementation of JDBC
...
Context ctx=new InitialContext(); // Create context for JNDI
DataSource ds=(DataSource)ctx.lookup("jdbc/sampledb");
// Get DataSource object
String id = "db2adm"; // Set user ID
Sring pw = "db2adm"; // Set password
Connection con = ds.getConnection(id, pw);
// Create connection
Alternatively, if you create and deploy the DataSource object, you can set the user
ID and password by invoking the DataSource.setUser and DataSource.setPassword
methods after you create the DataSource object. For example:
The following steps demonstrate how to build and run the Applt.java sample
JDBC applet.
1. Compile Applt.java to produce the file Applt.class with this command:
javac Applt.java
2. Ensure that your working directory is accessible by your web browser, or by
your Java applet viewer, if you are using it. If your directory is not accessible,
copy the following files into a directory that is accessible:
v Applt.html
v Applt.class
3. Copy sqllib\java\db2jcc.jar on Windows or sqllib/java/db2jcc.jar on
UNIX, into the same directory as Applt.class and Applt.html.
If you are using any JDBC 4.0 functions, copy db2jcc4.jar instead of db2jcc.jar.
4. If you are using the IBM Data Server Driver for JDBC and SQLJ, connect with
that driver by modifying the Applt.html file according to the instructions in the
file. For the TCP/IP port number, you should use the database port number
50000.
5. To run this applet, either ensure that a web server is installed and running on
your DB2 machine (server or client), or you can use the applet viewer that
comes with the SDK for Java by entering the following command in the
working directory of your client machine:
appletviewer Applt.html
The following steps demonstrate how to build and run the DbInfo sample JDBC
application.
1. Compile DbInfo.java to produce the file DbInfo.class with this command:
javac DbInfo.java
2. If you are running a Java application on UNIX in a 64-bit DB2 instance but the
software development kit for Java is 32-bit, you need to change the DB2 library
path before running the application. For example, on AIX:
v If using bash or Korn shell:
export LIBPATH=$HOME/sqllib/lib32
v If using C shell:
setenv LIBPATH $HOME/sqllib/lib32
The following steps demonstrate how to build and run these routines:
v The SpServer sample JDBC stored procedure
v The UDFsrv sample user-defined function, which has no SQL statements
v The UDFsqlsv sample user-defined function, which has SQL statements
v To build and run the SpServer.java stored procedure on the server, from the
command line:
1. Compile SpServer.java to produce the file SpServer.class with this command:
javac SpServer.java
2. Copy SpServer.class to the sqllib\function directory on Windows
operating systems, or to the sqllib/function directory on UNIX.
3. Catalog the routines by running the spcat script on the server. The spcat
script connects to the sample database, uncatalogs the routines if they were
previously cataloged by calling SpDrop.db2, then catalogs them by calling
SpCreate.db2, and finally disconnects from the database. You can also run the
SpDrop.db2 and SpCreate.db2 scripts individually.
4. Stop and restart the database to allow the new class file to be recognized. If
necessary, set the file mode for the class file to "read" so it is readable by the
fenced user.
5. Compile and run the SpClient client application to access the stored
procedure class.
v To build and run the UDFsrv.java user-defined function program (user-defined
function with no SQL statements) on the server, from the command line:
1. Compile UDFsrv.java to produce the file UDFsrv.class with this command:
javac UDFsrv.java
2. Copy UDFsrv.class to the sqllib\function directory on Windows operating
systems, or to the sqllib/function directory on UNIX.
3. Compile and run a client program that calls UDFsrv.
To access the UDFsrv library, you can use the UDFcli.java JDBC application,
or the UDFcli.sqlj SQLJ client application. Both versions of the client program
contain the CREATE FUNCTION SQL statement that you use to register the
user-defined functions with the database, and also contain SQL statements
that use the user-defined functions.
v To build and run the UDFsqlsv.java user-defined function program (user-defined
function with SQL statements) on the server, from the command line:
1. Compile UDFsqlsv.java to produce the file UDFsqlsv.class with this
command:
javac UDFsqlsv.java
2. Copy UDFsqlsv.class to the sqllib\function directory on Windows
operating systems, or to the sqllib/function directory on UNIX.
3. Compile and run a client program that calls UDFsqlsv.
To access the UDFsqlsv library, you can use the UDFsqlcl.java JDBC
application. The client program contains the CREATE FUNCTION SQL
The following steps demonstrate how to build and run the Applt sample SQLJ
applet. These steps use the build file, bldsqlj (UNIX), or bldsqlj.bat (Windows),
which contains commands to build either an SQLJ applet or application.
The build file takes up to six parameters: $1, $2, $3, $4, $5, and $6 on UNIX, and
%1, %2, %3, %4, %5, and %6 on Windows. The first parameter specifies the name
of your program. The second parameter specifies the user ID for the database
instance, the third parameter specifies the password. The fourth parameter
specifies the server name. The fifth parameter specifies the port number. And the
sixth parameter specifies the database name. For all but the first parameter,
program name, default values can be used. See the build file for details about
using default parameter values.
1. Build the applet with this command:
bldsqlj Applt <userid> <password> <server_name> <port_number> <db_name>
2. Ensure that your working directory is accessible by your web browser, or by
your Java applet viewer, if you are using it. If your directory is not accessible,
copy the following files into a directory that is accessible:
v Applt.html
v Applt.class
v Applt_Cursor1.class
v Applt_Cursor2.class
v Applt_SJProfileKeys.class
v Applt_SJProfile0.ser
3. Copy sqllib\java\db2jcc.jar on Windows or sqllib/java/db2jcc.jar on
UNIX, into the same directory as Applt.class and Applt.html.
If you are using any JDBC 4.0 functions, copy db2jcc4.jar instead of db2jcc.jar.
4. If you are using the IBM Data Server Driver for JDBC and SQLJ, connect with
that driver by modifying the Applt.html file according to the instructions in the
file. For the TCP/IP port number, you should use the database port number
50000.
5. To run this applet, either ensure that a web server is installed and running on
your DB2 machine (server or client), or you can use the applet viewer that
comes with the SDK for Java by entering the following command in the
working directory of your client machine:
appletviewer Applt.html
The following steps demonstrate how to build and run the TbMod sample SQLJ
application. These steps use the build file, bldsqlj (UNIX), or bldsqlj.bat
(Windows), which contains commands to build either an SQLJ applet or
application.
or
java sqlj.runtime.profile.util.SerProfileToClass Applt_SJProfile0.ser
Recommendation: Use the same SQLJ translator and customizer options that
bldsqlj uses when you build your SQLJ applications and applets on UNIX
platforms.
Recommendation: Use the same SQLJ translator and customizer options that
bldsqlj.bat uses when you build your SQLJ applications and applets on Windows
operating systems.
The following steps demonstrate how to build and run the SpServer sample SQLJ
stored procedure. These steps use the build file, bldsqljs (UNIX), or bldsqljs.bat
(Windows), which contains commands to build either an SQLJ applet or
application.
The build file takes up to six parameters: $1, $2, $3, $4, $5, and $6 on UNIX, and
%1, %2, %3, %4, %5, and %6 on Windows. The first parameter specifies the name
of your program. The second parameter specifies the user ID for the database
instance, the third parameter specifies the password. The fourth parameter
specifies the server name. The fifth parameter specifies the port number. And the
sixth parameter specifies the database name. For all but the first parameter,
program name, default values can be used. See the build file for details about
using default parameter values.
1. Build the stored procedure application with this command:
bldsqljs SpServer <userid> <password> <server_name> <port_number> <db_name>
2. Catalog the stored procedure with this command:
spcat
This script connects to the sample database, uncatalogs the routines if they
were previously cataloged by calling SpDrop.db2, then catalogs them by calling
SpCreate.db2, and finally disconnects from the database. You can also run the
SpDrop.db2 and SpCreate.db2 scripts individually.
3. Stop and restart the database to allow the new class file to be recognized. If
necessary, set the file mode for the class file to read, so it is readable by the
fenced user.
4. Compile and run the SpClient client application to access the stored procedure
class. You can build SpClient with the application build file, bldsqlj (UNIX) or
bldsqlj.bat (Windows).
Recommendation: Use the same SQLJ translator and customizer options that
bldsqljs uses when you build your SQLJ routines on UNIX platforms.
Recommendation: Use the same SQLJ translator and customizer options that
bldsqljs.bat uses when you build your SQLJ routines on Windows operating
systems.
The following SQLJ translator and customizer options are used in the bldsqljs.bat
batch file on Windows operating systems. These are the options DB2 recommends
that you use to build SQLJ routines (stored procedures and user-defined functions).
sqlj The SQLJ translator (also compiles the program).
%1.sqlj
The SQLJ source file.
db2sqljcustomize
The DB2 for Java profile customizer.
-url Specifies a JDBC URL for establishing a database connection, such as
jdbc:db2://servername:50000/sample.
-user Specifies a user ID.
-password
Specifies a password.
%1_SJProfile0
Specifies a serialized profile for the program.
You should run the trace and diagnostic utilities only under the direction of IBM
software support.
Procedure 1: For IBM Data Server Driver for JDBC and SQLJ type 4 connectivity or
IBM Data Server Driver for JDBC and SQLJ type 2 connectivity for DB2 for Linux,
UNIX and Windows, the recommended method is to start the trace by setting the
db2.jcc.override.traceFile property or the db2.jcc.override.traceDirectory property in
the IBM Data Server Driver for JDBC and SQLJ configuration properties file. You
can set the db2.jcc.tracePolling and db2.jcc.tracePollingInterval properties before
you start the driver to allow you to change global configuration trace properties
while the driver is running.
Procedure 2: If you use the DataSource interface to connect to a data source, follow
this method to start the trace:
1. Invoke the DB2BaseDataSource.setTraceLevel method to set the type of tracing
that you need. The default trace level is TRACE_ALL. See "Properties for the IBM
Data Server Driver for JDBC and SQLJ" for information on how to specify more
than one type of tracing.
2. Invoke the DB2BaseDataSource.setJccLogWriter method to specify the trace
destination and turn the trace on.
Procedure 3:
If you use the DataSource interface to connect to a data source, invoke the
javax.sql.DataSource.setLogWriter method to turn the trace on. With this method,
TRACE_ALL is the only available trace level.
If you use the DriverManager interface to connect to a data source, follow this
procedure to start the trace.
1. Invoke the DriverManager.getConnection method with the traceLevel property
set in the info parameter or url parameter for the type of tracing that you need.
The default trace level is TRACE_ALL. See "Properties for the IBM Data Server
Driver for JDBC and SQLJ" for information on how to specify more than one
type of tracing.
2. Invoke the DriverManager.setLogWriter method to specify the trace destination
and turn the trace on.
After a connection is established, you can turn the trace off or back on, change the
trace destination, or change the trace level with the DB2Connection.setJccLogWriter
method. To turn the trace off, set the logWriter value to null.
Procedure 4: If you are using the DriverManager interface, specify the traceFile
and traceLevel properties as part of the URL when you load the driver. For
example:
String url = "jdbc:db2://sysmvs1.stl.ibm.com:5021/san_jose" +
":traceFile=/u/db2p/jcctrace;" +
"traceLevel=" + com.ibm.db2.jcc.DB2BaseDataSource.TRACE_DRDA_FLOWS + ";";
Trace example program: For a complete example of a program for tracing under the
IBM Data Server Driver for JDBC and SQLJ, see "Example of a trace program
under the IBM Data Server Driver for JDBC and SQLJ".
To collect trace data to diagnose problems during the SQLJ customization or bind
process, specify the -tracelevel and -tracefile options when you run the
db2sqljcustomize or db2sqljbind bind utility.
profp serialized-profile-name
Run the profp utility on the serialized profile for the connection in which the error
occurs. If an exception is thrown, a Java stack trace is generated. You can
determine which serialized profile was in use when the exception was thrown
from the stack trace.
Run the db2sqljprint utility on the customized serialized profile for the
connection in which the error occurs.
Suppose that you want to collect trace data for a program named Test.java, which
uses IBM Data Server Driver for JDBC and SQLJ type 4 connectivity. Test.java does
no tracing, and you do not want to modify the program, so you enable tracing
using configuration properties. You want your trace output to have the following
characteristics:
v Trace information for each connection on the same DataSource is written to a
separate trace file. Output goes into a directory named /Trace.
v Each trace file name begins with jccTrace1.
v If trace files with the same names already exist, the trace data is appended to
them.
Although Test1.java does not contain any code to do tracing, you want to set the
configuration properties so that if the application is modified in the future to do
tracing, the settings within the program will take precedence over the settings in
the configuration properties. To do that, use the set of configuration properties that
begin with db2.jcc, not db2.jcc.override.
You want the trace settings to apply only to your stand-alone program Test1.java,
so you create a file with these settings, and then refer to the file when you invoke
the Java program by specifying the -Ddb2.jcc.propertiesFile option. Suppose that
the file that contains the settings is /Test/jcc.properties. To enable tracing when
you run Test1.java, you issue a command like this:
java -Ddb2.jcc.propertiesFile=/Test/jcc.properties Test1
Suppose that Test1.java creates two connections for one DataSource. The program
does not define a logWriter object, so the driver creates a global logWriter object
for the trace output. When the program completes, the following files contain the
trace data:
v /Trace/jccTrace1_global_0
v /Trace/jccTrace1_global_1
Example of a trace program under the IBM Data Server Driver for
JDBC and SQLJ
You might want to write a single class that includes methods for tracing under the
DriverManager interface, as well as the DataSource interface.
The following example shows such a class. The example uses IBM Data Server
Driver for JDBC and SQLJ type 4 connectivity.
Figure 48. Example of tracing under the IBM Data Server Driver for JDBC and SQLJ
Chapter 8. Problem diagnosis with the IBM Data Server Driver for JDBC and SQLJ 201
{
sampleConnectUsingSimpleDataSource();
sampleConnectWithURLUsingDriverManager();
}
c.close();
}
catch(java.sql.SQLException e) {
com.ibm.db2.jcc.DB2ExceptionFormatter.printTrace(e,
printWriter, "[TraceExample]");
}
finally {
cleanup(c, printWriter);
printWriter.flush();
}
}
try {
if(c.isClosed()) {
printWriter.println("[TraceExample] " +
"The connection was successfully closed");
return;
}
Chapter 8. Problem diagnosis with the IBM Data Server Driver for JDBC and SQLJ 203
// This time, send the printWriter to a file.
java.io.PrintWriter printWriter = null;
try {
printWriter =
new java.io.PrintWriter(
new java.io.BufferedOutputStream(
new java.io.FileOutputStream("/temp/driverLog.txt"), 4096), true);
}
catch(java.io.FileNotFoundException e) {
java.lang.System.err.println("Unable to establish a print writer for trace");
java.lang.System.err.flush();
return;
}
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
}
catch(ClassNotFoundException e) {
printWriter.println("[TraceExample] " +
"IBM Data Server Driver for JDBC and SQLJ type 4 connectivity " +
"is not in the application classpath. Unable to load driver.");
printWriter.flush();
return;
}
// This URL describes the target data source for Type 4 connectivity.
// The traceLevel property is established through the URL syntax,
// and driver tracing is directed to file "/temp/driverLog.txt"
// The traceLevel property has type int. The constants
// com.ibm.db2.jcc.DB2BaseDataSource.TRACE_DRDA_FLOWS and
// com.ibm.db2.jcc.DB2BaseDataSource.TRACE_CONNECTS represent
// int values. Those constants cannot be used directly in the
// first getConnection parameter. Resolve the constants to their
// int values by assigning them to a variable. Then use the
// variable as the first parameter of the getConnection method.
String databaseURL =
"jdbc:db2://sysmvs1.stl.ibm.com:5021" +
"/sample:traceFile=/temp/driverLog.txt;traceLevel=" +
(com.ibm.db2.jcc.DB2BaseDataSource.TRACE_DRDA_FLOWS |
com.ibm.db2.jcc.DB2BaseDataSource.TRACE_CONNECTS) + ";";
try {
// This connection request is traced using trace level
// TRACE_CONNECTS | TRACE_DRDA_FLOWS
c = java.sql.DriverManager.getConnection(databaseURL, properties);
c.close();
}
catch(java.sql.SQLException e) {
com.ibm.db2.jcc.DB2ExceptionFormatter.printTrace(e, printWriter,
"[TraceExample]");
}
finally {
cleanup(c, printWriter);
printWriter.flush();
}
}
}
Techniques for monitoring IBM Data Server Driver for JDBC and SQLJ
Sysplex support
To monitor IBM Data Server Driver for JDBC and SQLJ Sysplex support, you need
to monitor the global transport objects pool.
You can monitor the global transport objects pool in either of the following ways:
v Using traces that you start by setting IBM Data Server Driver for JDBC and
SQLJ configuration properties
v Using an application programming interface
For example, the following set of configuration property settings cause error
messages and dump pool error messages to be written every 60 seconds to a file
named /home/WAS/logs/srv1/poolstats:
db2.jcc.dumpPool=DUMP_SYSPLEX_MSG|DUMP_POOL_ERROR
db2.jcc.dumpPoolStatisticsOnSchedule=60
db2.jcc.dumpPoolStatisticsOnScheduleFile=/home/WAS/logs/srv1/poolstats
Chapter 8. Problem diagnosis with the IBM Data Server Driver for JDBC and SQLJ 205
boundary. If the Connection object needs a transport object later, and the
original transport object has not been used by any other Connection object, the
Connection object can use that transport object.
hwroc
The number of objects that were reused from the pool.
coc
The number of objects that the IBM Data Server Driver for JDBC and SQLJ
created since the pool was created.
aooc
The number of objects that exceeded the idle time that was specified by
db2.jcc.maxTransportObjectIdleTime and were deleted from the pool.
rmoc
The number of objects that have been deleted from the pool since the pool was
created.
nbr
The number of requests that the IBM Data Server Driver for JDBC and SQLJ
made to the pool that the pool blocked because the pool reached its maximum
capacity. A blocked request might be successful if an object is returned to the
pool before the db2.jcc.maxTransportObjectWaitTime is exceeded and an
exception is thrown.
tbt
The total time in milliseconds for requests that were blocked by the pool. This
time can be much larger than the elapsed execution time of the application if
the application uses multiple threads.
sbt
The shortest time in milliseconds that a thread waited to get a transport object
from the pool. If the time is under one millisecond, the value in this field is
zero.
lbt
The longest time in milliseconds that a thread waited to get a transport object
from the pool.
abt
The average amount of time in milliseconds that threads waited to get a
transport object from the pool. This value is tbt/nbr.
tpo
The number of objects that are currently in the pool.
You can write applications to gather statistics on the global transport objects pool.
Those applications create objects in the DB2PoolMonitor class and invoke methods
to retrieve information about the pool.
For example, the following code creates an object for monitoring the global
transport objects pool:
import com.ibm.db2.jcc.DB2PoolMonitor;
DB2PoolMonitor transportObjectPoolMonitor =
DB2PoolMonitor.getPoolMonitor (DB2PoolMonitor.TRANSPORT_OBJECT);
Chapter 8. Problem diagnosis with the IBM Data Server Driver for JDBC and SQLJ 207
208 Developing Java Applications
Chapter 9. System monitoring for the IBM Data Server Driver
for JDBC and SQLJ
To assist you in monitoring the performance of your applications with the IBM
Data Server Driver for JDBC and SQLJ, the driver provides two methods to collect
information for a connection.
To collect system monitoring data using the DB2SystemMonitor interface: Perform these
basic steps:
1. Invoke the DB2Connection.getDB2SystemMonitor method to create a
DB2SystemMonitor object.
2. Invoke the DB2SystemMonitor.enable method to enable the DB2SystemMonitor
object for the connection.
3. Invoke the DB2SystemMonitor.start method to start system monitoring.
4. When the activity that is to be monitored is complete, invoke
DB2SystemMonitor.stop to stop system monitoring.
5. Invoke the DB2SystemMonitor.getCoreDriverTimeMicros,
DB2SystemMonitor.getNetworkIOTimeMicros,
DB2SystemMonitor.getServerTimeMicros, or
DB2SystemMonitor.getApplicationTimeMillis methods to retrieve the elapsed
time data.
For example, the following code demonstrates how to collect each type of elapsed
time data. The numbers to the right of selected statements correspond to the
previously described steps.
// Create the connection using the IBM Data Server Driver for JDBC and SQLJ
Connection conn = DriverManager.getConnection (url,user,password);
// Commit changes manually
conn.setAutoCommit(false);
System.out.println("**** Created a JDBC connection to the data source");
DB2SystemMonitor systemMonitor = 1
((DB2Connection)conn).getDB2SystemMonitor();
systemMonitor.enable(true); 2
systemMonitor.start(DB2SystemMonitor.RESET_TIMES); 3
Statement stmt = conn.createStatement();
int numUpd = stmt.executeUpdate(
"UPDATE EMPLOYEE SET PHONENO=’4657’ WHERE EMPNO=’000010’");
systemMonitor.stop(); 4
System.out.println("Server elapsed time (microseconds)="
+ systemMonitor.getServerTimeMicros()); 5
System.out.println("Network I/O elapsed time (microseconds)="
+ systemMonitor.getNetworkIOTimeMicros());
System.out.println("Core driver elapsed time (microseconds)="
+ systemMonitor.getCoreDriverTimeMicros());
System.out.println("Application elapsed time (milliseconds)="
+ systemMonitor.getApplicationTimeMillis());
conn.rollback();
stmt.close();
conn.close();
}
// Handle errors
catch(ClassNotFoundException e)
{
System.err.println("Unable to load the driver, " + e);
}
catch(SQLException e)
{
System.out.println("SQLException: " + e);
e.printStackTrace();
}
}
}
Figure 49. Example of using DB2SystemMonitor methods to collect system monitoring data
To collect system monitoring information using the trace method: Start a JDBC trace,
using configuration properties or Connection or DataSource properties. Include
TRACE_SYSTEM_MONITOR when you set the traceLevel property. For example:
String url = "jdbc:db2://sysmvs1.stl.ibm.com:5021/san_jose" +
":traceFile=/u/db2p/jcctrace;" +
"traceLevel=" + com.ibm.db2.jcc.DB2BaseDataSource.TRACE_SYSTEM_MONITOR + ";";
The trace records with system monitor information look similar to this:
IBM Data Server Driver for JDBC and SQLJ remote trace controller
The IBM Data Server Driver for JDBC and SQLJ provides a facility for controlling
IBM Data Server Driver for JDBC and SQLJ traces dynamically.
This remote trace controller lets you perform operations like these for multiple
driver instances:
v Start, stop, or resume a trace
v Change the output trace file or directory location
v Change the trace level
The remote trace controller uses the Java Management Extensions (JMX)
architecture, which is part of the Java Standard Edition, Version 6, or later. The
JMX consists of:
v A set of built-in management utilities, which let you do monitoring from a
management console such as the Java Monitoring and Management Console
(JConsole).
v A set of APIs that let you write applications to perform the same functions.
The remote trace controller requires Java Standard Edition, Version 6 or later.
Chapter 9. System monitoring for the IBM Data Server Driver for JDBC and SQLJ 211
– Write a JMX agent. This technique is also discussed at:
http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html
In the following example, an RMI connector server is created for the
PlatformMBeanServer using the MyCustomJMXAuthenticator object. The
MyCustomJMXAuthenticator class defines how remote credentials are
converted into a JAAS Subject by implementing the JMXAuthenticator
interface:
...
HashMap<String> env = new HashMap<String>();
env.put(JMXConnectorServer.AUTHENTICATOR, new MyCustomJMXAuthenticator());
env.put("jmx.remote.x.access.file", "my.access.file");
MBeanServer mbs =
java.lang.management.ManagementFactory.getPlatformMBeanServer();
JMXServiceURL url =
new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
cs.start();
...
public class MyCustomJMXAuthenticator implements JMXAuthenticator {
...
// Authenticate using the provided credentials
...
if (authentication-successful) {
return new Subject(true,
Collections.singleton
(new JMXPrincipal(credentialsHash.get("username"))),
Collections.EMPTY_SET,
Collections.EMPTY_SET);
}
throw new SecurityException("Invalid credentials");
}
}
In an application that accesses the remote trace controller, the remote trace
controller is a managed bean (MBean). JMX manages resources through JMX
agents. A JMX agent is an MBean server. Each MBean represents a resource. Every
MBean has a name, which you define through an object of class
javax.management.ObjectName. You use the ObjectName object to register and
retrieve MBeans in the MBeanServer.
An application that accesses the remote trace controller must include these steps:
1. Establish a Remote Method Invocation (RMI) connection to an MBean server.
2. Perform a lookup on the remote trace controller in the MBean server.
3. Invoke trace operations on the MBean.
You can operate on the MBean in the following ways:
v Using an MBean proxy
v Without a proxy, through an MBeanServerConnection.
Example: accessing the remote trace controller without proxies: This example
demonstrates accessing MBeans directly from an MBeanServerConnection. This
method is the most generic because it does not require matching interface
definitions on the JMX client application.
Hashtable<String> env = new Hashtable<String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
try {
System.out.println ("");
System.out.println ("-------------------------------------------------");
System.out.println ("Establish an RMI connection to an MBeanServer");
System.out.println ("-------------------------------------------------");
JMXServiceURL url =
new JMXServiceURL ("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect (url, env);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
System.out.println ("");
System.out.println ("-------------------------------------------------");
System.out.println ("Processing MBean");
System.out.println ("-------------------------------------------------");
String objectNameString = "com.ibm.db2.jcc:name=DB2TraceManager";
ObjectName name = new ObjectName(objectNameString);
System.out.println ("ObjectName="+objectNameString);
System.out.println ("");
System.out.println ("-------------------------------------------------");
System.out.println ("Print all attributes of the MBean");
System.out.println ("-------------------------------------------------");
System.out.println(
"TraceDirectory = "+mbsc.getAttribute (name, "TraceDirectory"));
System.out.println(
"TraceFile = "+mbsc.getAttribute (name, "TraceFile"));
System.out.println(
"TraceFileAppend = "+mbsc.getAttribute (name, "TraceFileAppend"));
System.out.println(
"TraceLevel = "+mbsc.getAttribute (name, "TraceLevel"));
System.out.println ("");
System.out.println ("-------------------------------------------------");
System.out.println ("Invoke some operations on the MBean");
System.out.println ("-------------------------------------------------");
System.out.print ("Invoking suspendTrace()...");
mbsc.invoke (name, "suspendTrace", null , null);
System.out.println ("success");
Chapter 9. System monitoring for the IBM Data Server Driver for JDBC and SQLJ 213
mbsc.invoke (name, "resumeTrace", null , null);
System.out.println ("success");
}
catch (Exception e) {
System.out.println ("failure");
e.printStackTrace ();
}
Example: accessing the remote trace controller with proxies: This example
demonstrates the creation of a proxy to an MBean. The proxy implements the
com.ibm.db2.jcc.mx.DB2TraceManagerMXBean interface. The application makes
calls directly on the proxy, and the underlying proxy implementation invokes the
MBean operation on the remote MBean server.
Hashtable<String> env = new Hashtable<String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
try {
System.out.println ("");
System.out.println ("-------------------------------------------------");
System.out.println ("Establish an RMI connection to an MBeanServer");
System.out.println ("-------------------------------------------------");
JMXServiceURL url =
new JMXServiceURL ("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect (url, env);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
System.out.println ("");
System.out.println ("-------------------------------------------------");
System.out.println ("Processing MBean");
System.out.println ("-------------------------------------------------");
String objectNameString = "com.ibm.db2.jcc:name=DB2TraceManager";
ObjectName name = new ObjectName(objectNameString);
System.out.println ("ObjectName="+objectNameString);
System.out.println ("");
System.out.println ("-------------------------------------------------");
System.out.println ("Print all attributes of the MBean");
System.out.println ("-------------------------------------------------");
com.ibm.db2.jcc.mx.DB2TraceManagerMXBean mbeanProxy =
JMX.newMBeanProxy(mbsc, name,
com.ibm.db2.jcc.mx.DB2TraceManagerMXBean.class, true);
System.out.println ("TraceDirectory = "+mbeanProxy.getTraceDirectory ());
System.out.println ("TraceFile = "+mbeanProxy.getTraceFile ());
System.out.println ("TraceFileAppend = "+mbeanProxy.getTraceFileAppend ());
System.out.println ("TraceLevel = "+mbeanProxy.getTraceLevel ());
System.out.println ("");
System.out.println ("-------------------------------------------------");
System.out.println ("Invoke some operations on the MBean");
System.out.println ("-------------------------------------------------");
System.out.print ("Invoking suspendTrace()...");
mbeanProxy.suspendTrace();
System.out.println ("success");
System.out.print ("Invoking resumeTrace()...");
mbeanProxy.resumeTrace();
System.out.println ("success");
}
catch (Exception e) {
System.out.println ("failure");
e.printStackTrace ();
}
The following table provides links to server-side information about these features.
Table 34. Server-side information on high availability
Data server Related topics
DB2 Database for Linux, UNIX, and Windows v Automatic client reroute: Automatic client reroute
roadmap
IDS Manage Cluster Connections with the Connection
Manager
DB2 for z/OS Communicating with data sharing groups
Important: For connections to DB2 for z/OS, this information discusses direct
connections to DB2 for z/OS. For information about high availability for
connections through DB2 Connect Server, see the DB2 Connect documentation.
For Java clients, you need to use IBM Data Server Driver for JDBC and SQLJ type
4 connectivity to take advantage of DB2 Database for Linux, UNIX, and Windows
high-availability support. You need IBM Data Server Driver for JDBC and SQLJ
version 3.58 or 4.8, or later.
High availability support for connections to DB2 Database for Linux, UNIX, and
Windows servers includes:
Automatic client reroute
This support enables a client to recover from a failure by attempting to
reconnect to the database through an alternate server. Reconnection to another
server is called failover. For Java clients, automatic client reroute support is
always enabled.
Automatic client reroute capability is available for a database that is defined on
a single server. The configuration for that database includes specification of an
alternate server. Failover involves reconnection to the alternate server.
For Java, client applications, failover for automatic client reroute can be
seamless or non-seamless. With non-seamless failover, when the client application
reconnects to another server, an error is always returned to the application, to
indicate that failover (connection to the alternate server) occurred. With
seamless failover, the driver does not return an error if a connection failure and
successful reconnection to an alternate server occur during execution of the
first SQL statement in a transaction.
In a DB2 pureScale™ instance, automatic client reroute support can be used
without workload balancing or with workload balancing.
Client affinities
Client affinities is an automatic client reroute solution that is controlled
completely by the client. It is intended for situations in which you need to
connect to a particular primary server. If an outage occurs during the
connection to the primary server, you use client affinities to enforce a specific
order for failover to alternate servers.
Automatic client reroute support for Java client applications that connect to DB2
Database for Linux, UNIX, and Windows works for connections that are obtained
using the javax.sql.DataSource, javax.sql.ConnectionPoolDataSource,
javax.sql.XADataSource, or java.sql.DriverManager interface.
Restriction: Automatic client reroute support for connections that are made
with the DriverManager interface has the following restrictions:
– Alternate server information is shared between DriverManager
connections only if you create the connections with the same URL and
properties.
– You cannot set the clientRerouteServerListJNDIName property or the
clientRerouteServerListJNDIContext properties for a DriverManager
connection.
– Automatic client reroute is not enabled for default connections
(jdbc:default:connection).
v If your application is using the DataSource interface for connections, use one
or both of the following techniques:
– Set the server names and port numbers in DataSource properties:
a. Set the serverName and portNumber properties to the server name
and port number of the primary server that you want to use.
b. Set the clientRerouteAlternateServerName and
clientRerouteAlternatePortNumber properties to the server name and
port number of the alternate server that you want to use.
– Configure JNDI for automatic client reroute by using a
DB2ClientRerouteServerList instance to identify the primary server and
alternate server.
a. Create an instance of DB2ClientRerouteServerList.
DB2ClientRerouteServerList is a serializable Java bean with the
following properties:
Chapter 10. Java client support for high availability on IBM data servers 217
com.ibm.db2.jcc.DB2ClientRerouteServerList.alternatePortNumber
properties to the server names and port numbers of the alternate
server that you want to use.
d. To make the DB2ClientRerouteServerList persistent:
1) Bind the DB2ClientRerouteServerList instance to the JNDI registry.
2) Assign the JNDI name of the DB2ClientRerouteServerList object to
the IBM Data Server Driver for JDBC and SQLJ
clientRerouteServerListJNDIName property.
3) Assign the name of the JNDI context that is used for binding and
lookup of the DB2ClientRerouteServerList instance to the
clientRerouteServerListJNDIContext property.
When a DataSource is configured to use JNDI for storing automatic client
reroute alternate information, the standard server and port properties of
the DataSource are not used for a getConnection request. Instead, the
primary server address is obtained from the transient
clientRerouteServerList information. If the JNDI store is not available due
to a JNDI bind or lookup failure, the IBM Data Server Driver for JDBC
and SQLJ attempts to make a connection using the standard server and
port properties of the DataSource. Warnings are accumulated to indicate
that a JNDI bind or lookup failure occurred.
After a failover:
- The IBM Data Server Driver for JDBC and SQLJ attempts to propagate
the updated server information to the JNDI store.
- primaryServerName and primaryPortNumber values that are specified
in DB2ClientRerouteServerList are used for the connection. If
primaryServerName is not specified, the serverName and portNumber
values for the DataSource instance are used.
If you configure DataSource properties as well as configuring JNDI for
automatic client reroute, the DataSource properties have precedence over the
JNDI configuration.
2. Set properties to control the number of retries, time between retries, and the
frequency with which the server list is refreshed.
The following properties control retry behavior for automatic client reroute.
maxRetriesForClientReroute
The maximum number of connection retries for automatic client reroute.
When client affinities support is not configured, if
maxRetriesForClientReroute or retryIntervalForClientReroute is not set, the
default behavior is that the connection is retried for 10 minutes, with a wait
time between retries that increases as the length of time from the first retry
increases.
When client affinities is configured, the default for
maxRetriesForClientReroute is 3.
retryIntervalForClientReroute
The number of seconds between consecutive connection retries.
When client affinities support is not configured, if
retryIntervalForClientReroute or maxRetriesForClientReroute is not set, the
default behavior is that the connection is retried for 10 minutes, with a wait
time between retries that increases as the length of time from the first retry
increases.
The following example demonstrates setting up Java client applications for DB2
Database for Linux, UNIX, and Windows automatic client reroute support.
Suppose that your installation has a primary server and an alternate server with
the following server names and port numbers:
The following code configures JNDI for automatic client reroute. It creates an
instance of DB2ClientRerouteServerList, binds that instance to the JNDI registry,
and assigns the JNDI name of the DB2ClientRerouteServerList object to the
clientRerouteServerListJNDIName property.
// Create a starting context for naming operations
InitialContext registry = new InitialContext();
// Create a DB2ClientRerouteServerList object
DB2ClientRerouteServerList address = new DB2ClientRerouteServerList();
// Set the port number and server name for the primary server
address.setPrimaryPortNumber(50000);
address.setPrimaryServerName("srv1.sj.ibm.com");
// Set the port number and server name for the alternate server
int[] port = {50002};
String[] server = {"srv3.sj.ibm.com"};
address.setAlternatePortNumber(port);
address.setAlternateServerName(server);
registry.rebind("serverList", address);
// Assign the JNDI name of the DB2ClientRerouteServerList object to the
// clientRerouteServerListJNDIName property
datasource.setClientRerouteServerListJNDIName("serverList");
Chapter 10. Java client support for high availability on IBM data servers 219
Operation of automatic client reroute for connections to DB2
Database for Linux, UNIX, and Windows from Java clients
When IBM Data Server Driver for JDBC and SQLJ client reroute support is
enabled, a Java application that is connected to a DB2 Database for Linux, UNIX,
and Windows database can continue to run when the primary server has a failure.
Automatic client reroute for a Java application that is connected to a DB2 Database
for Linux, UNIX, and Windows database operates in the following way when
support for client affinities is disabled:
1. During each connection to the data source, the IBM Data Server Driver for
JDBC and SQLJ obtains primary and alternate server information.
v For the first connection to a DB2 Database for Linux, UNIX, and Windows
database:
a. If the clientRerouteAlternateServerName and
clientRerouteAlternatePortNumber properties are set, the IBM Data
Server Driver for JDBC and SQLJ loads those values into memory as the
alternate server values, along with the primary server values serverName
and portNumber.
b. If the clientRerouteAlternateServerName and
clientRerouteAlternatePortNumber properties are not set, and a JNDI
store is configured by setting the property
clientRerouteServerListJNDIName on the DB2BaseDataSource, the IBM
Data Server Driver for JDBC and SQLJ loads the primary and alternate
server information from the JNDI store into memory.
c. If no DataSource properties are set for the alternate servers, and JNDI is
not configured, the IBM Data Server Driver for JDBC and SQLJ checks
DNS tables for primary and alternate server information. If DNS
information exists, the IBM Data Server Driver for JDBC and SQLJ loads
those values into memory.
d. If no primary or alternate server information is available, a connection
cannot be established, and the IBM Data Server Driver for JDBC and
SQLJ throws an exception.
v For subsequent connections, the IBM Data Server Driver for JDBC and SQLJ
obtains primary and alternate server values from driver memory.
2. The IBM Data Server Driver for JDBC and SQLJ attempts to connect to the data
source using the primary server name and port number.
If the connection is through the DriverManager interface, the IBM Data Server
Driver for JDBC and SQLJ creates an internal DataSource object for automatic
client reroute processing.
3. If the connection to the primary server fails:
a. If this is the first connection, the IBM Data Server Driver for JDBC and
SQLJ attempts to reconnect to a server using information that is provided
by driver properties such as clientRerouteAlternateServerName and
clientRerouteAlternatePortNumber.
b. If this is not the first connection, the IBM Data Server Driver for JDBC and
SQLJ attempts to make a connection using the information from the latest
server list that is returned from the server.
Connection to an alternate server is called failover.
The IBM Data Server Driver for JDBC and SQLJ uses the
maxRetriesForClientReroute and retryIntervalForClientReroute properties to
Examples
Example: Automatic client reroute to a DB2 Database for Linux, UNIX, and Windows
server when maxRetriesForClientReroute and retryIntervalForClientReroute are not set:
Suppose that the following properties are set for a connection to a database:
Property Value
enableClientAffinitiesList DB2BaseDataSource.NO (2)
serverName host1
portNumber port1
clientRerouteAlternateServerName host2
clientRerouteAlternatePortNumber port2
Chapter 10. Java client support for high availability on IBM data servers 221
2. On the initial connection, the driver tries to connect to host1:port1.
3. The connection to host1:port1 fails, so the driver tries another connection to
host1:port1.
4. The reconnection to host1:port1 fails, so the driver tries to connect to
host2:port2.
5. The connection to host2:port2 succeeds.
6. The driver retrieves alternate server information that was received from server
host2:port2, and updates its memory with that information.
Assume that the driver receives a server list that contains host2:port2,
host2a:port2a. host2:port2 is stored as the new primary server, and
host2a:port2a is stored as the new alternate server. If another communication
failure is detected on this same connection, or on another connection that is
created from the same DataSource, the driver tries to connect to host2:port2 as
the new primary server. If that connection fails, the driver tries to connect to
the new alternate server host2a:port2a.
7. A communication failure occurs during the connection to host2:port2.
8. The driver tries to connect to host2a:port2a.
9. The connection to host2a:port2a is successful.
10. The driver retrieves alternate server information that was received from server
host2a:port2a, and updates its memory with that information.
Example: Automatic client reroute to a DB2 Database for Linux, UNIX, and Windows
server when maxRetriesForClientReroute and retryIntervalForClientReroute are set for
multiple retries: Suppose that the following properties are set for a connection to a
database:
Property Value
enableClientAffinitiesList DB2BaseDataSource.NO (2)
serverName host1
portNumber port1
clientRerouteAlternateServerName host2
clientRerouteAlternatePortNumber port2
maxRetriesForClientReroute 3
retryIntervalForClientReroute 2
The following conditions must be satisfied for failover for connections to DB2
Database for Linux, UNIX, and Windows to be seamless:
v The application programming language is Java, CLI, or .NET.
v The connection is not in a transaction. That is, the failure occurs when the first
SQL statement in the transaction is executed.
v All global session data is closed or dropped.
v There are no open, held cursors.
v If the application uses CLI, the application cannot perform actions that require
the driver to maintain a history of previously called APIs in order to replay the
SQL statement. Examples of such actions are specifying data at execution time,
performing compound SQL, or using array input.
v The application is not a stored procedure.
v Autocommit is not enabled. Seamless failover can occur when autocommit is
enabled. However, the following situation can cause problems: Suppose that
SQL work is successfully executed and committed at the data server, but the
connection or server goes down before acknowledgment of the commit
operation is sent back to the client. When the client re-establishes the connection,
it replays the previously committed SQL statement. The result is that the SQL
statement is executed twice. To avoid this situation, turn autocommit off when
you enable seamless failover.
Chapter 10. Java client support for high availability on IBM data servers 223
Client affinities is available for applications that use CLI, .NET, or Java (IBM Data
Server Driver for JDBC and SQLJ type 4 connectivity). All rerouting is controlled
by the driver.
Failover with client affinities is seamless, if the following conditions are true:
v The connection is not in a transaction. That is, the failure occurs when the first
SQL statement in the transaction is executed.
v There are no global temporary tables in use on the server.
v There are no open, held cursors.
When you use client affinities, you can specify that if the primary server returns to
operation after an outage, connections return from an alternate server to the
primary server on a transaction boundary. This activity is known as failback.
The following table describes the property settings for enabling client affinities for
Java applications.
Table 35. Property settings to enable client affinities for Java applications
IBM Data Server Driver for JDBC and SQLJ
setting Value
enableClientAffinitiesList DB2BaseDataSource.YES (1)
clientRerouteAlternateServerName A comma-separated list of the primary server
and alternate servers
clientRerouteAlternatePortNumber A comma-separated list of the port numbers
for the primary server and alternate servers
enableSeamlessFailover DB2BaseDataSource.YES (1) for seamless
failover; DB2BaseDataSource.NO (2) or
enableSeamlessFailover not specified for no
seamless failover
maxRetriesForClientReroute The number of times to retry the connection
to each server, including the primary server,
after a connection to the primary server fails.
The default is 3.
The following example shows how to enable client affinities for failover without
failback.
Suppose that you set the following properties for a connection to a database:
Property Value
enableClientAffinitiesList DB2BaseDataSource.YES (1)
clientRerouteAlternateServername host1,host2,host3
clientRerouteAlternatePortNumber port1,port2,port3
maxRetriesForClientReroute 3
retryIntervalForClientReroute 2
Suppose that a communication failure occurs during a connection to the server that
is identified by host1:port1. The following steps demonstrate automatic client
reroute with client affinities.
1. The driver tries to connect to host1:port1.
2. The connection to host1:port1 fails.
3. The driver waits two seconds.
4. The driver tries to connect to host1:port1.
5. The connection to host1:port1 fails.
6. The driver waits two seconds.
7. The driver tries to connect to host1:port1.
8. The connection to host1:port1 fails.
9. The driver waits two seconds.
10. The driver tries to connect to host2:port2.
11. The connection to host2:port2 fails.
12. The driver waits two seconds.
13. The driver tries to connect to host2:port2.
14. The connection to host2:port2 fails.
15. The driver waits two seconds.
16. The driver tries to connect to host2:port2.
17. The connection to host2:port2 fails.
Chapter 10. Java client support for high availability on IBM data servers 225
18. The driver waits two seconds.
19. The driver tries to connect to host3:port3.
20. The connection to host3:port3 fails.
21. The driver waits two seconds.
22. The driver tries to connect to host3:port3.
23. The connection to host3:port3 fails.
24. The driver waits two seconds.
25. The driver tries to connect to host3:port3.
26. The connection to host3:port3 fails.
27. The driver waits two seconds.
28. The driver throws an SQLException with error code -4499.
The following example shows how to enable client affinities for failover with
failback.
Suppose that you set the following properties for a connection to a database:
Property Value
enableClientAffinitiesList DB2BaseDataSource.YES (1)
clientRerouteAlternateServername host1,host2,host3
clientRerouteAlternatePortNumber port1,port2,port3
maxRetriesForClientReroute 3
retryIntervalForClientReroute 2
affinityFailbackInterval 300
Suppose that the database administrator takes the server that is identified by
host1:port1 down for maintenance after a connection is made to host1:port1. The
following steps demonstrate failover to an alternate server and failback to the
primary server after maintenance is complete.
1. The driver successfully connects to host1:port1 on behalf of an application.
2. The database administrator brings down host1:port1.
3. The application tries to do work on the connection.
4. The driver successfully fails over to host2:port2.
5. After a total of 200 seconds have elapsed, the work is committed.
6. After a total of 300 seconds have elapsed, the failback interval has elasped.
The driver checks whether the primary server is up. It is not up, so no
failback occurs.
7. After a total of 350 seconds have elapsed, host1:port1 is brought back online.
8. The application continues to do work on host2:port2, because the latest
failback interval has not elapsed.
9. After a total of 600 seconds have elapsed, the failback interval has elapsed
again. The driver checks whether the primary server is up. It is now up.
10. After a total of 650 seconds have elapsed, the work is committed.
11. After a total of 651 seconds have elapsed, the application tries to start a new
transaction on host2:port2. Failback to host1:port1 occurs, so the new
transaction starts on host1:port1.
For Java clients, you need to use IBM Data Server Driver for JDBC and SQLJ type
4 connectivity to take advantage of IDS high-availability cluster support.
For non-Java clients, you need to use one of the following clients or client
packages to take advantage of high-availability cluster support:
v IBM Data Server Client
v IBM Data Server Runtime Client
v IBM Data Server Driver Package
v IBM Data Server Driver for ODBC and CLI
Cluster support for high availability for connections to IDS servers includes:
Automatic client reroute
This support enables a client to recover from a failure by attempting to
reconnect to the database through any available server in a high-availability
cluster. Reconnection to another server is called failover. You enable automatic
client reroute on the client by enabling workload balancing on the client.
In an IDS environment, primary and standby servers correspond to members
of a high-availability cluster that is controlled by a Connection Manager. If
multiple Connection Managers exist, the client can use them to determine
primary and alternate server information. The client uses alternate Connection
Managers only for the initial connection.
Failover for automatic client reroute can be seamless or non-seamless. With
non-seamless failover, when the client application reconnects to an alternate
server, the server always returns an error to the application, to indicate that
failover (connection to the alternate server) occurred.
For Java, CLI, or .NET client applications, failover for automatic client reroute
can be seamless or non-seamless. Seamless failover means that when the
application successfully reconnects to an alternate server, the server does not
return an error to the application.
Workload balancing
Workload balancing can improve availability of an IDS high-availability cluster.
When workload balancing is enabled, the client gets frequent status
information about the members of a high-availability cluster. The client uses
this information to determine the server to which the next transaction should
be routed. With workload balancing, IDS Connection Managers ensure that
work is distributed efficiently among servers and that work is transferred to
another server if a server has a failure.
Connection concentrator
This support is available for Java applications that connect to IDS. The
connection concentrator reduces the resources that are required on IDS
database servers to support large numbers of workstation and web users. With
the connection concentrator, only a few concurrent, active physical connections
are needed to support many applications that concurrently access the database
Chapter 10. Java client support for high availability on IBM data servers 227
server. When you enable workload balancing on a Java client, you
automatically enable the connection concentrator.
Client affinities
Client affinities is an automatic client reroute solution that is controlled
completely by the client. It is intended for situations in which you need to
connect to a particular primary server. If an outage occurs during the
connection to the primary server, you use client affinities to enforce a specific
order for failover to alternate servers.
High availability support for Java clients that connect to IBM Informix works for
connections that are obtained using the javax.sql.DataSource,
javax.sql.ConnectionPoolDataSource, javax.sql.XADataSource, or
java.sql.DriverManager interface.
Restriction: High availability support for connections that are made with the
DriverManager interface has the following restrictions:
v Alternate server information is shared between DriverManager connections only
if you create the connections with the same URL and properties.
v You cannot set the clientRerouteServerListJNDIName property or the
clientRerouteServerListJNDIContext properties for a DriverManager connection.
v High availability support is not enabled for default connections
(jdbc:default:connection).
Before you can enable IBM Data Server Driver for JDBC and SQLJ for high
availability for connections to IBM Informix, your installation must have one or
more Connection Managers, a primary server, and one or more alternate servers.
The following table describes the basic property settings for enabling workload
balancing for Java applications.
Table 36. Basic settings to enable IDS high availability support in Java applications
IBM Data Server Driver for JDBC and SQLJ
setting Value
enableSysplexWLB property true
maxTransportObjects property The maximum number of connections that
the requester can make to the
high-availability cluster
Connection address:
server The IP address of a Connection Manager. See
“Setting server and port properties for
connecting to a Connection Manager” on
page 229.
port The SQL port number for the Connection
Manager. See “Setting server and port
properties for connecting to a Connection
Manager” on page 229.
database The database name
To set the server and port number for connecting to a Connection Manager, follow
this process:
v If your high-availability cluster is using a single Connection Manager, and your
application is using the DataSource interface for connections, set the serverName
and portNumber properties to the server name and port number of the
Connection Manager.
v If your high-availability cluster is using a single Connection Manager, and your
application is using the DriverManager interface for connections, specify the
server name and port number of the Connection manager in the connection
URL.
v If your high-availability cluster is using more than one Connection manager, and
your application is using the DriverManager interface for connections:
1. Specify the server name and port number of the main Connection Manager
that you want to use in the connection URL.
2. Set the clientRerouteAlternateServerName and
clientRerouteAlternatePortNumber properties to the server names and port
numbers of the alternative Connection Managers that you want to use.
Chapter 10. Java client support for high availability on IBM data servers 229
v If your high-availability cluster is using more than one Connection Manager, and
your application is using the DataSource interface for connections, use one of the
following techniques:
– Set the server names and port numbers in DataSource properties:
1. Set the serverName and portNumber properties to the server name and
port number of the main Connection Manager that you want to use.
2. Set the clientRerouteAlternateServerName and
clientRerouteAlternatePortNumber properties to the server names and
port numbers of the alternative Connection Managers that you want to
use.
– Configure JNDI for high availability by using a DB2ClientRerouteServerList
instance to identify the main Connection Manager and alternative Connection
Managers.
1. Create an instance of DB2ClientRerouteServerList.
DB2ClientRerouteServerList is a serializable Java bean with the following
properties:
The following example demonstrates setting up Java client applications for IDS
high availability support.
Before you can set up the client, you need to configure one or more high
availability clusters that are controlled by Connection Managers.
2. Set IBM Data Server Driver for JDBC and SQLJ Connection or DataSource
properties to enable workload balancing:
v enableSysplexWLB
v maxTransportObjects
v maxRefreshInterval
Start with settings similar to these:
Table 39. Example of Connection or DataSource property settings for workload balancing for
IDS
Property Setting
enableSysplexWLB true
maxTransportObjects 80
maxRefreshInterval 30
Chapter 10. Java client support for high availability on IBM data servers 231
v db2.jcc.maxTransportObjects
Start with a setting similar to this one:
db2.jcc.maxTransportObjects=500
c. Include the directory that contains DB2JccConfiguration.properties in the
CLASSPATH concatenation.
Automatic client reroute for a Java application that is connected to an IDS server
operates in the following way when automatic client reroute is enaabled:
1. During each connection to the data source, the IBM Data Server Driver for
JDBC and SQLJ obtains primary and alternate server information.
v For the first connection to IDS:
a. The application specifies a server and port for the initial connection.
Those values identify a Connection Manager.
b. The IBM Data Server Driver for JDBC and SQLJ uses the information
from the Connection Manager to obtain information about the primary
and alternate servers. IBM Data Server Driver for JDBC and SQLJ loads
those values into memory.
c. If the initial connection to the Connection Manager fails:
– If the clientRerouteAlternateServerName and
clientRerouteAlternatePortNumber properties are set, the IBM Data
Server Driver for JDBC and SQLJ connects to the Connection Manager
that is identified by clientRerouteAlternateServerName and
clientRerouteAlternatePortNumber, and obtains information about
primary and alternate servers from that Connection Manager. The IBM
Data Server Driver for JDBC and SQLJ loads those values into memory
as the primary and alternate server values.
– If the clientRerouteAlternateServerName and
clientRerouteAlternatePortNumber properties are not set, and a JNDI
store is configured by setting the property
clientRerouteServerListJNDIName on the DB2BaseDataSource, the IBM
Data Server Driver for JDBC and SQLJ connects to the Connection
Manager that is identified by
DB2ClientRerouteServerList.alternateServerName and
DB2ClientRerouteServerList.alternatePortNumber, and obtains
information about primary and alternate servers from that Connection
Manager. IBM Data Server Driver for JDBC and SQLJ loads the
primary and alternate server information from the Connection
Manager into memory.
d. If clientRerouteAlternateServerName and
clientRerouteAlternatePortNumber are not set, and JNDI is not
configured, the IBM Data Server Driver for JDBC and SQLJ checks DNS
tables for Connection Manager server and port information. If DNS
information exists, the IBM Data Server Driver for JDBC and SQLJ
connects to the Connection Manager, obtains information about primary
and alternate servers, and loads those values into memory.
Chapter 10. Java client support for high availability on IBM data servers 233
A reason code that is returned with error code -4498 indicates whether any
database server special registers that were modified during the original
connection are reestablished in the failover connection.
You can determine whether alternate server information was used in
establishing the initial connection by calling the
DB2Connection.alternateWasUsedOnConnect method.
6. After failover, driver memory is updated with new primary and alternate
server information from the new primary server.
Examples
Property Value
enableClientAffinitiesList DB2BaseDataSource.NO (2)
serverName host1
portNumber port1
clientRerouteAlternateServerName host2
clientRerouteAlternatePortNumber port2
The following overview describes the steps that occur when a client connects to an
IDS Connection Manager, and workload balancing is enabled:
Chapter 10. Java client support for high availability on IBM data servers 235
1. When the client first establishes a connection using the IP address of the
Connection Manager, the Connection Manager returns the server list and the
connection details (IP address, port, and weight) for the servers in the cluster.
The server list is cached by the client. The default lifespan of the cached server
list is 30 seconds.
2. At the start of a new transaction, the client reads the cached server list to
identify a server that has untapped capacity, and looks in the transport pool for
an idle transport that is tied to the under-utilized server. (An idle transport is a
transport that has no associated connection object.)
v If an idle transport is available, the client associates the connection object
with the transport.
v If, after a user-configurable timeout, no idle transport is available in the
transport pool and no new transport can be allocated because the transport
pool has reached its limit, an error is returned to the application.
3. When the transaction runs, it accesses the server that is tied to the transport.
4. When the transaction ends, the client verifies with the server that transport
reuse is still allowed for the connection object.
5. If transport reuse is allowed, the server returns a list of SET statements for
special registers that apply to the execution environment for the connection
object.
The client caches these statements, which it replays in order to reconstruct the
execution environment when the connection object is associated with a new
transport.
6. The connection object is then dissociated from the transport, if the client
determines that it needs to do so.
7. The client copy of the server list is refreshed when a new connection is made,
or every 30 seconds, or at the user-configured interval.
8. When workload balancing is required for a new transaction, the client uses the
previously described process to associate the connection object with a transport.
The following conditions must be satisfied for seamless failover to occur during
connections to IDS databases:
v The application programming language is Java, CLI, or .NET.
v The connection is not in a transaction. That is, the failure occurs when the first
SQL statement in the transaction is executed.
Client affinities is available for applications that use CLI, .NET, or Java (IBM Data
Server Driver for JDBC and SQLJ type 4 connectivity). All rerouting is controlled
by the driver.
Failover with client affinities is seamless, if the following conditions are true:
v The connection is not in a transaction. That is, the failure occurs when the first
SQL statement in the transaction is executed.
v There are no global temporary tables in use on the server.
v There are no open, held cursors.
When you use client affinities, you can specify that if the primary server returns to
operation after an outage, connections return from an alternate server to the
primary server on a transaction boundary. This activity is known as failback.
Chapter 10. Java client support for high availability on IBM data servers 237
Configuration of client affinities for Java clients for IDS
connections
To enable support for client affinities in Java applications, you set properties to
indicate that you want to use client affinities, and to specify the primary and
alternate servers.
The following table describes the property settings for enabling client affinities for
Java applications.
Table 40. Property settings to enable client affinities for Java applications
IBM Data Server Driver for JDBC and SQLJ
setting Value
enableClientAffinitiesList DB2BaseDataSource.YES (1)
clientRerouteAlternateServerName A comma-separated list of the primary server
and alternate servers
clientRerouteAlternatePortNumber A comma-separated list of the port numbers
for the primary server and alternate servers
enableSeamlessFailover DB2BaseDataSource.YES (1) for seamless
failover; DB2BaseDataSource.NO (2) or
enableSeamlessFailover not specified for no
seamless failover
maxRetriesForClientReroute The number of times to retry the connection
to each server, including the primary server,
after a connection to the primary server fails.
The default is 3.
retryIntervalForClientReroute The number of seconds to wait between
retries. The default is no wait.
affinityFailbackInterval The number of seconds to wait after the first
transaction boundary to fail back to the
primary server. Set this value if you want to
fail back to the primary server.
The following example shows how to enable client affinities for failover without
failback.
Suppose that you set the following properties for a connection to a database:
Property Value
enableClientAffinitiesList DB2BaseDataSource.YES (1)
clientRerouteAlternateServername host1,host2,host3
clientRerouteAlternatePortNumber port1,port2,port3
maxRetriesForClientReroute 3
retryIntervalForClientReroute 2
The following example shows how to enable client affinities for failover with
failback.
Suppose that you set the following properties for a connection to a database:
Property Value
enableClientAffinitiesList DB2BaseDataSource.YES (1)
clientRerouteAlternateServername host1,host2,host3
clientRerouteAlternatePortNumber port1,port2,port3
maxRetriesForClientReroute 3
retryIntervalForClientReroute 2
affinityFailbackInterval 300
Chapter 10. Java client support for high availability on IBM data servers 239
Suppose that the database administrator takes the server that is identified by
host1:port1 down for maintenance after a connection is made to host1:port1. The
following steps demonstrate failover to an alternate server and failback to the
primary server after maintenance is complete.
1. The driver successfully connects to host1:port1 on behalf of an application.
2. The database administrator brings down host1:port1.
3. The application tries to do work on the connection.
4. The driver successfully fails over to host2:port2.
5. After a total of 200 seconds have elapsed, the work is committed.
6. After a total of 300 seconds have elapsed, the failback interval has elasped.
The driver checks whether the primary server is up. It is not up, so no
failback occurs.
7. After a total of 350 seconds have elapsed, host1:port1 is brought back online.
8. The application continues to do work on host2:port2, because the latest
failback interval has not elapsed.
9. After a total of 600 seconds have elapsed, the failback interval has elapsed
again. The driver checks whether the primary server is up. It is now up.
10. After a total of 650 seconds have elapsed, the work is committed.
11. After a total of 651 seconds have elapsed, the application tries to start a new
transaction on host2:port2. Failback to host1:port1 occurs, so the new
transaction starts on host1:port1.
Java client support for high availability for connections to DB2 for
z/OS servers
Sysplex workload balancing functionality on DB2 for z/OS servers provides high
availability for client applications that connect directly to a data sharing group.
Sysplex workload balancing functionality provides workload balancing and
automatic client reroute capability. This support is available for applications that
use Java clients (JDBC, SQLJ, or pureQuery) that use IBM Data Server Driver for
JDBC and SQLJ type 4 connectivity, or non-Java clients (ODBC, CLI, .NET, OLE
DB, PHP, Ruby, or embedded SQL). Workload balancing is transparent to
applications.
A Sysplex is a set of z/OS systems that communicate and cooperate with each
other through certain multisystem hardware components and software services to
process customer workloads. DB2 for z/OS subsystems on the z/OS systems in a
Sysplex can be configured to form a data sharing group. With data sharing,
applications that run on more than one DB2 for z/OS subsystem can read from
and write to the same set of data concurrently. One or more coupling facilities
provide high-speed caching and lock processing for the data sharing group. The
Sysplex, together with the Workload Manager (WLM), dynamic virtual IP address
(DVIPA), and the Sysplex Distributor, allow a client to access a DB2 for z/OS
database over TCP/IP with network resilience, and distribute transactions for an
application in a balanced manner across members within the data sharing group.
Central to these capabilities is a server list that the data sharing group returns on
connection boundaries and optionally on transaction boundaries. This list contains
the IP address and WLM weight for each data sharing group member. With this
information, a client can distribute transactions in a balanced manner, or identify
the member to use when there is a communication failure.
DB2 for z/OS provides several methods for clients to access a data sharing group.
The access method that is set up for communication with the data sharing group
determines whether Sysplex workload balancing is possible. The following table
lists the access methods and indicates whether Sysplex workload balancing is
possible.
Table 41. Data sharing access methods and Sysplex workload balancing
Sysplex
workload
Data sharing access balancing
method1 Description possible?
Group access A requester uses the group's dynamic virtual IP Yes
address (DVIPA) to make an initial connection
to the DB2 for z/OS location. A connection to
the data sharing group that uses the group IP
address and SQL port is always successful if at
least one member is started. The server list that
is returned by the data sharing group contains:
v A list of members that are currently active
and can perform work
v The WLM weight for each member
The group IP address is configured using the
z/OS Sysplex distributor. To clients that are
outside the Sysplex, the Sysplex distributor
provides a single IP address that represents a
DB2 location. In addition to providing fault
tolerance, the Sysplex distributor can be
configured to provide connection load
balancing.
Member-specific access A requester uses a location alias to make an Yes
initial connection to one of the members that is
represented by the alias. A connection to the
data sharing group that uses the group IP
address and alias SQL port is always successful
if at least one member is started. The server list
that is returned by the data sharing group
contains:
v A list of members that are currently active,
can perform work, and have been configured
as an alias
v The WLM weight for each member
The requester uses this information to connect to
the member or members with the most capacity
that are also associated with the location alias.
Member-specific access is used when requesters
need to take advantage of Sysplex workload
balancing among a subset of members of a data
sharing group.
Single-member access Single-member access is used when requesters No
need to access only one member of a data
sharing group. For single-member access, the
connection uses the member-specific IP address.
Chapter 10. Java client support for high availability on IBM data servers 241
Table 41. Data sharing access methods and Sysplex workload balancing (continued)
Sysplex
workload
Data sharing access balancing
method1 Description possible?
Note:
1. For more information on data sharing access methods, see http://
publib.boulder.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db29.doc.dshare/
db2z_tcpipaccessmethods.htm.
Sysplex workload balancing includes automatic client reroute: Automatic client reroute
support enables a client to recover from a failure by attempting to reconnect to the
database through any available member of a Sysplex. Reconnection to another
member is called failover.
Sysplex workload balancing during migration of a data sharing group to DB2 9.1 for z/OS:
When you migrate a data sharing group to DB2 9.1 for z/OS new-function mode,
you need to take these steps:
1. Restart all members of the data group.
2. Restart the JVMs under which applications that connect to the data sharing
group using IBM Data Server Driver for JDBC and SQLJ type 4 connectivity
run.
Stopping and starting all members prevents applications that use Sysplex workload
balancing from having unbalanced connections.
For Java, CLI, or .NET client applications, failover for automatic client reroute can
be seamless or non-seamless. Seamless failover means that when the application
successfully reconnects to an alternate server, the server does not return an error to
the application.
Client support for high availability is incompatible with a DB2 Connect environment:
Client support for high availability requires a DB2 Connect license. However, this
support is incompatible with a DB2 Connect environment. Do not use a DB2
Connect server when you use client support for high availability.
Do not use client affinities: Client affinities should not be used as a high availability
solution for direct connections to DB2 for z/OS. Client affinities is not applicable to
a DB2 for z/OS data sharing environment, because all members of a data sharing
group can access data concurrently. A major disadvantage of client affinities in a
data sharing environment is that if failover occurs because a data sharing group
member fails, the member that fails might have retained locks that can severely
affect transactions on the member to which failover occurs.
The following table describes the basic property settings for Java applications.
The following IBM Data Server Driver for JDBC and SQLJ Connection or
DataSource properties control Sysplex workload balancing.
Table 43. Connection or DataSource properties for fine-tuning Sysplex workload balancing for direct connections from
the IBM Data Server Driver for JDBC and SQLJ to DB2 for z/OS
IBM Data Server Driver for JDBC and SQLJ
property Description
blockingReadConnectionTimeout Specifies the amount of time in seconds before a connection
socket read times out. This property affects all requests that
are sent to the data source after a connection is successfully
established. The default is 0, which means that there is no
timeout. Set this property to a value greater by a few seconds
than the time that is required to execute the longest query in
the application.
loginTimeout Specifies the maximum time in seconds to wait for a new
connection to a data source. After the number of seconds that
are specified by loginTimeout have elapsed, the driver closes
the connection to the data source. The default is 0, which
means that the timeout value is the default system timeout
value. The recommended value is five seconds.
maxRefreshInterval Specifies the maximum amount of time in seconds between
refreshes of the client copy of the server list. The default is 30.
The minimum valid value is 1.
maxTransportObjects Specifies the maximum number of connections that the
requester can make to the data sharing group. The default is
-1, which means an unlimited number.
Chapter 10. Java client support for high availability on IBM data servers 243
The following IBM Data Server Driver for JDBC and SQLJ configuration properties
also control Sysplex workload balancing.
Table 44. Configuration properties for fine-tuning Sysplex workload balancing for direct connections from the IBM Data
Server Driver for JDBC and SQLJ to DB2 for z/OS
IBM Data Server Driver for JDBC and SQLJ
configuration property Description
db2.jcc.maxTransportObjectIdleTime Specifies the maximum elapsed time in number of seconds
before an idle transport is dropped. The default is 60. The
minimum supported value is 0.
db2.jcc.maxTransportObjectWaitTime Specifies the number of seconds that the client will wait for a
transport to become available. The default is -1 (unlimited).
The minimum supported value is 0.
db2.jcc.minTransportObjects Specifies the lower limit for the number of transport objects in
a global transport object pool. The default value is 0. Any
value that is less than or equal to 0 means that the global
transport object pool can become empty.
The following examples demonstrate setting up Java client applications for Sysplex
workload balancing for high availability.
Before you can set up the client, you need to configure the following server
software:
v WLM for z/OS
For workload balancing to work efficiently, DB2 work needs to be classified.
Classification applies to the first non-SET SQL statement in each transaction.
Among the areas by which you need to classify the work are:
– Authorization ID
– Client info properties
– Stored procedure name
The stored procedure name is used for classification only if the first statement
that is issued by the client in the transaction is an SQL CALL statement.
For a complete list of classification attributes, see the information on
classification attributes at the following URL:
http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/topic/-
com.ibm.db29.doc.perf/db2z_classificationattributes.htm
v DB2 for z/OS, set up for data sharing
This example assumes that you are using WebSphere Application Server. The
minimum level of WebSphere Application Server is Version 5.1.
2. Set the IBM Data Server Driver for JDBC and SQLJ data source property
enableSysplexWLB to enable the Sysplex workload balancing.
In the WebSphere Application Server administrative console, set the following
properties for the DataSource that your application uses to connect to the data
source. Start with settings similar to these:
Table 45. Example of data source property settings for IBM Data Server Driver for JDBC and
SQLJ Sysplex workload balancing for DB2 for z/OS
Property Setting
enableSysplexWLB true
maxRefreshInterval 30
maxTransportObjects 80
This example assumes that you are using the DriverManager interface to establish
a connection.
Chapter 10. Java client support for high availability on IBM data servers 245
c.
[jcc] Driver: IBM Data Server Driver for JDBC and SQLJ Architecture nnn xxx
2. Set the IBM Data Server Driver for JDBC and SQLJ Connection property
enableSysplexWLB to enable workload balancing. You can also use property
maxTransportObjects to limit the total number of connections to the DB2 for
z/OS data sharing group, and maxRefreshInterval to specify the maximum
amount of time between refreshes of the client copy of the server list. A
minimum driver level of 3.58 is required for using maxRefreshInterval.
java.util.Properties properties = new java.util.Properties();
properties.put("user", "xxxx");
properties.put("password", "yyyy");
properties.put("enableSysplexWLB", "true");
properties.put("maxTransportObjects", "80");
properties.put("maxRefreshInterval", "30");
java.sql.Connection con =
java.sql.DriverManager.getConnection(url, properties);
3. Set IBM Data Server Driver for JDBC and SQLJ configuration properties to
fine-tune workload balancing for all DataSource or Connection instances that
are created under the driver. Set the configuration properties in a
DB2JccConfiguration.properties file by following these steps:
a. Create a DB2JccConfiguration.properties file or edit the existing
DB2JccConfiguration.properties file.
b. Set the db2.jcc.maxTransportObjects configuration property only if multiple
DataSource objects are defined that point to the same data sharing group,
and the number of connections across the different DataSource objects needs
to be limited.
Start with a setting similar to this one:
db2.jcc.maxTransportObjects=500
c. Include the directory that contains DB2JccConfiguration.properties in the
CLASSPATH concatenation.
The following overview describes the steps that occur when a client connects to a
DB2 for z/OS Sysplex, and Sysplex workload balancing is enabled:
1. When the client first establishes a connection using the sysplex-wide IP address
called the group IP address, or when a connection is reused by another
connection object, the server returns member workload distribution
information.
The default lifespan of the cached server list is 30 seconds.
2. At the start of a new transaction, the client reads the cached server list to
identify a member that has untapped capacity, and looks in the transport pool
for an idle transport that is tied to the under-utilized member. (An idle
transport is a transport that has no associated connection object.)
v If an idle transport is available, the client associates the connection object
with the transport.
v If, after a user-configurable timeout, no idle transport is available in the
transport pool and no new transport can be allocated because the transport
pool has reached its limit, an error is returned to the application.
Client support for automatic client reroute is available in IBM data server clients
that have a DB2 Connect license. The DB2 Connect server is not required to
perform automatic client reroute.
Automatic client reroute for connections to DB2 for z/OS operates in the following
way:
1. As part of the response to a COMMIT request from the client, the data server
returns:
v An indicator that specifies whether transports can be reused. Transports can
be reused if there are no resources remaining, such as held cursors.
v SET statements that the client can use to replay the connection state during
transport reuse.
2. If the first SQL statement in a transaction fails, and transports can be reused:
v No error is reported to the application.
v The failing SQL statement is executed again.
v The SET statements that are associated with the logical connection are
replayed to restore the connection state.
3. If an SQL statement that is not the first SQL statement in a transaction fails,
and transports can be reused:
v The transaction is rolled back.
v The application is reconnected to the data server.
v The SET statements that are associated with the logical connection are
replayed to restore the connection state.
v SQL error -30108 (for Java) or SQL30108N (for non-Java clients) is returned to
the application to notify it of the rollback and successful reconnection. The
application needs to include code to retry the failed transaction.
Chapter 10. Java client support for high availability on IBM data servers 247
4. If an SQL statement that is not the first SQL statement in a transaction fails,
and transports cannot be reused:
v The logical connection is returned to its initial, default state.
v SQL error -30081 (for Java) or SQL30081N (for non-Java clients) is returned to
the application to notify it that reconnection was unsuccessful. The
application needs to reconnect to the data server, reestablish the connection
state, and retry the failed transaction.
5. If connections to all members of the data sharing member list have been tried,
and none have succeeded, a connection is tried using the URL that is associated
with the data sharing group, to determine whether any members are now
available.
The following conditions must be satisfied for seamless failover to occur for direct
connections to DB2 for z/OS:
v The application language is Java, CLI, or .NET.
v The connection is not in a transaction. That is, the failure occurs when the first
SQL statement in the transaction is executed.
v The data server allows transport reuse at the end of the previous transaction. An
exception to this condition is if transport reuse is not granted because the
application was bound with KEEPDYNAMIC(YES).
v All global session data is closed or dropped.
v There are no open, held cursors.
v If the application uses CLI, the application cannot perform actions that require
the driver to maintain a history of previously called APIs in order to replay the
SQL statement. Examples of such actions are specifying data at execution time,
performing compound SQL, or using array input.
v The application is not a stored procedure.
v The application is not running in a Federated environment.
v Two-phase commit is used, if transactions are dependent on the success of
previous transactions. When a failure occurs during a commit operation, the
client has no information about whether work was committed or rolled back at
the server. If each transaction is dependent on the success of the previous
transaction, use two-phase commit. Two-phase commit requires the use of XA
support.
In most cases, these services are provided with the help of multi-tier applications
with each tier serving a specific purpose.
The runtime environment defines four application component types that a J2EE
product must support:
v Application clients are Java programming language programs that are typically
GUI programs that execute on a desktop computer. Application clients have
access to all of the facilities of the J2EE middle tier.
v Applets are GUI components that typically execute in a web browser, but can
execute in a variety of other applications or devices that support the applet
programming model.
v Servlets, JavaServer Pages (JSPs), filters, and web event listeners typically
execute in a web server and might respond to HTTP requests from web clients.
Servlets, JSPs, and filters can be used to generate HTML pages that are an
application's user interface. They can also be used to generate XML or other
format data that is consumed by other application components. Servlets, pages
created with the JSP technology, web filters, and web event listeners are referred
to collectively in this specification as web components. Web applications are
composed of web components and other data such as HTML pages.
The application components listed above can divided into three categories, based
on how they can be deployed and managed:
v Components that are deployed, managed, and executed on a J2EE server.
v Components that are deployed, managed on a J2EE server, but are loaded to and
executed on a client machine.
v Components whose deployment and management are not completely defined by
this specification. Application clients can be under this category.
A typical J2EE product will provide a container for each application component
type; application client container, applet container, web container, and enterprise
bean container. The container tools also understand the file formats for packaging
the application components for deployment.
The JNDI API has two parts: an application-level interface used by the application
components to access naming and directory services and a service provider
interface to attach a provider of a naming and directory service.
J2EE includes support for distributed transactions through two specifications, Java
Transaction API (JTA) and Java Transaction Service (JTS). JTA is a high-level,
implementation-independent, protocol-independent API that allows applications
and application servers to access transactions. In addition, the JTA is always
enabled.
The IBM Data Server Driver for JDBC and SQLJ and the DB2 JDBC Type 2 Driver
for Linux, UNIX and Windows implement the JTA and JTS specifications.
For IBM Data Server Driver for JDBC and SQLJ type 4 connectivity distributed
transactions are supported to DB2 Database for Linux, UNIX, and Windows, DB2
for z/OS, and DB2 for i servers.
JTA specifies standard Java interfaces between a transaction manager and the
parties involved in a distributed transaction system: the resource manager, the
application server, and the transactional applications.
JTS specifies the implementation of a Transaction Manager which supports JTA and
implements the Java mapping of the OMG Object Transaction Service (OTS) 1.1
specification at the level below the API. JTS propagates transactions using IIOP.
JTA and JTS allow application J2EE servers to take the burden of transaction
management off of the component developer. Developers can define the
transactional properties of EJB technology based components during design or
deployment using declarative statements in the deployment descriptor. The
application server takes over the transaction management responsibilities.
The DB2 JDBC Type 2 Driver provides these two DataSource classes:
v COM.ibm.db2.jdbc.DB2ConnectionPoolDataSource
v COM.ibm.db2.jdbc.DB2XADataSource
The IBM Data Server Driver for JDBC and SQLJ provides these two DataSource
classes:
v com.ibm.db2.jcc.DB2ConnectionPoolDataSource
v com.ibm.db2.jcc.DB2XADataSource
For the detail information about how to configure the WebSphere Application
Server with DB2, refer to WebSphere Application Server InfoCenter at:
http://www.ibm.com/software/webservers/appserv/library.html
The best way to demonstrate distributed transactions is to contrast them with local
transactions. With local transactions, a JDBC application makes changes to a
database permanent and indicates the end of a unit of work in one of the
following ways:
v By calling the Connection.commit or Connection.rollback methods after
executing one or more SQL statements
v By calling the Connection.setAutoCommit(true) method at the beginning of the
application to commit changes after every SQL statement
Figure 50 outlines code that executes local transactions.
javax.transaction.UserTransaction utx;
// Use the begin method on a UserTransaction object to indicate
// the beginning of a distributed transaction.
utx.begin();
...
// Execute some SQL with one Connection object.
// Do not call Connection methods commit or rollback.
...
// Use the commit method on the UserTransaction object to
// drive all transaction branches to commit and indicate
// the end of the distributed transaction.
utx.commit();
...
class XASample
{
javax.sql.XADataSource xaDS1;
javax.sql.XADataSource xaDS2;
javax.sql.XAConnection xaconn1;
javax.sql.XAConnection xaconn2;
javax.transaction.xa.XAResource xares1;
javax.transaction.xa.XAResource xares2;
java.sql.Connection conn1;
java.sql.Connection conn2;
try
{ // Now prepare both branches of the distributed transaction.
// Both branches must prepare successfully before changes
// can be committed.
// If the distributed transaction fails, an XAException is thrown.
rc1 = xares1.prepare(xid1);
if(rc1 == javax.transaction.xa.XAResource.XA_OK)
{ // Prepare was successful. Prepare the second connection.
rc2 = xares2.prepare(xid1);
if(rc2 == javax.transaction.xa.XAResource.XA_OK)
{ // Both connections prepared successfully and neither was read-only.
xares1.commit(xid1, false);
xares2.commit(xid1, false);
}
else if(rc2 == javax.transaction.xa.XAException.XA_RDONLY)
{ // The second connection is read-only, so just commit the
// first connection.
xares1.commit(xid1, false);
}
try
{
conn1.close();
xaconn1.close();
}
catch (Exception e)
{
System.out.println("Failed to close connection 1: " + e.toString());
e.printStackTrace();
}
try
{
conn2.close();
xaconn2.close();
}
catch (Exception e)
{
System.out.println("Failed to close connection 2: " + e.toString());
e.printStackTrace();
}
}
catch (java.sql.SQLException sqe)
A distributed transaction to DB2 Database for Linux, UNIX, and Windows that
ends, but cannot be prepared, is not an indoubt transaction. Therefore, the
transaction manager cannot recover the transaction, and the DB2 resource manager
does not put the transaction in its list of indoubt transactions. The DB2 resource
manager does not roll back the transaction immediately, but waits until all
connections to the database are released. During this period of inactivity, the
transaction continues to hold locks on the database. If the transaction manager
does not disconnect all connections to the database to allow rollback, the ended
transaction continues to lock database records. If another application attempts to
access those locked records, a deadlock can occur.
In a Java application that uses distributed transactions and IBM Data Server Driver
for JDBC and SQLJ type 4 connectivity, you can prevent a transaction from holding
locks on a database indefinitely by calling the XAResource.setTransactionTimeout
method to set a timeout value on transactions. To do that, follow these steps:
1. On the DB2 Database for Linux, UNIX, and Windows instance, issue this
command to cause the instance to check for timeout values.
DB2 UPDATE DBM CFG USING RESYNC_INTERVAL seconds
seconds needs to be less than the minimum timeout value that you set for a
transaction.
2. In your application, after you create an XAResource object, call the
XAResource.setTransactionTimeout method to set the timeout value.
You can check the current timeout value by calling
XAResource.getTransactionTimeout.
Session beans represent business services and are not shared between users. Entity
beans are multi-user, distributed transactional objects that represent persistent data.
The transactional boundaries of a EJB application can be set by specifying either
container-managed or bean-managed transactions.
The EJB sample application provides two business services. One service allows the
user to access information about an employee (which is stored in the EMPLOYEE
table of the sample database) through that employee's employee number. The
other service allows the user to retrieve a list of the employee numbers, so that the
user can obtain an employee number to use for querying employee data.
The following sample uses EJBs to implement a J2EE application to access a data
source. The sample utilizes the Model-View-Controller (MVC) architecture, which
is a commonly-used GUI architecture. The JSP is used to implement the view (the
presentation component). A servlet acts as the controller in the sample. It controls
the workflow and delegates the user's request to the model, which is implemented
using EJBs. The model component of the sample consists of two EJBs, one session
bean and one entity bean. The container-managed persistence (CMP) bean,
Employee, represents the distributed transactional objects that represent the
persistent data in the EMPLOYEE table of the sample database. The term
container-managed persistence means that the EJB container handles all database
access required by the entity bean. The bean's code contains no database access
(SQL) calls. As a result, the bean's code is not tied to a specific persistent storage
mechanism (database). The session bean, AccessEmployee, acts as the Façade of the
entity bean and provides provide a uniform client access strategy. This Façade
design reduces the network traffic between the EJB client and the entity bean and
is more efficient in distributed transactions than if the EJB client accesses the entity
bean directly. Access to the database server can be provided from the session bean
or entity bean. The two services of the sample application demonstrate both
approaches to accessing the database server. In the first service, the entity bean is
used:
//====================================================
// This method returns an employee’s information by
// interacting with the entity bean located by the
// provided employee number
public EmployeeInfo getEmployeeInfo(String empNo)
throws java.rmi.RemoteException
}
Employee employee = null;
try
}
employee = employeeHome.findByPrimaryKey(new EmployeeKey(empNo));
EmployeeInfo empInfo = new EmployeeInfo(empNo);
//set the employee’s information to the dependent value object
empInfo.setEmpno(employee.getEmpno());
empInfo.setFirstName (employee.getFirstName());
empInfo.setMidInit(employee.getMidInit());
empInfo.setLastName(employee.getLastName());
empInfo.setWorkDept(employee.getWorkDept());
In the second service, which displays employee numbers, the session bean,
AccessEmployee, directly accesses the database table.
/=============================================
* Get the employee number list.
* @return Collection
*/
public Collection getEmpNoList()
{
ResultSet rs = null;
PreparedStatement ps = null;
Vector list = new Vector();
DataSource ds = null;
Connection con = null;
try
{
ds = getDataSource();
con = ds.getConnection();
String schema = getEnvProps(DBschema);
String query = "Select EMPNO from " + schema + ".EMPLOYEE";
ps = con.prepareStatement(query);
ps.executeQuery();
rs = ps.getResultSet();
EmployeeKey pk;
while (rs.next())
{
pk = new EmployeeKey();
pk.employeeId = rs.getString(1);
list.addElement(pk.employeeId);
}
rs.close();
return list;
The IBM Data Server Driver for JDBC and SQLJ provides a factory of pooled
connections that are used by WebSphere Application Server or other application
servers. The application server actually does the pooling. Connection pooling is
completely transparent to a JDBC or SQLJ application.
With homogeneous pooling, all Connection objects that come from a connection
pool should have the same properties. The first logical Connection that is created
with the DataSource has the properties that were defined for the DataSource.
However, an application can change those properties. When a Connection is
returned to the connection pool, an application server or a pooling module should
reset the properties to their original values. However, an application server or
pooling module might not reset the changed properties. The JDBC driver does not
modify the properties. Therefore, depending on the application server or pool
module design, a reused logical Connection might have the same properties as
those that are defined for the DataSource or different properties.
With heterogeneous pooling, Connection objects with different properties can share
the same connection pool.
The following tables summarize the mappings of Java data types to JDBC and
database data types for a DB2 Database for Linux, UNIX, and Windows, DB2 for
z/OS, or IBM Informix (IDS) system.
The following table summarizes the mappings of Java data types to database data
types for PreparedStatement.setXXX or ResultSet.updateXXX methods in JDBC
programs, and for input host expressions in SQLJ programs. When more than one
Java data type is listed, the first data type is the recommended data type.
Table 46. Mappings of Java data types to database server data types for updating database tables
Java data type Database data type
short SMALLINT
1 1
boolean , byte , java.lang.Boolean SMALLINT
int, java.lang.Integer INTEGER
long, java.lang.Long BIGINT11
float, java.lang.Float REAL
double, java.lang.Double DOUBLE
java.math.BigDecimal DECIMAL(p,s)2
java.math.BigDecimal DECFLOAT(n)3,4
java.lang.String CHAR(n)5
java.lang.String GRAPHIC(m)6
java.lang.String VARCHAR(n)7
java.lang.String VARGRAPHIC(m)8
java.lang.String CLOB9
java.lang.String XML10
byte[] CHAR(n) FOR BIT DATA5
byte[] VARCHAR(n) FOR BIT DATA7
byte[] BINARY(n)5, 12
byte[] VARBINARY(n)7, 12
byte[] BLOB9
byte[] ROWID
byte[] XML10
The following table summarizes the mappings of DB2 or IDS data types to Java
data types for ResultSet.getXXX methods in JDBC programs, and for iterators in
SQLJ programs. This table does not list Java numeric wrapper object types, which
are retrieved using ResultSet.getObject.
The following table summarizes mappings of Java data types to JDBC data types
and DB2 or IDS data types for calling user-defined function and stored procedure
parameters. The mappings of Java data types to JDBC data types are for
CallableStatement.registerOutParameter methods in JDBC programs. The mappings
of Java data types to database server data types are for parameters in stored
procedure or user-defined function invocations.
If more than one Java data type is listed in the following table, the first data type
is the recommended data type.
Table 48. Mappings of Java, JDBC, and SQL data types for calling stored procedures and user-defined functions
Java data type JDBC data type SQL data type
1
boolean BIT SMALLINT
1
byte TINYINT SMALLINT
short, java.lang.Short SMALLINT SMALLINT
int, java.lang.Integer INTEGER INTEGER
long BIGINT BIGINT5
float, java.lang.Float REAL REAL
float, java.lang.Float FLOAT REAL
double, java.lang.Double DOUBLE DOUBLE
The following table summarizes mappings of the SQL parameter data types in a
CREATE PROCEDURE or CREATE FUNCTION statement to the data types in the
corresponding Java stored procedure or user-defined function method.
For DB2 Database for Linux, UNIX, and Windows, if more than one Java data type
is listed for an SQL data type, only the first Java data type is valid.
For DB2 for z/OS, if more than one Java data type is listed, and you use a data
type other than the first data type as a method parameter, you need to include a
method signature in the EXTERNAL clause of your CREATE PROCEDURE or
CREATE FUNCTION statement that specifies the Java data types of the method
parameters.
Table 49. Mappings of SQL data types in a CREATE PROCEDURE or CREATE FUNCTION statement to data types in
the corresponding Java stored procedure or user-defined function program
SQL data type in CREATE PROCEDURE or CREATE Data type in Java stored procedure or
FUNCTION user-defined function method1
SMALLINT short, java.lang.Integer
INTEGER int, java.lang.Integer
2
BIGINT long, java.lang.Long
REAL float, java.lang.Float
DOUBLE double, java.lang.Double
DECIMAL java.math.BigDecimal
3
DECFLOAT java.math.BigDecimal
CHAR java.lang.String
VARCHAR java.lang.String
CHAR FOR BIT DATA byte[]
VARCHAR FOR BIT DATA byte[]
4
BINARY byte[]
4
VARBINARY byte[]
DATE java.sql.Date
The IBM Data Server Driver for JDBC and SQLJ uses Java data types for its
internal processing of input and output parameters and ResultSet content in JDBC
and SQLJ applications. The Java data type that is used by the driver is based on
the best match for the corresponding SQL type when the target SQL type is known
to the driver.
For values that are assigned to or retrieved from DATE, TIME, or TIMESTAMP
SQL types, the IBM Data Server Driver for JDBC and SQLJ uses java.sql.Date for
DATE SQL types, java.sql.Time for TIME SQL types, and java.sql.Timestamp for
TIMESTAMP SQL types.
When you assign a string value to a DATE, TIME, or TIMESTAMP target, the IBM
Data Server Driver for JDBC and SQLJ uses Java facilities to convert the string
value to a java.sql.Date, java.sql.Time, or java.sql.Timestamp value. If a string
representation of a date, time, or timestamp value does not correspond to a real
date or time, Java adjusts the value to a real date or time value. In particular, Java
Important: To avoid unexpected results when you assign or retrieve date, time, or
timestamp values in JDBC or SQLJ applications, ensure that the values are real
date, time, or timestamp values. In addition, do not use '24' as the hour component
of a time or timestamp value.
If a value that does not correspond to a real date or time, such as a value with an
hour component of '24', is stored in a TIME or TIMESTAMP column, you can
avoid adjustment during retrieval by executing the SQL CHAR function against
that column in the SELECT statement that defines a ResultSet. Executing the
CHAR function converts the date or time value to a character string value on the
database side. However, if you use the getTime or getTimestamp method to
retrieve that value from the ResultSet, the IBM Data Server Driver for JDBC and
SQLJ converts the value to a java.sql.Time or java.sql.Timestamp type, and Java
adjusts the value. To avoid date adjustment, execute the CHAR function against
the column value, and retrieve the value from the ResultSet with the getString
method.
The Java java.util.Date and java.util.Timestamp classes use the Julian calendar for
dates before October 4, 1582, and the Gregorian calendar for dates starting with
October 4, 1582. In the Gregorian calendar, October 4, 1582, is followed by October
15, 1582. If a Java program encounters a java.util.Date or java.util.Timestamp value
that is between October 5, 1582, and October 14, 1582, inclusive, Java adds 10 days
to that date. Therefore, a DATE or TIMESTAMP value in a DB2 table that has a
value between October 5, 1582, and October 14, 1582, inclusive, is retrieved in a
Java program as a java.util.Date or java.util.Timestamp value between October 15,
1582, and October 24, 1582, inclusive. A java.util.Date or java.util.Timestamp value
in a Java program that is between October 5, 1582, and October 14, 1582, inclusive,
is stored in a DB2 table as a DATE or TIMESTAMP value between October 15,
1582, and October 24, 1582, inclusive.
To retrieve a value in the range October 5, 1582, to October 14, 1582, from a DB2
table without date adjustment, execute the SQL CHAR function against the DATE
or TIMESTAMP column in the SELECT statement that defines a ResultSet.
Executing the CHAR function converts the date or time value to a character string
value on the database side.
To store a value in the range October 5, 1582, to October 14, 1582 in a DB2 table
without date adjustment, you can use one of the following techniques:
v For a JDBC or an SQLJ application, use the setString method to assign the value
to a String input parameter. Cast the input parameter as VARCHAR, and execute
the DATE or TIMESTAMP function against the result of the cast. Then store the
result of the DATE or TIMESTAMP function in the DATE or TIMESTAMP
column.
v For a JDBC application, set the Connection or DataSource property
sendDataAsIs to true, and use the setString method to assign the date or
Example: Retrieve October 10, 1582, from a DATE column without date
adjustment.
// DATETABLE has one date column called DATECOL with one row.
// Its value is 1582-10-10.
java.sql.ResultSet rs =
statement.executeQuery(SELECT CHAR(DATECOL) FROM DATETABLE);
rs.next();
System.out.println(rs.getString(1)); // Value is retrieved as 1582-10-10
Example: Store October 10, 1582, in a DATE column without date adjustment.
String s = "1582-10-10";
java.sql.Statement stmt = c.createStatement;
java.sql.PreparedStatement ps =
c.prepareStatement("Insert INTO DATETABLE VALUES " +
"(DATE(CAST (? AS VARCHAR)))");
ps.setString(1, s);
ps.executeUpdate(); // Value is inserted as 1582-10-10
Properties for the IBM Data Server Driver for JDBC and SQLJ
IBM Data Server Driver for JDBC and SQLJ properties define how the connection
to a particular data source should be made. Most properties can be set for a
DataSource object or for a Connection object.
Connection con =
java.sql.DriverManager.getConnection(url);
deferPrepares
Specifies whether invocation of the Connection.prepareStatement method
results in immediate preparation of an SQL statement on the data source, or
whether statement preparation is deferred until the PreparedStatement.execute
method is executed. The data type of this property is boolean.
deferPrepares is supported for IBM Data Server Driver for JDBC and SQLJ
type 2 connectivity to DB2 Database for Linux, UNIX, and Windows, and for
IBM Data Server Driver for JDBC and SQLJ type 4 connectivity.
Possible values are:
true Statement preparation on the data source does not occur until the
PreparedStatement.execute method is executed. This is the default.
false Statement preparation on the data source occurs when the
Connection.prepareStatement method is executed.
Deferring prepare operations can reduce network delays. However, if you defer
prepare operations, you need to ensure that input data types match table
column types.
description
A description of the data source. The data type of this property is String.
downgradeHoldCursorsUnderXa
Specifies whether cursors that are defined WITH HOLD can be opened under
XA connections.
downgradeHoldCursorsUnderXa applies to:
v IBM Data Server Driver for JDBC and SQLJ type 4 connectivity to DB2 for
z/OS servers.
v IBM Data Server Driver for JDBC and SQLJ type 4 connectivity or IBM Data
Server Driver for JDBC and SQLJ type 2 connectivity to DB2 Database for
Linux, UNIX, and Windows servers.
The default is false, which means that a cursor that is defined WITH HOLD
cannot be opened under an XA connection. An exception is thrown when an
attempt is made to open that cursor.
resultSetHoldability
Specifies whether cursors remain open after a commit operation. The data type
of this property is int. Valid values are:
DB2BaseDataSource.HOLD_CURSORS_OVER_COMMIT (1)
Leave cursors open after a commit operation.
This setting is not valid for a connection that is part of a distributed
(XA) transaction.
DB2BaseDataSource.CLOSE_CURSORS_AT_COMMIT (2)
Close cursors after a commit operation.
DB2BaseDataSource.NOT_SET (0)
This is the default value. The behavior is:
v For connections that are part of distributed (XA) transactions,
cursors are closed after a commit operation.
v For connections that are not part of a distributed transaction:
– For connections to all versions of DB2 for z/OS, DB2 Database for
Linux, UNIX, and Windows, or DB2 for i servers, or to
Cloudscape Version 8.1 or later servers, cursors remain open after
a commit operation.
Integer
Constant value Format
com.ibm.db2.jcc.DB2BaseDataSource.ISO 1 yyyy-mm-dd-
hh.mm.ss.nnnnnn
com.ibm.db2.jcc.DB2BaseDataSource.JDBC 5 yyyy-mm-dd
hh:mm:ss.nnnnnn
Note:
If the traceFile property is also specified, the traceDirectory value is not used.
traceFile
Specifies the name of a file into which the IBM Data Server Driver for JDBC
and SQLJ writes trace information. The data type of this property is String.
The traceFile property is an alternative to the logWriter property for directing
the output trace stream to a file.
traceFileAppend
Specifies whether to append to or overwrite the file that is specified by the
traceFile property. The data type of this property is boolean. The default is
false, which means that the file that is specified by the traceFile property is
overwritten.
traceLevel
Specifies what to trace. The data type of this property is int.
You can specify one or more of the following traces with the traceLevel
property:
v com.ibm.db2.jcc.DB2BaseDataSource.TRACE_NONE (X'00')
Integer
Constant value Format
com.ibm.db2.jcc.DB2BaseDataSource.ISO 1 yyyy-mm-dd
com.ibm.db2.jcc.DB2BaseDataSource.USA 2 mm/dd/yyyy
com.ibm.db2.jcc.DB2BaseDataSource.EUR 3 dd.mm.yyyy
com.ibm.db2.jcc.DB2BaseDataSource.JIS 4 yyyy-mm-dd
Integer
Constant value Format
com.ibm.db2.jcc.DB2BaseDataSource.ISO 1 hh:mm:ss
com.ibm.db2.jcc.DB2BaseDataSource.USA 2 hh:mm am or
hh:mm pm
com.ibm.db2.jcc.DB2BaseDataSource.EUR 3 hh.mm.ss
com.ibm.db2.jcc.DB2BaseDataSource.JIS 4 hh:mm:ss
Properties that apply to IDS and DB2 Database for Linux, UNIX, and Windows are:
currentLockTimeout
Specifies whether DB2 Database for Linux, UNIX, and Windows servers wait
for a lock when the lock cannot be obtained immediately. The data type of this
property is int. Possible values are:
integer Wait for integer seconds. integer is between -1 and 32767, inclusive.
LOCK_TIMEOUT_NO_WAIT
Do not wait for a lock. This is the default.
LOCK_TIMEOUT_WAIT_INDEFINITELY
Wait indefinitely for a lock.
LOCK_TIMEOUT_NOT_SET
Use the default for the data source.
IBM Data Server Driver for JDBC and SQLJ properties for DB2
Database for Linux, UNIX, and Windows
Some of the IBM Data Server Driver for JDBC and SQLJ properties apply only to
DB2 Database for Linux, UNIX, and Windows servers.
IBM Data Server Driver for JDBC and SQLJ properties for DB2
for z/OS
Some of the IBM Data Server Driver for JDBC and SQLJ properties apply only to
DB2 for z/OS servers.
IBM Data Server Driver for JDBC and SQLJ properties for IDS
Some of the IBM Data Server Driver for JDBC and SQLJ properties apply only to
IBM Informix (IDS) databases. Those properties correspond to IDS environment
variables.
IBM Data Server Driver for JDBC and SQLJ configuration properties
The IBM Data Server Driver for JDBC and SQLJ configuration properties have
driver-wide scope.
collection-ID.*
You should set the trace properties under the direction of IBM Software
Support.
This configuration property applies only to DB2 for z/OS.
db2.jcc.t2zosTraceWrap
Enables or disables wrapping of the SQLJ trace. db2.jcc.t2zosTraceWrap can
have one of the following values:
1 Wrap the trace
0 Do not wrap the trace
If a method has JDBC 2.0 and JDBC 3.0 forms, the IBM Data Server Driver for
JDBC and SQLJ supports all forms. The DB2 JDBC Type 2 Driver for Linux, UNIX
and Windows supports only the JDBC 2.0 forms.
Table 56. Support for Array methods
IBM Data Server DB2 JDBC Type 2
Driver for JDBC and Driver for Linux, UNIX IDS JDBC Driver
JDBC method SQLJ1 support and Windows support support
free2 Yes No No
getArray Yes No Yes
getBaseType Yes No Yes
getBaseTypeName Yes No Yes
getResultSet Yes No Yes
Notes:
1. Under the IBM Data Server Driver for JDBC and SQLJ, Array methods are supported for connections to DB2
Database for Linux, UNIX, and Windows data sources only.
2. This is a JDBC 4.0 method.
IBM Data Server Driver for JDBC and SQLJ support for SQL escape
syntax
The IBM Data Server Driver for JDBC and SQLJ supports SQL escape syntax, as
described in the JDBC 1.0 specification.
SQLJ clause
The SQL statements in an SQLJ program are in SQLJ clauses.
Syntax
#sql connection-declaration-clause ;
iterator-declaration-clause
executable-clause
Usage notes
Keywords in an SQLJ clause are case sensitive, unless those keywords are part of
an SQL statement in an executable clause.
SQLJ host-expression
A host expression is a Java variable or expression that is referenced by SQLJ
clauses in an SQLJ application program.
Syntax
: simple-variable
IN (complex-expression)
OUT
INOUT
Description
: Indicates that the variable or expression that follows is a host expression. The
colon must immediately precede the variable or expression.
IN|OUT|INOUT
For a host expression that is used as a parameter in a stored procedure call,
identifies whether the parameter provides data to the stored procedure (IN),
retrieves data from the stored procedure (OUT), or does both (INOUT). The
default is IN.
simple-variable
Specifies a Java unqualified identifier.
complex-expression
Specifies a Java expression that results in a single value.
Usage notes
v A complex expression must be enclosed in parentheses.
v ANSI/ISO rules govern where a host expression can appear in a static SQL
statement.
SQLJ implements-clause
The implements clause derives one or more classes from a Java interface.
Syntax
,
implements interface-element
interface-element:
sqlj.runtime.ForUpdate
sqlj.runtime.Scrollable
user-specified-interface-class
Description
interface-element
Specifies a user-defined Java interface, the SQLJ interface
sqlj.runtime.ForUpdate or the SQLJ interface sqlj.runtime.Scrollable.
You need to implement sqlj.runtime.ForUpdate when you declare an iterator
for a positioned UPDATE or positioned DELETE operation. See "Perform
positioned UPDATE and DELETE operations in an SQLJ application" for
information on performing a positioned UPDATE or positioned DELETE
operation in SQLJ.
You need to implement sqlj.runtime.Scrollable when you declare a scrollable
iterator. See "Use scrollable iterators in an SQLJ application" for information on
scrollable iterators.
SQLJ with-clause
The with clause specifies a set of one or more attributes for an iterator or a
connection context.
Syntax
,
with ( with-element )
with-element:
Description
holdability
For an iterator, specifies whether an iterator keeps its position in a table after a
COMMIT is executed. The value for holdability must be true or false.
sensitivity
For an iterator, specifies whether changes that are made to the underlying table
can be visible to the iterator after it is opened. The value must be
INSENSITIVE, SENSITIVE, or ASENSITIVE. The default is ASENSITIVE.
For connections to IBM Informix (IDS), only INSENSITIVE is supported.
dynamic
For an iterator that is defined with sensitivity=SENSITIVE, specifies whether
the following cases are true:
v When the application executes positioned UPDATE and DELETE statements
with the iterator, those changes are visible to the iterator.
v When the application executes INSERT, UPDATE, and DELETE statements
within the application but outside the iterator, those changes are visible to
the iterator.
The value for dynamic must be true or false. The default is false.
DB2 Database for Linux, UNIX, and Windows servers do not support dynamic
scrollable cursors. Specify true only if your application accesses data on DB2
for z/OS servers, at Version 9 or later.
For connections to IDS, only false is supported. IDS does not support
dynamic cursors.
updateColumns
For an iterator, specifies the columns that are to be modified when the iterator
is used for a positioned UPDATE statement. The value for updateColumns
must be a literal string that contains the column names, separated by commas.
column-name
For an iterator, specifies a column of the result table that is to be updated
using the iterator.
Java-ID
For an iterator or connection context, specifies a Java variable that identifies a
user-defined attribute of the iterator or connection context. The value of
Java-constant-expression is also user-defined.
dataSource
For a connection context, specifies the logical name of a separately-created
Usage notes
v The value on the left side of a with element must be unique within its with
clause.
v If you specify updateColumns in a with element of an iterator declaration
clause, the iterator declaration clause must also contain an implements clause
that specifies the sqlj.runtime.ForUpdate interface.
v If you do not customize your SQLJ program, the JDBC driver ignores the value
of holdability that is in the with clause. Instead, the driver uses the JDBC driver
setting for holdability.
SQLJ connection-declaration-clause
The connection declaration clause declares a connection to a data source in an
SQLJ application program.
Syntax
context Java-class-name
Java-modifiers implements-clause with-clause
Description
Java-modifiers
Specifies modifiers that are valid for Java class declarations, such as static,
public, private, or protected.
Java-class-name
Specifies a valid Java identifier. During the program preparation process, SQLJ
generates a connection context class whose name is this identifier.
implements-clause
See "SQLJ implements-clause" for a description of this clause. In a connection
declaration clause, the interface class to which the implements clause refers
must be a user-defined interface class.
with-clause
See "SQLJ with-clause" for a description of this clause.
Usage notes
v SQLJ generates a connection class declaration for each connection declaration
clause you specify. SQLJ data source connections are objects of those generated
connection classes.
v You can specify a connection declaration clause anywhere that a Java class
definition can appear in a Java program.
SQLJ iterator-declaration-clause
An iterator declaration clause declares a positioned iterator class or a named
iterator class in an SQLJ application program.
An iterator contains the result table from a query. SQLJ generates an iterator class
for each iterator declaration clause you specify. An iterator is an object of an
iterator class.
Syntax
iterator Java-class-name
Java-modifiers implements-clause with-clause
( positioned-iterator-column-declarations )
named-iterator-column-declarations
positioned-iterator-column declarations:
Java-data-type
named-iterator-column-declarations:
Java-data-type Java-ID
Description
Java-modifiers
Any modifiers that are valid for Java class declarations, such as static, public,
private, or protected.
Java-class-name
Any valid Java identifier. During the program preparation process, SQLJ
generates an iterator class whose name is this identifier.
implements-clause
See "SQLJ implements-clause" for a description of this clause. For an iterator
declaration clause that declares an iterator for a positioned UPDATE or
positioned DELETE operation, the implements clause must specify interface
sqlj.runtime.ForUpdate. For an iterator declaration clause that declares a
scrollable iterator, the implements clause must specify interface
sqlj.runtime.Scrollable.
with-clause
See "SQLJ with-clause" for a description of this clause.
positioned-iterator-column-declarations
Specifies a list of Java data types, which are the data types of the columns in
the positioned iterator. The data types in the list must be separated by
commas. The order of the data types in the positioned iterator declaration is
the same as the order of the columns in the result table. For online checking
during serialized profile customization to succeed, the data types of the
columns in the iterator must be compatible with the data types of the columns
in the result table. See "Java, JDBC, and SQL data types" for a list of compatible
data types.
Usage notes
v An iterator declaration clause can appear anywhere in a Java program that a
Java class declaration can appear.
v When a named iterator declaration contains more than one pair of Java data
types and Java IDs, all Java IDs within the list must be unique. Two Java IDs are
not unique if they differ only in case.
SQLJ executable-clause
An executable clause contains an SQL statement or an assignment statement. An
assignment statement assigns the result of an SQL operation to a Java variable.
Syntax
statement-clause
context-clause assignment-clause
Usage notes
v An executable clause can appear anywhere in a Java program that a Java
statement can appear.
v SQLJ reports negative SQL codes from executable clauses through class
java.sql.SQLException.
If SQLJ raises a run-time exception during the execution of an executable clause,
the value of any host expression of type OUT or INOUT is undefined.
SQLJ context-clause
A context clause specifies a connection context, an execution context, or both. You
use a connection context to connect to a data source. You use an execution context
to monitor and modify SQL statement execution.
Syntax
[ connection-context ]
execution-context
connection-context , execution context
Description
connection-context
Specifies a valid Java identifier that is declared earlier in the SQLJ program.
Usage notes
v If you do not specify a connection context in an executable clause, SQLJ uses the
default connection context.
v If you do not specify an execution context, SQLJ obtains the execution context
from the connection context of the statement.
SQLJ statement-clause
A statement clause contains an SQL statement or a SET TRANSACTION clause.
Syntax
{ SQL-statement }
SET-TRANSACTION-clause
Description
SQL-statement
You can include SQL statements in Table 101 in a statement clause.
SET-TRANSACTION-clause
Sets the isolation level for SQL statements in the program and the access mode
for the connection. The SET TRANSACTION clause is equivalent to the SET
TRANSACTION statement, which is described in the ANSI/ISO SQL standard
of 1992 and is supported in some implementations of SQL.
Table 101. Valid SQL statements in an SQLJ statement clause
Statement Applicable data sources
ALTER DATABASE 1 on page 362, 2 on page 362
ALTER FUNCTION 1 on page 362, 2 on page 362, 3 on page 362
ALTER INDEX 1 on page 362, 2 on page 362, 3 on page 362
ALTER PROCEDURE 1 on page 362, 2 on page 362, 3 on page 362
ALTER STOGROUP 1 on page 362, 2 on page 362
ALTER TABLE 1 on page 362, 2 on page 362, 3 on page 362
ALTER TABLESPACE 1 on page 362, 2 on page 362
CALL 1 on page 362, 2 on page 362, 3 on page 362
COMMENT ON 1 on page 362, 2 on page 362
COMMIT 1 on page 362, 2 on page 362, 3 on page 362
Compound SQL (BEGIN ATOMIC...END) 2 on page 362
CREATE ALIAS 1 on page 362, 2 on page 362
CREATE DATABASE 1 on page 362, 2 on page 362, 3a on page 362
CREATE DISTINCT TYPE 1 on page 362, 2 on page 362, 3 on page 362
CREATE FUNCTION 1 on page 362, 2 on page 362, 3 on page 362
Usage notes
v SQLJ supports both positioned and searched DELETE and UPDATE operations.
v For a FETCH statement, a positioned DELETE statement, or a positioned
UPDATE statement, you must use an iterator to refer to rows in a result table.
SQLJ SET-TRANSACTION-clause
The SET TRANSACTION clause sets the isolation level for the current unit of
work.
Syntax
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
READ UNCOMMITTED
REPEATABLE READ
SERIALIZABLE
Usage notes
SQLJ assignment-clause
The assignment clause assigns the result of an SQL operation to a Java variable.
Syntax
Java-ID = { fullselect }
order-by-clause optimize-for-clause
isolation-clause
queryno-clause
fetch-first-clause
iterator-conversion-clause
Description
Java-ID
Identifies an iterator that was declared previously as an instance of an iterator
class.
fullselect
Generates a result table.
iterator-conversion-clause
See "SQLJ iterator-conversion-clause" for a description of this clause.
Usage notes
v If the object that is identified by Java-ID is a positioned iterator, the number of
columns in the result set must match the number of columns in the iterator. In
addition, the data type of each column in the result set must be compatible with
the data type of the corresponding column in the iterator. See "Java, JDBC, and
SQL data types" for a list of compatible Java and SQL data types.
v If the object that is identified by Java-ID is a named iterator, the name of each
accessor method must match, except for case, the name of a column in the result
set. In addition, the data type of the object that an accessor method returns must
be compatible with the data type of the corresponding column in the result set.
v You can put an assignment clause anywhere in a Java program that a Java
assignment statement can appear. However, you cannot put an assignment
SQLJ iterator-conversion-clause
The iterator conversion clause converts a JDBC ResultSet to an iterator.
Syntax
CAST host-expression
Description
host-expression
Identifies the JDBC ResultSet that is to be converted to an SQLJ iterator.
Usage notes
v If the iterator to which the JDBC ResultSet is to be converted is a positioned
iterator, the number of columns in the ResultSet must match the number of
columns in the iterator. In addition, the data type of each column in the
ResultSet must be compatible with the data type of the corresponding column in
the iterator.
v If the iterator is a named iterator, the name of each accessor method must match,
except for case, the name of a column in the ResultSet. In addition, the data type
of the object that an accessor method returns must be compatible with the data
type of the corresponding column in the ResultSet.
v When an iterator that is generated through the iterator conversion clause is
closed, the ResultSet from which the iterator is generated is also closed.
Classes such as AsciiStream are used directly by the SQLJ programmer. Interfaces
such as ResultSetIterator are implemented as part of generated class declarations.
sqlj.runtime interfaces
sqlj.runtime.ConnectionContext interface
The sqlj.runtime.ConnectionContext interface provides a set of methods that
manage SQL operations that are performed during a session with a specific data
source.
Variables
CLOSE_CONNECTION
Format:
public static final boolean CLOSE_CONNECTION=true;
A constant that can be passed to the close method. It indicates that the
underlying JDBC Connection object should be closed.
KEEP_CONNECTION
Format:
public static final boolean KEEP_CONNECTION=false;
A constant that can be passed to the close method. It indicates that the
underlying JDBC Connection object should not be closed.
Methods
close()
Format:
This method is used by code that is generated by the SQLJ translator. It is not
intended for direct use by application programs.
getConnection
Format:
public abstract Connection getConnection()
Returns the underlying JDBC Connection object for the given connection
context object.
getExecutionContext
Format:
public abstract ExecutionContext getExecutionContect()
Returns the default ExecutionContext object that is associated with the given
connection context object.
isClosed
Format:
public abstract boolean isClosed()
Returns true if the given connection context object has been closed. Returns
false if the connection context object has not been closed.
Parameters:
url The representation of a data source, as specified in the JDBC getConnection
method.
autocommit
Whether autocommit is enabled for the connection. A value of true means
that autocommit is enabled. A value of false means that autocommit is
disabled.
Ctx(String, String, String, boolean)
Format:
public Ctx(String url, String user, String password,
boolean autocommit)
throws SQLException
Parameters:
url The representation of a data source, as specified in the JDBC getConnection
method.
user
The user ID under which the connection to the data source is made.
password
The password for the user ID under which the connection to the data
source is made.
autocommit
Whether autocommit is enabled for the connection. A value of true means
that autocommit is enabled. A value of false means that autocommit is
disabled.
Ctx(String, Properties, boolean)
Format:
public Ctx(String url, Properties info, boolean autocommit)
throws SQLException
Parameters:
url The representation of a data source, as specified in the JDBC getConnection
method.
info
An object that contains a set of driver properties for the connection. Any of
the IBM Data Server Driver for JDBC and SQLJ properties can be specified.
autocommit
Whether autocommit is enabled for the connection. A value of true means
that autocommit is enabled. A value of false means that autocommit is
disabled.
Parameters:
JDBC-connection-object
A previously created JDBC Connection object.
Parameters:
SQLJ-connection-context-object
A previously created SQLJ ConnectionContext object.
Parameters:
user
The user ID under which the connection to the data source is made.
password
The password for the user ID under which the connection to the data
source is made.
Ctx(Connection)
Format:
public Ctx(java.sql.Connection JDBC-connection-object)
throws SQLException
Parameters:
JDBC-connection-object
A previously created JDBC Connection object.
Parameters:
SQLJ-connection-context-object
A previously created SQLJ ConnectionContext object.
Methods
Returns the default connection context object for the Ctx class.
getProfileKey
Format:
public static Object getProfileKey(sqlj.runtime.profile.Loader loader,
String profileName) throws SQLException
This method is used by code that is generated by the SQLJ translator. It is not
intended for direct use by application programs.
getProfile
Format:
public static sqlj.runtime.profile.Profile getProfile(Object key)
This method is used by code that is generated by the SQLJ translator. It is not
intended for direct use by application programs.
getTypeMap
Format:
public static java.util.Map getTypeMap()
Sets the default connection context object for the Ctx class.
Recommendation: Do not use this method for multithreaded applications.
Instead, use explicit contexts.
Methods
getCursorName
Format:
public abstract String getCursorName() throws SQLException
This method is used by code that is generated by the SQLJ translator. It is not
intended for direct use by application programs.
sqlj.runtime.NamedIterator interface
The sqlj.runtime.NamedIterator interface is implemented when an SQLJ application
executes an iterator declaration clause for a named iterator.
A named iterator includes result table column names, and the order of the columns
in the iterator is not important.
Returns a value of true if the close method has been invoked. Returns false if
the close method has not been invoked.
next
Format:
public abstract boolean next() throws SQLException
Advances the iterator to the next row. Before an instance of the next method is
invoked for the first time, the iterator is positioned before the first row of the
result table. next returns a value of true when a next row is available and
false when all rows have been retrieved.
sqlj.runtime.PositionedIterator interface
The sqlj.runtime.PositionedIterator interface is implemented when an SQLJ
application executes an iterator declaration clause for a positioned iterator.
Methods
sqlj.runtime.ResultSetIterator interface
The sqlj.runtime.ResultSetIterator interface is implemented by SQLJ for all iterator
declaration clauses.
Variables
ASENSITIVE
Format:
public static final int ASENSITIVE
Methods
clearWarnings
Format:
public abstract void clearWarnings() throws SQLException
Returns the number of rows that should be fetched by SQLJ when more rows
are needed. The returned value is the value that was set by the setFetchSize
method, or 0 if no value was set by setFetchSize.
getResultSet
Format:
public abstract ResultSet getResultSet() throws SQLException
Returns the JDBC ResultSet object that is associated with the iterator.
Returns the current row number. The first row is number 1, the second is
number 2, and so on. If the iterator is not positioned on a row, 0 is returned.
getSensitivity
Format:
synchronized public int getSensitivity() throws SQLException
Returns the first warning that is reported by calls on the iterator. Subsequent
iterator warnings are be chained to this SQLWarning. The warning chain is
automatically cleared each time the iterator moves to a new row.
isClosed
Format:
public abstract boolean isClosed() throws SQLException
Advances the iterator to the next row. Before next is invoked for the first time,
the iterator is positioned before the first row of the result table. next returns a
value of true when a next row is available and false when all rows have been
retrieved.
setFetchSize
Format:
synchronized public void setFetchSize(int number-of-rows) throws SQLException
Gives SQLJ a hint as to the number of rows that should be fetched when more
rows are needed.
Parameters:
number-of-rows
The expected number of rows that SQLJ should fetch for the iterator that is
associated with the given execution context.
sqlj.runtime.Scrollable interface
sqlj.runtime.Scrollable provides methods to move around in the result table and to
check the position in the result table.
Methods
absolute(int)
Format:
public abstract boolean absolute (int n) throws SQLException
Moves the iterator after the last row of the result table.
beforeFirst()
Format:
public abstract void beforeFirst() throws SQLException
Moves the iterator before the first row of the result table.
first()
Format:
public abstract boolean first() throws SQLException
Returns true if the iterator is positioned before the first row of the result table.
Otherwise, returns false.
isFirst()
Format:
public abstract boolean isFirst() throws SQLException
Returns true if the iterator is positioned on the first row of the result table.
Otherwise, returns false.
isLast()
Format:
public abstract boolean isLast() throws SQLException
Returns true if the iterator is positioned on the last row of the result table.
Otherwise, returns false.
last()
Format:
public abstract boolean last() throws SQLException
If n>0, positions the iterator on the row that is n rows after the current row. If
n<0, positions the iterator on the row that is n rows before the current row. If
n=0, positions the iterator on the current row.
The cursor must be on a valid row of the result table before you can use this
method. If the cursor is before the first row or after the last throw, the method
throws an SQLException.
Suppose that m is the number of rows in the result table and x is the current
row number in the result table. If n>0 and x+n>m, the iterator is positioned
after the last row. If n<0 and x+n<1, the iterator is positioned before the first
row.
Returns true if the iterator is on a row. Otherwise, returns false.
setFetchDirection(int)
Format:
Gives the SQLJ runtime environment a hint as to the direction in which rows
of this iterator object are processed. Possible values are:
sqlj.runtime.ResultSetIterator.FETCH_FORWARD
Rows are processed in a forward direction, from first to last.
sqlj.runtime.ResultSetIterator.FETCH_REVERSE
Rows are processed in a backward direction, from last to first.
sqlj.runtime.ResultSetIterator.FETCH_UNKNOWN
The order of processing is not known.
sqlj.runtime.AsciiStream class
The sqlj.runtime.AsciiStream class is for an input stream of ASCII data with a
specified length.
Constructors
AsciiStream(InputStream)
Format:
public AsciiStream(java.io.InputStream input-stream)
sqlj.runtime.BinaryStream class
The sqlj.runtime.BinaryStream class is for an input stream of binary data with a
specified length.
sqlj.runtime.CharacterStream class
The sqlj.runtime.CharacterStream class is for an input stream of character data with
a specified length.
Constructors
CharacterStream(InputStream)
Format:
public CharacterStream(java.io.Reader input-stream)
Methods
getReader
Format:
public Reader getReader()
Sets the number of characters that are read from the Reader object when the
object is passed as an input argument to an SQL operation.
Parameters:
length
The number of characters that are read from the Reader object.
sqlj.runtime.ExecutionContext class
The sqlj.runtime.ExecutionContext class is defined for execution contexts. An
execution context is used to control the execution of SQL statements.
Variables
ADD_BATCH_COUNT
Format:
public static final int ADD_BATCH_COUNT
A constant that can be passed to the setBatchLimit method. It indicates that the
previous execution produced a result set.
UNLIMITED_BATCH
Format:
public static final int UNLIMITED_BATCH
Constructors:
ExecutionContext
Format:
public ExecutionContext()
Methods
cancel
Format:
public void cancel() throws SQLException
Executes the pending statement batch and returns an array of update counts. If
no pending statement batch exists, null is returned. When this method is
called, the statement batch is cleared, even if the call results in an exception.
Each element in the returned array can be one of the following values:
-2 This value indicates that the SQL statement executed successfully, but the
number of rows that were updated could not be determined.
-3 This value indicates that the SQL statement failed.
Other integer
This value is the number of rows that were updated by the statement.
The executeBatch method throws an SQLException if a database error occurs
while the statement batch executes.
executeQuery
Format:
public RTResultSet executeQuery ( ) throws SQLException
This method is used by code that is generated by the SQLJ translator. It is not
intended for direct use by application programs.
executeUpdate
Format:
public int executeUpdate() throws SQLException
This method is used by code that is generated by the SQLJ translator. It is not
intended for direct use by application programs.
getBatchLimit
Format:
synchronized public int getBatchLimit()
Returns the number of statements that are added to a batch before the batch is
implicitly executed.
The returned value is one of the following values:
UNLIMITED_BATCH
This value indicates that the batch size is unlimited.
AUTO_BATCH
This value indicates that the batch size is finite but unknown.
Other integer
The current batch limit.
getBatchUpdateCounts
Format:
public synchronized int[] getBatchUpdateCounts()
Returns an array that contains the number of rows that were updated by each
statement that successfully executed in a batch. The order of elements in the
Returns the current fetch direction for scrollable iterator objects that were
generated from the given execution context. If a fetch direction was not set for
the execution context, sqlj.runtime.ResultSetIterator.FETCH_FORWARD is
returned.
getFetchSize
Format:
synchronized public int getFetchSize() throws SQLException
Returns the number of rows that should be fetched by SQLJ when more rows
are needed. This value applies only to iterator objects that were generated from
the given execution context. The returned value is the value that was set by the
setFetchSize method, or 0 if no value was set by setFetchSize.
getMaxFieldSize
Format:
public synchronized int getMaxFieldSize()
Returns the maximum number of bytes that are returned for any string
(character, graphic, or varying-length binary) column in queries that use the
given execution context. If this limit is exceeded, SQLJ discards the remaining
bytes. A value of 0 means that the maximum number of bytes is unlimited.
getMaxRows
Format:
public synchronized int getMaxRows()
Returns the maximum number of rows that are returned for any query that
uses the given execution context. If this limit is exceeded, SQLJ discards the
remaining rows. A value of 0 means that the maximum number of rows is
unlimited.
getNextResultSet()
Format:
public ResultSet getNextResultSet() throws SQLException
After a stored procedure call, returns a result set from the stored procedure.
A null value is returned if any of the following conditions are true:
v There are no more result sets to be returned.
v The stored procedure call did not produce any result sets.
v A stored procedure call has not been executed under the execution context.
After a stored procedure call, returns a result set from the stored procedure.
A null value is returned if any of the following conditions are true:
v There are no more result sets to be returned.
v The stored procedure call did not produce any result sets.
v A stored procedure call has not been executed under the execution context.
If an error occurs during a call to getNextResultSet, resources for the current
JDBC ResultSet object are released, and an SQLException is thrown.
Subsequent calls to getNextResultSet return null.
Parameters:
current
Indicates what SQLJ does with the currently open result set before it
advances to the next result set:
java.sql.Statement.CLOSE_CURRENT_RESULT
Specifies that the current ResultSet object is closed when the next
ResultSet object is returned.
java.sql.Statement.KEEP_CURRENT_RESULT
Specifies that the current ResultSet object stays open when the next
ResultSet object is returned.
java.sql.Statement.CLOSE_ALL_RESULTS
Specifies that all open ResultSet objects are closed when the next
ResultSet object is returned.
getQueryTimeout
Format:
public synchronized int getQueryTimeout()
Returns the maximum number of seconds that SQL operations that use the
given execution context object can execute. If an SQL operation exceeds the
limit, an SQLException is thrown. The returned value is the value that was set
by the setQueryTimeout method, or 0 if no value was set by setQueryTimeout.
0 means that execution time is unlimited.
getUpdateCount
Format:
public abstract int getUpdateCount() throws SQLException
Returns:
ExecutionContext.ADD_BATCH_COUNT
If the statement was added to an existing batch.
ExecutionContext.NEW_BATCH_COUNT
If the statement was the first statement in a new batch.
Returns the first warning that was reported by the last SQL operation that was
executed using the given execution context. Subsequent warnings are chained
to the first warning. If no warnings occurred, null is returned.
getWarnings is used to retrieve positive SQLCODEs.
isBatching
Format:
public synchronized boolean isBatching()
Returns true if batching is enabled for the execution context. Returns false if
batching is disabled.
registerStatement
Format:
public RTStatement registerStatement(ConnectionContext connCtx,
Object profileKey, int stmtNdx)
throws SQLException
This method is used by code that is generated by the SQLJ translator. It is not
intended for direct use by application programs.
releaseStatement
Format:
public void releaseStatement() throws SQLException
This method is used by code that is generated by the SQLJ translator. It is not
intended for direct use by application programs.
setBatching
Format:
public synchronized void setBatching(boolean batching)
Parameters:
batching
Indicates whether batchable statements that are registered with the given
execution context can be added to a statement batch:
true
Statements can be added to a statement batch.
Sets the maximum number of statements that are added to a batch before the
batch is implicitly executed.
Parameters:
batch-size
One of the following values:
ExecutionContext.UNLIMITED_BATCH
Indicates that implicit execution occurs only when SQLJ encounters a
statement that is batchable but incompatible, or not batchable. Setting
this value is the same as not invoking setBatchLimit.
ExecutionContext.AUTO_BATCH
Indicates that implicit execution occurs when the number of statements
in the batch reaches a number that is set by SQLJ.
Positive integer
The number of statements that are added to the batch before SQLJ
executes the batch implicitly. The batch might be executed before this
many statements have been added if SQLJ encounters a statement that
is batchable but incompatible, or not batchable.
Gives SQLJ a hint as to the current fetch direction for scrollable iterator objects
that were generated from the given execution context.
Parameters:
direction
One of the following values:
sqlj.runtime.ResultSetIterator.FETCH_FORWARD
Rows are fetched in a forward direction. This is the default.
sqlj.runtime.ResultSetIterator.FETCH_REVERSE
Rows are fetched in a backward direction.
sqlj.runtime.ResultSetIterator.FETCH_UNKNOWN
The order of fetching is unknown.
Specifies the maximum number of bytes that are returned for any string
(character, graphic, or varying-length binary) column in queries that use the
given execution context. If this limit is exceeded, SQLJ discards the remaining
bytes.
Parameters:
max-bytes
The maximum number of bytes that SQLJ should return from a BINARY,
VARBINARY, CHAR, VARCHAR, GRAPHIC, or VARGRAPHIC column. A
value of 0 means that the number of bytes is unlimited. 0 is the default.
setMaxRows
Format:
public synchronized void setMaxRows(int max-rows)
Specifies the maximum number of rows that are returned for any query that
uses the given execution context. If this limit is exceeded, SQLJ discards the
remaining rows.
Parameters:
max-rows
The maximum number of rows that SQLJ should return for a query that
uses the given execution context. A value of 0 means that the number of
rows is unlimited. 0 is the default.
setQueryTimeout
Format:
public synchronized void setQueryTimeout(int timeout-value)
Specifies the maximum number of seconds that SQL operations that use the
given execution context object can execute. If an SQL operation exceeds the
limit, an SQLException is thrown.
Parameters:
timeout-value
The maximum number of seconds that SQL operations that use the given
execution context object can execute. 0 means that execution time is
unlimited. 0 is the default.
sqlj.runtime.StreamWrapper class
The sqlj.runtime.StreamWrapper class wraps a java.io.InputStream instance and
extends the java.io.InputStream class.
Constructors
StreamWrapper(InputStream)
Format:
protected StreamWrapper(InputStream input-stream)
Methods
getInputStream
Format:
public InputStream getInputStream()
Sets the number of bytes that are read from the wrapped InputStream object
when the object is passed as an input argument to an SQL operation.
Parameters:
length
The number of bytes that are read from the wrapped InputStream object.
sqlj.runtime.UnicodeStream class
The sqlj.runtime.UnicodeStream class is for an input stream of Unicode data with a
specified length.
Constructors
UnicodeStream(InputStream)
Format:
public UnicodeStream(java.io.InputStream input-stream)
IBM Data Server Driver for JDBC and SQLJ extensions to JDBC
The IBM Data Server Driver for JDBC and SQLJ provides a set of extensions to the
support that is provided by the JDBC specification.
Table 104 summarizes the IBM Data Server Driver for JDBC and SQLJ-only
interfaces.
Table 104. Summary of IBM Data Server Driver for JDBC and SQLJ-only interfaces provided by the IBM Data Server
Driver for JDBC and SQLJ
Interface name Applicable data sources Purpose
DB2CallableStatement 2 Extends the java.sql.CallableStatement and the
com.ibm.db2.jcc.DB2PreparedStatement interfaces.
DB2Connection 1, 2, 3 Extends the java.sql.Connection interface.
DB2DatabaseMetaData 1, 2, 3 Extends the java.sql.DatabaseMetaData interface.
DB2Diagnosable 1, 2, 3 Provides a mechanism for getting DB2
diagnostics from a DB2 SQLException.
DB2ParameterMetaData 2 Extends the java.sql.ParameterMetaData interface.
DB2PreparedStatement 1, 2, 3 Extends the com.ibm.db2.jcc.DB2Statement and
java.sql.PreparedStatement interfaces.
DB2ResultSet 1, 2, 3 Extends the java.sql.ResultSet interface.
DB2RowID 1, 2 Used for declaring Java objects for use with the
ROWID data type.
DB2Statement 1, 2, 3 Extends the java.sql.Statement interface.
DB2SystemMonitor 1, 2, 3 Used for collecting system monitoring data for a
connection.
DB2TraceManagerMXBean 1, 2, 3 Provides the MBean interface for the remote trace
controller.
DB2Xml 1, 2 Used for updating data in XML columns and
retrieving data from XML columns.
DBBatchUpdateException 1, 2, 3 Used for retrieving error information about batch
execution of statements that return automatically
generated keys.
Note: The interface applies to connections to the following data sources:
1. DB2 for z/OS
2. DB2 Database for Linux, UNIX, and Windows
3. IBM Informix
Table 105 summarizes the IBM Data Server Driver for JDBC and SQLJ-only classes.
Table 105. Summary of IBM Data Server Driver for JDBC and SQLJ-only classes provided by the IBM Data Server
Driver for JDBC and SQLJ
Class name Applicable data sources Purpose
DB2Administrator (DB2 Database 2 on page 389 Instances of the DB2Administrator class are used
for Linux, UNIX, and Windows to retrieve DB2CataloguedDatabase objects.
only)
DBBatchUpdateException interface
The com.ibm.db2.jcc.DBBatchUpdateException interface is used for retrieving error
information about batch execution of statements that return automatically
generated keys.
DBBatchUpdateException methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getDBGeneratedKeys
Format:
DB2Administrator class
Instances of the com.ibm.db2.jcc.DB2Administrator class are used to retrieve
DB2CataloguedDatabase objects. DB2Administrator applies to DB2 Database for
Linux, UNIX, and Windows databases only.
DB2Administrator methods
getInstance
Format:
public static DB2Administrator getInstance()
DB2BaseDataSource class
The com.ibm.db2.jcc.DB2BaseDataSource class is the abstract data source parent
class for all IBM Data Server Driver for JDBC and SQLJ-specific implementations
of javax.sql.DataSource, javax.sql.ConnectionPoolDataSource, and
javax.sql.XADataSource.
DB2BaseDataSource properties
The following properties are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
All properties except the following properties have a setXXX method to set the
value of the property and a getXXX method to retrieve the value:
v minTransportObjects
v maxTransportObjectIdleTime
v maxTransportObjectWaitTime
v dumpPool
v dumpPoolStatisticsOnSchedule
390 Developing Java Applications
v dumpPoolStatisticsOnScheduleFile
Property-name is the unqualified property name. For properties that are not specific
to IBM Informix, the first character of the property name is capitalized. For
properties that are used only by IBM Informix, all characters of the property name
are capitalized.
The following table lists the IBM Data Server Driver for JDBC and SQLJ properties
and their data types.
Table 106. DB2BaseDataSource properties and their data types
Applicable data
Property name sources Data type
com.ibm.db2.jcc.DB2BaseDataSource.accountingInterval 1 on page 396 String
com.ibm.db2.jcc.DB2BaseDataSource.affinityFailbackInterval 1 on page 396, 2 int
on page 396, 3
on page 396
com.ibm.db2.jcc.DB2BaseDataSource.allowNextOnExhaustedResultSet 1 on page 396, 2 int
on page 396, 3
on page 396
com.ibm.db2.jcc.DB2BaseDataSource.allowNullResultSetForExecuteQuery 1 on page 396, 2 int
on page 396, 3
on page 396
com.ibm.db2.jcc.DB2BaseDataSource.atomicMultiRowInsert 1 on page 396, 2 int
on page 396, 3
on page 396
com.ibm.db2.jcc.DB2BaseDataSource.blockingReadConnectionTimeout 1 on page 396, 2 int
on page 396, 3
on page 396
com.ibm.db2.jcc.DB2BaseDataSource.charOutputSize 1 on page 396 short
com.ibm.db2.jcc.DB2BaseDataSource.clientAccountingInformation 1 on page 396, 2 String
on page 396
com.ibm.db2.jcc.DB2BaseDataSource.clientApplicationInformation 1 on page 396, 2 String
on page 396
com.ibm.db2.jcc.DB2BaseDataSource.clientDebugInfo (IBM Data Server Driver for JDBC 1 on page 396, 2 String
and SQLJ type 4 connectivity) on page 396
com.ibm.db2.jcc.DB2BaseDataSource.clientProgramId 1 on page 396, 2 String
on page 396
com.ibm.db2.jcc.DB2BaseDataSource.clientProgramName (IBM Data Server Driver for 1 on page 396, 2 String
JDBC and SQLJ type 4 connectivity) on page 396
com.ibm.db2.jcc.DB2BaseDataSource.clientRerouteAlternateServerName 1 on page 396, 2 String
on page 396, 3
on page 396
com.ibm.db2.jcc.DB2BaseDataSource.clientRerouteAlternatePortNumber 1 on page 396, 2 String
on page 396, 3
on page 396
com.ibm.db2.jcc.DB2BaseDataSource.clientRerouteServerListJNDIContext 1 on page 396, 2 javax.naming.Context
on page 396, 3
on page 396
DB2BaseDataSource fields
The following constants are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
public final static int INTERRUPT_PROCESSING_MODE_DISABLED = 0
A constant for the interruptProcessingMode property. This value indicates that
interrupt processing is disabled.
public final static int
INTERRUPT_PROCESSING_MODE_STATEMENT_CANCEL = 1
A constant for the interruptProcessingMode property. This value indicates that
the IBM Data Server Driver for JDBC and SQLJ cancels the currently executing
statement when an application executes Statement.cancel, if the data server
supports interrupt processing.
DB2BaseDataSource methods
DB2CallableStatement interface
The com.ibm.db2.jcc.DB2CallableStatement interface extends the
java.sql.CallableStatement and the com.ibm.db2.jcc.DB2PreparedStatement
interfaces.
DB2CallableStatement methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getJccArrayAtName
Format:
public java.sql.Array getJccArrayAtName(String parameterMarkerName)
throws java.sql.SQLException
DB2CataloguedDatabase class
The com.ibm.db2.jcc.DB2CataloguedDatabase class contains methods that retrieve
information about a local DB2 Database for Linux, UNIX, and Windows database.
DB2CataloguedDatabase methods
getServerName
Format:
public String getServerName()
Retrieves the port number that is associated with the DB2 instance.
getDatabaseName
Format:
public String getDatabaseName()
DB2ClientRerouteServerList class
The com.ibm.db2.jcc.DB2ClientRerouteServerList class implements the
java.io.Serializable and javax.naming.Referenceable interfaces.
DB2ClientRerouteServerList methods
getAlternatePortNumber
Format:
public int[] getAlternatePortNumber()
Retrieves the port numbers that are associated with the alternate servers.
getAlternateServerName
Format:
public String[] getAlternateServerName()
Retrieves an array that contains the names of the alternate servers. These
values are IP addresses or DNS server names.
getPrimaryPortNumber
Format:
public int getPrimaryPortNumber()
Retrieves the port number that is associated with the primary server.
getPrimaryServerName
Format:
public String[] getPrimaryServerName()
Retrieves the name of the primary server. This value is an IP address or a DNS
server name.
setAlternatePortNumber
Format:
public void setAlternatePortNumber(int[] alternatePortNumberList)
Sets the port numbers that are associated with the alternate servers.
Sets the alternate server names for servers. These values are IP addresses or
DNS server names.
setPrimaryPortNumber
Format:
public void setPrimaryPortNumber(int primaryPortNumber)
Sets the port number that is associated with the primary server.
setPrimaryServerName
Format:
public void setPrimaryServerName(String primaryServer)
Sets the primary server name for a server. This value is an IP address or a
DNS server name.
DB2Connection interface
The com.ibm.db2.jcc.DB2Connection interface extends the java.sql.Connection
interface.
DB2Connection methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
alternateWasUsedOnConnect
Format:
public boolean alternateWasUsedOnConnect()
throws java.sql.SQLException
Returns true if the driver used alternate server information to obtain the
connection. The alternate server information is available in the transient
clientRerouteServerList information on the DB2BaseDataSource, which the
database server updates as primary and alternate servers change.
changeDB2Password
Format:
public abstract void changeDB2Password(String oldPassword,
String newPassword)
throws java.sql.SQLException
Changes the password for accessing the data source, for the user of the
Connection object.
Parameter descriptions:
oldPassword
The original password for the Connection.
newPassword
The new password for the Connection.
Returns the user-defined program identifier for the client. The program
identifier can be used to identify the application at the data source.
getDB2ClientProgramId does not apply to DB2 Database for Linux, UNIX, and
Windows data servers.
getDB2ClientAccountingInformation
Format:
public String getDB2ClientAccountingInformation()
throws SQLException
Returns the current client user name for the connection. This name is not the
user value for the JDBC connection.
Important: getDB2ClientUser is deprecated in the JDBC 4.0 implementation of
the IBM Data Server Driver for JDBC and SQLJ. Use
java.sql.Connection.getClientInfo instead.
getDB2ClientWorkstation
Format:
public String getDB2ClientWorkstation()
throws java.sql.SQLException
Returns the value of the crrtkn (correlation token) instance variable that DRDA
sends with the ACCRDB command. The correlation token uniquely identifies a
logical connection to a server.
getDB2CurrentPackagePath
Format:
public String getDB2CurrentPackagePath()
throws java.sql.SQLException
Returns the list of DB2 package collections that are searched for JDBC and
SQLJ packages.
The getDB2CurrentPackagePath method applies only to connections to DB2
database systems.
getDB2CurrentPackageSet
Format:
public String getDB2CurrentPackageSet()
throws java.sql.SQLException
Returns the system monitor object for the connection. Each IBM Data Server
Driver for JDBC and SQLJ connection can have a single system monitor.
getDBProgressiveStreaming
Format:
public int getDB2ProgressiveStreaming()
throws java.sql.SQLException
Returns the statement concentrator use setting for the connection. The
statement concentrator use setting is set by the setDBStatementConcentrator
method or by the statementConcentrator property.
getJccLogWriter
Format:
public PrintWriter getJccLogWriter()
throws java.sql.SQLException
Returns the current trace destination for the IBM Data Server Driver for JDBC
and SQLJ trace.
getJccSpecialRegisterProperties
Format:
public java.util.Properties getJccSpecialRegisterProperties()
throws java.sql.SQLException
Returns a java.util.Properties object, in which the keys are the special registers
that are supported at the target data source, and the key values are the current
values of those special registers.
This method does not apply to connections to IBM Informix data sources.
getSavePointUniqueOption
Format:
public boolean getSavePointUniqueOption()
throws java.sql.SQLException
Returns true if the socket for a connection to the data source is still active.
Important: isDB2Alive is deprecated in the JDBC 4.0 implementation of the
IBM Data Server Driver for JDBC and SQLJ. Use Connection.isDBValid instead.
isDBValid
Format:
public boolean DB2Connection.isDBValid(boolean throwException, int timeout)
throws java.sql.SQLException
Returns true if the connection has not been closed and is still valid. Returns
false otherwise.
Parameter descriptions:
throwException
Specifies whether isDBValid throws an SQLException if the connection is
not valid. Possible values are:
true isDBValid throws an SQLException if the connection is not valid.
false isDBValid throws an SQLException only if the value of timeout is
less than 0.
timeout
The time in seconds to wait for a database operation that the driver
submits to complete. The driver submits that database operation to the
data source to validate the connection. If the timeout period expires before
the database operation completes, isDBValid returns false. A value of 0
indicates that there is no timeout period for the database operation.
This method does not apply to connections to IBM Informix data sources.
prepareDB2OptimisticLockingQuery
Format:
reconfigureDB2Connection
Format:
public void reconfigureDB2Connection(java.util.Properties properties)
throws SQLException
Reconfigures a connection with new settings. The connection does not need to
be returned to a connection pool before it is reconfigured. This method can be
called while a transaction is in progress, and can be used for trusted or
untrusted connections.
Trusted connections are supported for:
v IBM Data Server Driver for JDBC and SQLJ type 4 connectivity to:
– DB2 Database for Linux, UNIX, and Windows Version 9.5 or later
– DB2 for z/OS Version 9.1 or later
– IBM Informix Version 11.70 or later
v IBM Data Server Driver for JDBC and SQLJ type 2 connectivity on DB2 for
z/OS Version 9.1 or later
Parameter descriptions:
properties
New properties for the connection. These properties override any
properties that are already defined on the DB2Connection instance.
registerDB2XmlSchema
Formats:
public void registerDB2XmlSchema(String[] sqlIdSchema,
String[] sqlIdName,
String[] xmlSchemaLocations,
InputStream[] xmlSchemaDocuments,
int[] xmlSchemaDocumentsLengths,
Sets the progressive streaming setting for all ResultSet objects that are created
on the connection.
Parameter descriptions:
newSetting
The new progresssive streaming setting. Possible values are:
DB2BaseDataSource.YES (1)
Enable progressive streaming. If the data source does not support
progressive streaming, this setting has no effect.
DB2BaseDataSource.NO (2)
Disable progressive streaming.
updateDB2XmlSchema
Format:
public void updateDB2XmlSchema(String[] targetSqlIdSchema,
String[] targetSqlIdName,
String[] sourceSqlIdSchema,
Updates the contents of an XML schema with the contents of another XML
schema in the XML schema repository, and optionally drops the source
schema. The schema documents in the target XML schema are replaced with
the schema documents from the source XML schema. Before
updateDB2XmlSchema can be called, registration of the source and target XML
schemas must be completed.
The SQL ALTERIN privilege is required for updating the target XML schema.
The SQL DROPIN privilege is required for dropping the source XML schema.
Parameter descriptions:
targetSqlIdSchema
The SQL schema name for a registered XML schema that is to be updated.
targetSqlIdSchema is a String value with a maximum length of 128 bytes.
targetSqlIdName
The name of the registered XML schema that is to be updated.
targetSqlIdName is a String value with a maximum length of 128 bytes.
sourceSqlIdSchema
The SQL schema name for a registered XML schema that is used to update
the target XML schema. sourceSqlIdSchema is a String value with a
maximum length of 128 bytes.
sourceSqlIdName
The name of the registered XML schema that is used to update the target
XML schema. sourceSqlIdName is a String value with a maximum length of
128 bytes.
dropSourceSchema
Indicates whether the source XML schema is to be dropped after the target
XML schema is updated. dropSourceSchema is a boolean value. false is the
default.
This method does not apply to connections to IBM Informix data sources.
removeDB2JavaStoredProcedure
Format:
public void DB2Connection.removeDB2JavaStoredProcedure(
String jarId)
throws java.sql.SQLException
Sets a value for the CLIENT DEBUGINFO connection attribute, to notify the
database system that stored procedures and user-defined functions that are
using the connection are running in debug mode. CLIENT DEBUGINFO is
used by the DB2 Unified Debugger. Use the first form to set the entire CLIENT
DEBUGINFO string. Use the second form to modify only the session manager
and trace information in the CLIENT DEBUGINFO string.
Setting the CLIENT DEBUGINFO attribute to a string of length greater than
zero requires one of the following privileges:
v The DEBUGSESSION privilege
v SYSADM authority
Parameter description:
For example:
M9.72.133.89:8355,I9.72.133.89,P4552,T123,C1,L0
For example:
M9.72.133.89:8355
For example:
L0
Sets a user-defined program identifier for the connection, on DB2 for z/OS
servers. That program identifier is an 80-byte string that is used to identify the
caller.
setDB2ClientProgramId does not apply to DB2 Database for Linux, UNIX, and
Windows or IBM Informix data servers.
Specifies the current client user name for the connection. This name is for
client accounting purposes, and is not the user value for the JDBC connection.
Unlike the user for the JDBC connection, the current client user name can
change during a connection.
Parameter description:
user
The user ID for the current client. The maximum length depends on the
server. For a DB2 Database for Linux, UNIX, and Windows server, the
maximum length is 255 bytes. For a DB2 for z/OS server, the maximum
length is 16 bytes. A Java empty string ("") is valid for this parameter
value, but a Java null value is not valid.
Important: setDB2ClientUser is deprecated in the JDBC 4.0 implementation of
the IBM Data Server Driver for JDBC and SQLJ. Use
java.sql.Connection.setClientInfo instead.
setDB2ClientWorkstation
Format:
public void setDB2ClientWorkstation(String name)
throws java.sql.SQLException
Specifies the current client workstation name for the connection. This name is
for client accounting purposes. The current client workstation name can change
during a connection.
Parameter description:
name
The workstation name for the current client. The maximum length depends
on the server. For a DB2 Database for Linux, UNIX, and Windows server,
the maximum length is 255 bytes. For a DB2 for z/OS server, the
maximum length is 18 bytes. A Java empty string ("") is valid for this
parameter value, but a Java null value is not valid.
Important: getDB2ClientWorkstation is deprecated in the JDBC 4.0
implementation of the IBM Data Server Driver for JDBC and SQLJ. Use
java.sql.Connection.getClientInfo instead.
setDB2CurrentPackagePath
Format:
public void setDB2CurrentPackagePath(String packagePath)
throws java.sql.SQLException
Specifies a list of collection IDs that the database system searches for JDBC and
SQLJ packages.
The setDB2CurrentPackagePath method applies only to connections to DB2
database systems.
Parameter description:
Specifies the collection ID for the connection. When you set this value, you
also set the collection ID of the IBM Data Server Driver for JDBC and SQLJ
instance that is used for the connection.
The setDB2CurrentPackageSet method applies only to connections to DB2
database systems.
Parameter description:
packageSet
The collection ID for the connection. The maximum length for the
packageSet value is 18 bytes. You can invoke this method as an alternative
to executing the SQL SET CURRENT PACKAGESET statement in your
program.
setDB2ProgressiveStreaming
Format:
public void setDB2ProgressiveStreaming(int newSetting)
throws java.sql.SQLException
Sets the progressive streaming setting for all ResultSet objects that are created
on the connection.
Parameter descriptions:
newSetting
The new progresssive streaming setting. Possible values are:
DB2BaseDataSource.YES (1)
Enable progressive streaming. If the data source does not support
progressive streaming, this setting has no effect.
DB2BaseDataSource.NO (2)
Disable progressive streaming.
setJccLogWriter
Formats:
public void setJccLogWriter(PrintWriter logWriter)
throws java.sql.SQLException
Enables or disables the IBM Data Server Driver for JDBC and SQLJ trace, or
changes the trace destination during an active connection.
Parameter descriptions:
logWriter
An object of type java.io.PrintWriter to which the IBM Data Server Driver
for JDBC and SQLJ writes trace output. To turn off the trace, set the value
of logWriter to null.
DB2ConnectionPoolDataSource class
DB2ConnectionPoolDataSource is a factory for PooledConnection objects. An object
that implements this interface is registered with a naming service that is based on
the Java Naming and Directory Interface (JNDI).
DB2ConnectionPoolDataSource properties
These properties are defined only for the IBM Data Server Driver for JDBC and
SQLJ. "Properties for the IBM Data Server Driver for JDBC and SQLJ" for
explanations of these properties.
These properties have a setXXX method to set the value of the property and a
getXXX method to retrieve the value. A setXXX method has this form:
void setProperty-name(data-type property-value)
Property-name is the unqualified property name, with the first character capitalized.
DB2ConnectionPoolDataSource methods
getDB2PooledConnection
Formats:
public DB2PooledConnection getDB2PooledConnection(String user,
String password,
java.util.Properties properties)
throws java.sql.SQLException
public DB2PooledConnection getDB2PooledConnection(
org.ietf.jgss.GSSCredential gssCredential,
java.util.Properties properties)
throws java.sql.SQLException
DB2DatabaseMetaData interface
The com.ibm.db2.jcc.DB2DatabaseMetaData interface extends the
java.sql.DatabaseMetaData interface.
DB2DatabaseMetaData methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
isIDSDatabaseAnsiCompliant
Format:
public boolean isIDSDatabaseAnsiCompliant();
Returns true if the target database server requires clean reuse to support
eWLM. Returns false otherwise.
supportsDB2ProgressiveStreaming
Format:
public boolean supportsDB2ProgressiveStreaming();
Returns true if the target data source supports progressive streaming. Returns
false otherwise.
DB2Diagnosable interface
The com.ibm.db2.jcc.DB2Diagnosable interface provides a mechanism for getting
DB2 diagnostics from an SQLException.
DB2Diagnosable methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getSqlca
Format:
public DB2Sqlca getSqlca();
DB2ExceptionFormatter class
The com.ibm.db2.jcc.DB2ExceptionFormatter class contains methods for printing
diagnostic information to a stream.
DB2ExceptionFormatter methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
printTrace
Formats:
static public void printTrace(java.sql.SQLException sqlException,
java.io.PrintWriter printWriter, String header)
DB2FileReference class
The com.ibm.db2.jcc.DB2FileReference class is an abstract class that defines
methods that support insertion of data into tables from file reference variables.
This class applies only to IBM Data Server Driver for JDBC and SQLJ type 2
connectivity to DB2 for z/OS Version 9 or later.
DB2FileReference fields
The following constants define types codes only for the IBM Data Server Driver for
JDBC and SQLJ.
public static final short MAX_FILE_NAME_LENGTH = 255
The maximum length of the file name for a file reference variable.
DB2FileReference methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getDriverType
Format:
public int getDriverType()
Returns the encoding of the data in the file for a DB2FileReference object.
getFileName
Format:
public String getFileName()
Returns the CCSID of the data in the file for a DB2FileReference object.
setFileName
Format:
public String setFileName(String fileName)
throws java.sql.SQLException
DB2JCCPlugin class
The com.ibm.db2.jcc.DB2JCCPlugin class is an abstract class that defines methods
that can be implemented to provide DB2 Database for Linux, UNIX, and Windows
plug-in support. This class applies only to DB2 Database for Linux, UNIX, and
Windows.
DB2JCCPlugin methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getTicket
Format:
public abstract byte[] getTicket(String user,
String password,
byte[] returnedToken)
throws org.ietf.jgss.GSSException
DB2ParameterMetaData interface
The com.ibm.db2.jcc.DB2ParameterMetaData interface extends the
java.sql.ParameterMetaData interface.
DB2ParameterMetaData methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getParameterMarkerNames
Format:
public String[] getParameterMarkerNames()
throws java.sql.SQLException
Returns a list of the parameter marker names that are used in an SQL
statement.
This method returns null if the enableNamedParameterMarkers property is set
DB2BaseDataSource.NOT_SET or DB2BaseDataSource.NO, or if there are no
named parameter markers in the SQL statement.
getProcedureParameterName
Format:
public String getProcedureParameterName(int param)
throws java.sql.SQLException
DB2PooledConnection class
The com.ibm.db2.jcc.DB2PooledConnection class provides methods that an
application server can use to switch users on a preexisting trusted connection.
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getConnection (untrusted or trusted reuse without reauthentication)
Format:
public DB2Connection getConnection()
throws java.sql.SQLException
This method is for dirty reuse of a connection. This means that the connection
state is not reset when the object is reused from the pool. Special register
settings and property settings remain in effect unless they are overridden by
passed properties. Global temporary tables are not deleted. Properties that are
not specified are not re-initialized. All JDBC standard transient properties, such
as the isolation level, autocommit mode, and read-only mode are reset to their
JDBC defaults. Certain properties, such as user, password, databaseName,
serverName, portNumber, planName, and pkList remain unchanged.
getDB2Connection (trusted reuse)
Formats:
public DB2Connection getDB2Connection(byte[] cookie,
String user,
String password,
String userRegistry,
byte[] userSecToken,
String originalUser,
java.util.Properties properties)
throws java.sql.SQLException
public Connection getDB2Connection(byte[] cookie,
org.ietf.GSSCredential gssCredential,
String usernameRegistry,
byte[] userSecToken,
String originalUser,
java.util.Properties properties)
throws java.sql.SQLException
DB2PoolMonitor class
The com.ibm.db2.jcc.DB2PoolMonitor class provides methods for monitoring the
global transport objects pool that is used for the connection concentrator and
Sysplex workload balancing.
DB2PoolMonitor fields
The following fields are defined only for the IBM Data Server Driver for JDBC and
SQLJ.
public static final int TRANSPORT_OBJECT = 1
This value is a parameter for the DB2PoolMonitor.getPoolMonitor method.
DB2PoolMonitor methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
agedOutObjectCount
Format:
public abstract int agedOutObjectCount()
Retrieves the number of objects that exceeded the idle time that was specified
by db2.jcc.maxTransportObjectIdleTime and were deleted from the pool.
createdObjectCount
Format:
public abstract int createdObjectCount()
Retrieves the number of objects that the IBM Data Server Driver for JDBC and
SQLJ created since the pool was created.
getMonitorVersion
Format:
public int getMonitorVersion()
Retrieves the number of objects that were reused from the pool.
lightWeightReusedObjectCount
Format:
public abstract int lightWeightReusedObjectCount()
Retrieves the number of objects that were reused but were not in the pool. This
can happen if a Connection object releases a transport object at a transaction
boundary. If the Connection object needs a transport object later, and the
original transport object has not been used by any other Connection object, the
Connection object can use that transport object.
longestBlockedRequestTime
Format:
public abstract long longestBlockedRequestTime()
Retrieves the number of times that the release of a connection was refused.
numberOfRequestsBlocked
Format:
public abstract int numberOfRequestsBlocked()
Retrieves the number of requests that the IBM Data Server Driver for JDBC
and SQLJ made to the pool that the pool blocked because the pool reached its
maximum capacity. A blocked request might be successful if an object is
returned to the pool before the db2.jcc.maxTransportObjectWaitTime is
exceeded and an exception is thrown.
numberOfRequestsBlockedDataSourceMax
Format:
public abstract int numberOfRequestsBlockedDataSourceMax()
Retrieves the number of requests that the IBM Data Server Driver for JDBC
and SQLJ made to the pool that the pool blocked because the maximum
number for the pool was reached.
removedObjectCount
Format:
public abstract int removedObjectCount()
Retrieves the number of objects that have been deleted from the pool since the
pool was created.
shortestBlockedRequestTime
Format:
public abstract long shortestBlockedRequestTime()
Retrieves the number of successful requests that the IBM Data Server Driver
for JDBC and SQLJ has made to the pool since the pool was created. A
successful request means that the pool returned an object.
totalPoolObjects
Format:
public abstract int totalPoolObjects()
Retrieves the total number of requests that the IBM Data Server Driver for
JDBC and SQLJ has made to the pool since the pool was created.
totalTimeBlocked
Format:
public abstract long totalTimeBlocked()
Retrieves the total time in milliseconds for requests that were blocked by the
pool. This time can be much larger than the elapsed execution time of the
application if the application uses multiple threads.
DB2PreparedStatement interface
The com.ibm.db2.jcc.DB2PreparedStatement interface extends the
com.ibm.db2.jcc.DB2Statement and java.sql.PreparedStatement interfaces.
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
executeDB2QueryBatch
Format:
public void executeDB2QueryBatch()
throws java.sql.SQLException
Returns the estimated cost of an SQL statement from the data server after the
data server dynamically prepares the statement successfully. This value is the
same as the fourth element in the sqlerrd array of the SQLCA.
If the deferPrepares property is set to true, calling getEstimateCost causes the
data server to execute a dynamic prepare operation.
If the SQL statement cannot be prepared, or the data server does not return
estimated cost information at prepare time, getEstimateCost returns -1.
getEstimateRowCount
Format:
public int getEstimateRowCount()
throws java.sql.SQLException
Supported by the IBM Data Server Driver for JDBC and SQLJ version 4.7 and
later:
public void setJccAsciiStreamAtName(String parameterMarkerName,
java.io.InputStream x)
throws java.sql.SQLException
public void setJccAsciiStreamAtName(String parameterMarkerName,
java.io.InputStream x, long length)
throws java.sql.SQLException
Supported by the IBM Data Server Driver for JDBC and SQLJ version 4.7 and
later:
public void setJccBinaryStreamAtName(String parameterMarkerName,
java.io.InputStream x)
throws java.sql.SQLException
public void setJccBinaryStreamAtName(String parameterMarkerName,
java.io.InputStream x, long length)
throws java.sql.SQLException
Supported by the IBM Data Server Driver for JDBC and SQLJ version 4.7 and
later:
public void setJccCharacterStreamAtName(String parameterMarkerName,
java.io.Reader x)
throws java.sql.SQLException
public void setJccCharacterStreamAtName(String parameterMarkerName,
java.io.Reader x, long length)
throws java.sql.SQLException
Supported by the IBM Data Server Driver for JDBC and SQLJ version 4.7 and
later:
DB2ResultSet interface
The com.ibm.db2.jcc.DB2ResultSet interface is used to create objects from which
IBM Data Server Driver for JDBC and SQLJ-only query information can be
obtained.
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getDB2RowChangeToken
Format:
public long DB2ResultSet.getDB2RowChangeToken()
throws java.sql.SQLException
Returns the row change token for the current row, if it is available. Returns 0 if
optimistic locking columns were not requested or are not available.
This method applies only to connections to DB2 Database for Linux, UNIX,
and Windows.
getDB2RID
Format:
public Object DB2ResultSet.getDB2RID()
throws java.sql.SQLException
Returns the RID for the current row, if it is available. The RID is available if
optimistic locking columns were requested and are available. Returns null if
optimistic locking columns were not requested or are not available.
This method applies only to connections to DB2 Database for Linux, UNIX,
and Windows.
getDB2RIDType
Format:
public int DB2ResultSet.getDB2RIDType()
throws java.sql.SQLException
Returns the data type of the RID column in a DB2ResultSet. The returned
value maps to a java.sql.Types constant. If the DB2ResultSet does not contain
a RID column, java.sql.Types.NULL is returned.
This method applies only to connections to DB2 Database for Linux, UNIX,
and Windows.
DB2ResultSetMetaData interface
The com.ibm.db2.jcc.DB2ResultSetMetaData interface provides methods that
provide information about a ResultSet object.
DB2ResultSetMetaData methods:
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getDB2OptimisticLockingColumns
Format:
public int getDB2OptimisticLockingColumns()
throws java.sql.SQLException
Returns true if the name of a ResultSet column is in the SQL SELECT list that
generated the ResultSet.
For example, suppose that a ResultSet is generated from the SQL statement
SELECT EMPNAME, SUM(SALARY) FROM EMP. Column name EMPNAME
is derived from the SQL SELECT list, but the name of the column in the
ResultSet that corresponds to SUM(SALARY) is not derived from the SELECT
list.
Parameter descriptions:
column
The name of a column in the ResultSet.
DB2RowID interface
The com.ibm.db2.jcc.DB2RowID interface is used for declaring Java objects for use
with the SQL ROWID data type.
DB2RowID methods
The following method is defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getBytes
Format:
public byte[] getBytes()
DB2SimpleDataSource class
The com.ibm.db2.jcc.DB2SimpleDataSource class extends the DB2BaseDataSource
class.
The following property is defined only for the IBM Data Server Driver for JDBC
and SQLJ. See "Properties for the IBM Data Server Driver for JDBC and SQLJ" for
an explanation of this property.
String com.ibm.db2.jcc.DB2SimpleDataSource.password
DB2SimpleDataSource methods
The following method is defined only for the IBM Data Server Driver for JDBC
and SQLJ.
setPassword
Format:
public void setPassword(String password)
DB2Sqlca class
The com.ibm.db2.jcc.DB2Sqlca class is an encapsulation of the SQLCA.
DB2Sqlca methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
getMessage
Format:
public abstract String getMessage()
Returns a string that contains the SQLCA SQLERRMC values, delimited with
spaces.
getSqlErrmcTokens
Format:
public abstract String[] getSqlErrmcTokens()
DB2Statement interface
The com.ibm.db2.jcc.DB2Statement interface extends the java.sql.Statement
interface.
DB2Statement fields
The following fields are defined only for the IBM Data Server Driver for JDBC and
SQLJ.
public static final int RETURN_OPTLOCK_COLUMN_NONE = 0
public static final int RETURN_OPTLOCK_COLUMN_ALWAYS = 1
public static final int RETURN_OPTLOCK_COLUMN_NO_FALSE_NEGATIVES
=2
These values are arguments for the
DB2Statement.executeDB2OptimisticLockingQuery method.
DB2Statement methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
executeDB2OptimisticLockingQuery
Format:
public java.sql.ResultSet DB2Statement.executeDB2OptimisticLockingQuery(
String sql,
int returnOptLockingColumn)
throws java.sql.SQLException
getDB2ClientProgramId
Format:
public String getDB2ClientProgramId()
throws java.sql.SQLException
Returns the user-defined client program identifier for the connection, which is
stored on the data source.
getDB2ClientProgramId does not apply to DB2 Database for Linux, UNIX, and
Windows data servers.
setDB2ClientProgramId
Format:
public abstract void setDB2ClientProgramId(String program-ID)
throws java.sql.SQLException
Sets a user-defined program identifier for the connection on a data server. That
program identifier is an 80-byte string that is used to identify the caller.
setDB2ClientProgramId does not apply to DB2 Database for Linux, UNIX, and
Windows data servers.
The DB2 for z/OS server places the string in IFCID 316 trace records along
with other statistics, so that you can identify which program is associated with
a particular SQL statement.
getIDSBigSerial
Format:
public int getIDSBigSerial()
throws java.sql.SQLException
After an SQL statement executes on an IDS data source, if the statement has a
syntax error, getIDSSQLStatementOffSet returns the offset into the statement
text of the syntax error.
getIDSSQLStatementOffSet returns:
v 0, if the statement does not have a syntax error.
DB2SystemMonitor interface
The com.ibm.db2.jcc.DB2SystemMonitor interface is used for collecting system
monitoring data for a connection. Each connection can have one
DB2SystemMonitor instance.
DB2SystemMonitor fields
The following fields are defined only for the IBM Data Server Driver for JDBC and
SQLJ.
public final static int RESET_TIMES
public final static int ACCUMULATE_TIMES
These values are arguments for the DB2SystemMonitor.start method.
RESET_TIMES sets time counters to zero before monitoring starts.
ACCUMULATE_TIMES does not set time counters to zero.
DB2SystemMonitor methods
The following methods are defined only for the IBM Data Server Driver for JDBC
and SQLJ.
enable
Format:
public void enable(boolean on)
throws java.sql.SQLException
Enables the system monitor that is associated with a connection. This method
cannot be called during monitoring. All times are reset when enable is
invoked.
getApplicationTimeMillis
Format:
public long getApplicationTimeMillis()
throws java.sql.SQLException
Returns the sum of the application, JDBC driver, network I/O, and database
server elapsed times. The time is in milliseconds.
A monitored elapsed time interval is the difference, in milliseconds, between
these points in the JDBC driver processing:
Interval beginning
When start is called.
Interval end
When stop is called.
getApplicationTimeMillis returns 0 if system monitoring is disabled. Calling
this method without first calling the stop method results in an SQLException.
getCoreDriverTimeMicros
Format:
public long getCoreDriverTimeMicros()
throws java.sql.SQLException
Returns the sum of elapsed network I/O times that were collected while
system monitoring was enabled. The time is in microseconds.
Elapsed network I/O time includes the time to write and read DRDA data
from network I/O streams. A network I/O elapsed time interval is the time
interval to perform the following operations in the JDBC driver:
v Issue a TCP/IP command to send a DRDA message to the database server.
This time interval is the difference, in microseconds, between points
immediately before and after a write and flush to the network I/O stream is
performed.
v Issue a TCP/IP command to receive DRDA reply messages from the
database server. This time interval is the difference, in microseconds,
between points immediately before and after a read on the network I/O
stream is performed.
Network I/O time intervals are captured for all send and receive operations,
including the sending of messages for commits and rollbacks.
The time spent waiting for network I/O might be impacted by delays in CPU
dispatching at the database server for low-priority SQL requests.
getNetworkIOTimeMicros returns 0 if system monitoring is disabled. Calling
this method without first calling the stop method, or calling this method when
the underlying JVM does not support reporting times in microseconds results
in an SQLException.
getServerTimeMicros
Format:
Returns the sum of all reported database server elapsed times that were
collected while system monitoring was enabled. The time is in microseconds.
The database server reports elapsed times under these conditions:
v The database server supports returning elapsed time data to the client.
DB2 Database for Linux, UNIX, and Windows Version 9.5 and later and DB2
for z/OS support this function.
v The database server performs operations that can be monitored. For
example, database server elapsed time is not returned for commits or
rollbacks.
For IBM Data Server Driver for JDBC and SQLJ type 2 connectivity to DB2
Database for Linux, UNIX, and Windows, and IBM Data Server Driver for JDBC and
SQLJ type 4 connectivity: The database server elapsed time is defined as the
elapsed time to parse the request data stream, process the command, and
generate the reply data stream at the database server. Network time to receive
or send the data stream is not included. The database server elapsed time
interval is the difference, in microseconds, between these points in the database
server processing:
Interval beginning
When the operating system dispatches the database server to process a
TCP/IP message that is received from the JDBC driver.
Interval end
When the database server is ready to issue the TCP/IP command to return
the reply message to the client.
For IBM Data Server Driver for JDBC and SQLJ type 2 connectivity to DB2 for
z/OS: The database server elapsed time interval is the difference, in
microseconds, between these points in the JDBC driver native processing:
Interval beginning
The z/OS Store Clock (STCK) value when a JDBC driver native method
calls the RRS attachment facility to process an SQL request.
Interval end
The z/OS Store Clock (STCK) value when control returns to the JDBC
driver native method following an RRS attachment facility call to process
an SQL request.
getServerTimeMicros returns 0 if system monitoring is disabled. Calling this
method without first calling the stop method results in an SQLException.
start
Format:
public void start (int lapMode)
throws java.sql.SQLException
If the system monitor is enabled, stop ends the collection of system monitoring
data for a connection. After monitoring is stopped, monitored times can be
obtained with the getXXX methods of DB2SystemMonitor.
Calling this method with system monitoring disabled does nothing. Calling
this method without first calling start, or calling this method more than once
without an intervening start call results in an SQLException.
DB2TraceManager class
The com.ibm.db2.jcc.DB2TraceManager class controls the global log writer.
The global log writer is driver-wide, and applies to all connections. The global log
writer overrides any other JDBC log writers. In addition to starting the global log
writer, the DB2TraceManager class provides the ability to suspend and resume
tracing of any type of log writer. That is, the suspend and resume methods of the
DB2TraceManager class apply to all current and future DriverManager log writers,
DataSource log writers, or IBM Data Server Driver for JDBC and SQLJ-only
connection-level log writers.
DB2TraceManager methods
getTraceManager
Format:
static public DB2TraceManager getTraceManager()
throws java.sql.SQLException
Enables a global trace. After setLogWriter is called, all calls for DataSource or
Connection traces are discarded until DB2TraceManager.unsetLogWriter is
called.
When setLogWriter is called, all future Connection or DataSource traces are
redirected to a trace file or PrintWriter, depending on the form of setLogWriter
that you use. If the global trace is suspended when setLogWriter is called, the
specified settings take effect when the trace is resumed.
Parameter descriptions:
traceDirectory
Specifies a directory into which global trace information is written. This
setting overrides the settings of the traceDirectory and logWriter properties
for a DataSource or DriverManager connection.
Returns the PrintWriter for the global log writer, if it is set. Otherwise,
getLogWriter returns null.
getTraceFile
Format:
public abstract String getTraceFile()
throws java.sql.SQLException
Returns the name of the destination file for the global log writer, if it is set.
Otherwise, getTraceFile returns null.
Returns the name of the destination directory for global log writer files, if it is
set. Otherwise, getTraceDirectory returns null.
getTraceLevel
Format:
public abstract int getTraceLevel()
throws java.sql.SQLException
Returns the trace level for the global trace, if it is set. Otherwise, getTraceLevel
returns -1 (TRACE_ALL).
getTraceFileAppend
Format:
public abstract boolean getTraceFileAppend()
throws java.sql.SQLException
Returns true if the global trace records are appended to the trace file.
Otherwise, getTraceFileAppend returns false.
DB2TraceManagerMXBean interface
The com.ibm.db2.jcc.mx.DB2TraceManagerMXBean interface is the means by which
an application makes DB2TraceManager available as an MXBean for the remote
trace controller.
DB2TraceManagerMXBean methods
setTraceFile
Format:
public void setTraceFile(String traceFile,
boolean fileAppend, int traceLevel)
throws java.sql.SQLException
Specifies the name of the file into which the remote trace manager writes trace
information, and the type of information that is to be traced.
Parameter descriptions:
traceFileName
Specifies the file into which global trace information is written. This setting
overrides the settings of the traceFile and logWriter properties for a
DataSource or DriverManager connection.
When the form of setLogWriter with the traceFileName parameter is used,
only one log file is written.
traceFileName can include a directory path.
fileAppend
Specifies whether to append to or overwrite the file that is specified by the
traceFile parameter. true means that the existing file is not overwritten.
traceLevel
Specifies what to trace.
You can specify one or more of the following traces with the traceLevel
parameter:
Returns the name of the destination file for the remote trace controller, if it is
set. Otherwise, getTraceFile returns null.
setTraceDirectory
Format:
public void setTraceDirectory(String traceDirectory,
String baseTraceFileName,
int traceLevel) throws java.sql.SQLException
Specifies the name of the directory into which the remote trace controller
writes trace information, and the type of information that is to be traced.
Parameter descriptions:
traceDirectory
Specifies a directory into which trace information is written. This setting
overrides the settings of the traceDirectory and logWriter properties for a
DataSource or DriverManager connection.
Each JDBC driver connection is traced to a different file in the specified
directory. The naming convention for the files in that directory depends on
whether a non-null value is specified for baseTraceFileName:
Returns true if trace records that are generated by the trace controller are
appended to the trace file. Otherwise, getTraceFileAppend returns false.
Returns the name of the destination directory for trace records that are
generated by the trace controller, if it is set. Otherwise, getTraceDirectory
returns null.
getTraceLevel
Format:
public void getTraceLevel()
throws java.sql.SQLException
Returns the trace level for the trace records that are generated by the trace
controller, if it is set. Otherwise, getTraceLevel returns -1 (TRACE_ALL).
unsetLogWriter
Format:
public abstract void unsetLogWriter()
throws java.sql.SQLException
DB2Types class
The com.ibm.db2.jcc.DB2Types class provides fields that define IBM Data Server
Driver for JDBC and SQLJ-only data types.
DB2Types fields
The following constants define types codes only for the IBM Data Server Driver for
JDBC and SQLJ.
v public final static int BLOB_FILE = -100002
v public final static int CLOB_FILE = -100003
v public final static int CURSOR = -100008
v public final static int DECFLOAT = -100001
DB2XADataSource class
DB2XADataSource is a factory for XADataSource objects. An object that
implements this interface is registered with a naming service that is based on the
Java Naming and Directory Interface (JNDI).
DB2XADataSource methods
getDB2TrustedXAConnection
Formats:
public Object[] getDB2TrustedXAConnection(String user,
String password,
java.util.Properties properties)
throws java.sql.SQLException
public Object[] getDB2TrustedXAConnection(
java.util.Properties properties)
throws java.sql.SQLException
public Object[] getDB2TrustedXAConnection(
org.ietf.jgss.GSSCredential gssCredential,
java.util.Properties properties)
throws java.sql.SQLException
DB2Xml interface
The com.ibm.db2.jcc.DB2Xml interface is used for declaring Java objects for use
with the DB2 XML data type.
DB2Xml methods
The following method is defined only for the IBM Data Server Driver for JDBC
and SQLJ.
closeDB2Xml
Format:
public void closeDB2Xml()
throws SQLException
Retrieves data from a DB2Xml object, and converts the data to US-ASCII
encoding.
getDB2BinaryStream
Format:
public java.io.InputStream getDB2BinaryStream()
throws SQLException
Retrieves data from a DB2Xml object as a byte array. The character encoding of
the bytes is defined in the XML 1.0 specification.
getDB2CharacterStream
Format:
public java.io.Reader getDB2CharacterStream()
throws SQLExceptionn
Retrieves data from a DB2Xml object, converts the data to US-ASCII encoding,
and imbeds an XML declaration with an encoding specification for US-ASCII
in the returned data.
getDB2XmlBinaryStream
Format:
public java.io.InputStream getDB2XmlBinaryStream(String targetEncoding)
throws SQLExceptionn
Retrieves data from a DB2Xml object as a binary stream, converts the data to
targetEncoding, and imbeds an XML declaration with an encoding specification
for targetEncoding in the returned data.
Parameter:
targetEncoding
A valid encoding name that is listed in the IANA Charset Registry. The
encoding names that are supported by the DB2 server are listed in
"Mappings of CCSIDs to encoding names for serialized XML output data".
getDB2XmlBytes
Format:
public byte[] getDB2XmlBytes(String targetEncoding)
throws SQLExceptionn
Retrieves data from a DB2Xml object as a byte array, converts the data to
targetEncoding, and imbeds an XML declaration with an encoding specification
for targetEncoding in the returned data.
Parameter:
targetEncoding
A valid encoding name that is listed in the IANA Charset Registry. The
encoding names that are supported by the DB2 server are listed in
"Mappings of CCSIDs to encoding names for serialized XML output data".
getDB2XmlCharacterStream
Format:
public java.io.Reader getDB2XmlCharacterStream()
throws SQLExceptionn
Retrieves data from a DB2Xml object as a String object, converts the data to
ISO-10646-UCS-2 encoding, and imbeds an XML declaration with an encoding
specification for ISO-10646-UCS-2 in the returned data.
JDBC differences between the current IBM Data Server Driver for
JDBC and SQLJ and earlier DB2 JDBC drivers
Before you can upgrade your JDBC applications from older drivers to the IBM
Data Server Driver for JDBC and SQLJ, you need to understand the differences
between those drivers.
Important: The DB2 JDBC Type 2 Driver for Linux, UNIX and Windows (DB2
JDBC Type 2 Driver) is deprecated. This information is provided to assist you in
moving your applications to the IBM Data Server Driver for JDBC and SQLJ.
Supported methods
For a comparison of method support by the JDBC drivers, see "Driver support for
JDBC APIs".
For IBM Data Server Driver for JDBC and SQLJ, Version 3.50 and later, use of
progressive streaming is the default for LOB retrieval, for connections to DB2
Database for Linux, UNIX, and Windows Version 9.5 and later.
Progressive streaming is supported in the IBM Data Server Driver for JDBC and
SQLJ Version 3.1 and later, but for IBM Data Server Driver for JDBC and SQLJ
version 3.2 and later, use of progressive streaming is the default for LOB and XML
retrieval, for connections to DB2 for z/OS Version 9.1 and later.
Previous versions of the IBM Data Server Driver for JDBC and SQLJ and the DB2
JDBC Type 2 Driver did not support progressive streaming.
Important: With progressive streaming, when you retrieve a LOB or XML value
from a ResultSet into an application variable, you can manipulate the contents of
that application variable until you move the cursor or close the cursor on the
ResultSet. After that, the contents of the application variable are no longer
available to you. If you perform any actions on the LOB in the application variable,
you receive an SQLException. For example, suppose that progressive streaming is
enabled, and you execute statements like this:
...
ResultSet rs = stmt.executeQuery("SELECT CLOBCOL FROM MY_TABLE");
rs.next(); // Retrieve the first row of the ResultSet
Clob clobFromRow1 = rs.getClob(1);
// Put the CLOB from the first column of
// the first row in an application variable
String substr1Clob = clobFromRow1.getSubString(1,50);
// Retrieve the first 50 bytes of the CLOB
rs.next(); // Move the cursor to the next row.
// clobFromRow1 is no longer available.
// String substr2Clob = clobFromRow1.getSubString(51,100);
// This statement would yield an SQLException
Clob clobFromRow2 = rs.getClob(1);
After you execute rs.next() to position the cursor at the second row of the
ResultSet, the CLOB value in clobFromRow1 is no longer available to you.
Similarly, after you execute rs.close() to close the ResultSet, the values in
clobFromRow1 and clobFromRow2 are no longer available.
To avoid errors that are due to this changed behavior, you need to take one of the
following actions:
v Modify your applications.
Applications that retrieve LOB data into application variables can manipulate
the data in those application variables only until the cursors that were used to
retrieve the data are moved or closed.
v Disable progressive streaming by setting the progressiveStreaming property to
DB2BaseDataSource.NO (2).
For the IBM Data Server Driver for JDBC and SQLJ version 4.0 and later, the
default behavior of ResultSetMetaData.getColumnName and
ResultSetMetaData.getColumnLabel differs from the default behavior for earlier
JDBC drivers.
If you need to use IBM Data Server Driver for JDBC and SQLJ version 4.0 or later,
but your applications need to return the ResultSetMetaData.getColumnName and
ResultSetMetaData.getColumnLabel values that were returned with older JDBC
drivers, you can set the useJDBC4ColumnNameAndLabelSemantics Connection
and DataSource property to DB2BaseDataSource.NO (2).
With the IBM Data Server Driver for JDBC and SQLJ version 3.52 or later,
preparing an SQL statement for retrieval of automatically generated keys is
supported.
With the IBM Data Server Driver for JDBC and SQLJ version 3.50 or version 3.51,
preparing an SQL statement for retrieval of automatically generated keys and
using the PreparedStatement object for batch updates causes an SQLException.
Versions of the IBM Data Server Driver for JDBC and SQLJ before Version 3.50 do
not throw an SQLException when an application calls the addBatch or
executeBatch method on a PreparedStatement object that is prepared to return
automatically generated keys. However, the PreparedStatement object does not
return automatically generated keys.
For a JDBC or SQLJ application that runs under the IBM Data Server Driver for
JDBC and SQLJ version 2.6 or later, using type 4 connectivity, the initial value for
the DB2 for z/OS CURRENT CLIENT_ACCTNG special register is the
concatenation of the DB2 for z/OS version and the value of the clientWorkStation
The IBM Data Server Driver for JDBC and SQLJ supports scrollable and updatable
ResultSets.
The DB2 JDBC Type 2 Driver supports scrollable ResultSets but not updatable
ResultSets.
The IBM Data Server Driver for JDBC and SQLJ does not use existing SQLCODEs
or SQLSTATEs for internal errors, as the other drivers do. See "Error codes issued
by the IBM Data Server Driver for JDBC and SQLJ" and "SQLSTATEs issued by the
IBM Data Server Driver for JDBC and SQLJ".
The JDBC/SQLJ driver for OS/390 and z/OS return ODBC SQLSTATEs when
internal errors occur.
With the IBM Data Server Driver for JDBC and SQLJ, when you execute
SQLException.getMessage(), formatted message text is not returned unless you set
the retrieveMessagesFromServerOnGetMessage property to true.
With the DB2 JDBC Type 2 Driver, when you execute SQLException.getMessage(),
formatted message text is returned.
Security mechanisms
For information on IBM Data Server Driver for JDBC and SQLJ security
mechanisms, see "Security under the IBM Data Server Driver for JDBC and SQLJ".
For information on security mechanisms for the DB2 JDBC Type 2 Driver, see
"Security under the DB2 JDBC Type 2 Driver".
With the IBM Data Server Driver for JDBC and SQLJ, you can make a connection
read-only through the readOnly property for a Connection or DataSource object.
The IBM Data Server Driver for JDBC and SQLJ returns data from a
ResultSet.getString call for a CHAR FOR BIT DATA or VARCHAR FOR BIT DATA
column as a lowercase hexadecimal string.
The DB2 JDBC Type 2 Driver returns the data as an uppercase hexadecimal string.
By default, the IBM Data Server Driver for JDBC and SQLJ truncates trailing zeroes
when it returns data for a ResultSet.getString call for a TIMESTAMP column value.
You can change this behavior with the timestampPrecisionReporting property.
The DB2 JDBC Type 2 Driver does not truncate trailing zeroes when it returns data
for a ResultSet.getString call for a TIMESTAMP column value.
The IBM Data Server Driver for JDBC and SQLJ generates an SQLWarning when
an executeUpdate call affects no rows.
The IBM Data Server Driver for JDBC and SQLJ does not generate an SQLWarning
when a getDate or getTime call is made against a TIMESTAMP column.
The DB2 JDBC Type 2 Driver generates an SQLWarning when a getDate or getTime
call is made against a TIMESTAMP column.
Date and time adjustment for input and output values that to do
not correspond to real dates and times
The DB2 JDBC Type 2 Driver for Linux, UNIX and Windows does no adjustment
of date or time values that do not correspond to real dates or times. That driver
passes the values to and from the database as they are. For example, if you update
a TIMESTAMP column with the value 9999-12-31 24:00:00.0 under the DB2 JDBC
Type 2 Driver for Linux, UNIX and Windows, no exception is thrown. See the
information on date, time, and timestamp values that can cause problems in JDBC
and SQLJ applications for more information.
For the DB2 JDBC Type 2 Driver for Linux, UNIX and Windows, the default
format for retrieval of DATE, TIME, or TIMESTAMP column data into strings is
JIS, unless the default format is changed by the CLI keyword
DateTimeStringFormat.
For the IBM Data Server Driver for JDBC and SQLJ, the default format for retrieval
of DATE, TIME, or TIMESTAMP column data into strings is ISO, unless the default
format is changed by the dateFormat or timeFormat Connection or DataSource
property.
If the numbers of bytes do not match, the IBM Data Server Driver for JDBC and
SQLJ does not throw an exception until the subsequent
PreparedStatement.executeUpdate method executes. Therefore, for the IBM Data
Server Driver for JDBC and SQLJ, some data might be sent to the server when the
lengths to not match. That data is truncated or padded by the server. The calling
application needs to issue a rollback request to undo the database updates that
include the truncated or padded data.
With the IBM Data Server Driver for JDBC and SQLJ, when you use the
PreparedStatement.setBinaryStream , PreparedStatement.setCharacterStream, or
PreparedStatement.setUnicodeStream method, and no information about the data
type of the target column is available, the input data is mapped to a BLOB or
CLOB data type.
For the DB2 JDBC Type 2 Driver, the input data is mapped to a VARCHAR FOR
BIT DATA or VARCHAR data type.
When character data is transferred between a client and a server, the data must be
converted to a form that the receiver can process.
For the IBM Data Server Driver for JDBC and SQLJ, character data that is sent
from the data source to the client is converted using Java's built-in character
converters. The conversions that the IBM Data Server Driver for JDBC and SQLJ
supports are limited to those that are supported by the underlying JRE
implementation.
For the DB2 JDBC Type 2 Driver, character conversions can be performed if the
conversions are supported by the DB2 server.
If a GRAPHIC column contains single-byte characters (an error condition), the DB2
JDBC Type 2 Driver performs character conversion during data retrieval without
issuing an error, but the results might be incorrect. The IBM Data Server Driver for
JDBC and SQLJ issues an error.
If character data other than ASCII data is retrieved from a CLOB column with
getAsciiStream, the DB2 JDBC Type 2 Driver performs character conversion
correctly during data retrieval. The IBM Data Server Driver for JDBC and SQLJ
does not perform character conversion correctly. getAsciiStream should be used
only for retrieval of ASCII data. For other types of character data, use
getCharacterStream or getString instead.
Those drivers use CCSID information from the data source if it is available. The
drivers convert input parameter data to the CCSID of the data source before
sending the data. If target CCSID information is not available, the drivers send the
data as Unicode UTF-8.
With the IBM Data Server Driver for JDBC and SQLJ, conversion to the correct
SQL data type occurs implicitly if the target data type is known and if the
deferPrepares and sendDataAsIs connection properties are set to false. In this
case, the implicit values override any explicit values in the setXXX call. If the
deferPrepares connection property or the sendDataAsIs connection property is set
to true, you must use the PreparedStatement.setObject method to convert the
parameter to the correct SQL data type.
For the DB2 JDBC Type 2 Driver, if the data type of a parameter does not match its
default SQL data type, you must use the PreparedStatement.setObject method to
convert the parameter to the correct SQL data type.
The IBM Data Server Driver for JDBC and SQLJ does not support
PreparedStatement.setObject calls of the following form when x is an object of type
String:
setObject(parameterIndex, x, java.sqlTypes.BINARY)
The DB2 JDBC Type 2 Driver supports calls of this type. The driver interprets the
value of x as a hexadecimal string.
With the IBM Data Server Driver for JDBC and SQLJ, if you call
PreparedStatement.setObject with a decimal input parameter, and the scale of the
input parameter is greater than the scale of the target column, the driver truncates
the trailing digits of the input value before assigning the value to the column.
The DB2 JDBC Type 2 Driver rounds the trailing digits of the input value before
assigning the value to the column.
For the following form of PreparedStatement.setObject, the IBM Data Server Driver
for JDBC and SQLJ supports the standard data type mappings of Java objects to
JDBC data types when it converts x to a JDBC data type:
setObject(parameterIndex, x)
The DB2 JDBC Type 2 Driver supports the non-standard mapping of x from
java.lang.Character to CHAR.
The IBM Data Server Driver for JDBC and SQLJ supports
ResultSet.getBinaryStream with an argument that represents a character column
only if the column has the FOR BIT DATA attribute.
With the IBM Data Server Driver for JDBC and SQLJ, when you execute
ResultSet.getString against a binary column, the returned data is in the form of
lowercase, hexadecimal digit pairs.
With the DB2 JDBC Type 2 Driver, when you execute ResultSet.getString against a
binary column, the returned data is in the form of uppercase, hexadecimal digit
pairs.
With the IBM Data Server Driver for JDBC and SQLJ, when you execute
PreparedStatement.setObject(parameterIndex,x,CHAR), and x is Boolean, the value
"0" or "1" is inserted into the table column.
With the IBM Data Server Driver for JDBC and SQLJ, when you execute
ResultSet.getBoolean or CallableStatement.getBoolean to retrieve a Boolean value
from a CHAR column, and the column contains the value "false" or "0", the value
false is returned. If the column contains any other value, true is returned.
With the DB2 JDBC Type 2 Driver, when you execute ResultSet.getBoolean or
CallableStatement.getBoolean to retrieve a Boolean value from a CHAR column,
and the column contains the value "true" or "1", the value true is returned. If the
column contains any other value, false is returned.
With the IBM Data Server Driver for JDBC and SQLJ, when all rows have been
retrieved from a ResultSet, the cursor is automatically closed. When you execute
ResultSet.next after the cursor is closed, an SQLException is thrown. This behavior
conforms with the JDBC standard.
With the DB2 JDBC Type 2 Driver, when all rows have been retrieved from a
ResultSet, the cursor is not closed. When ResultSet.next is executed after all rows
have been retrieved, a value of false is returned, and no exception is thrown.
With the IBM Data Server Driver for JDBC and SQLJ, you can specify null for an
argument in a DatabaseMetaData method call only where the JDBC specification
states that null is allowed. Otherwise, an exception is thrown.
With the DB2 JDBC Type 2 Driver, null means that the argument is not used to
narrow the search.
The IBM Data Server Driver for JDBC and SQLJ does not fold any arguments in
method calls to uppercase.
The IBM Data Server Driver for JDBC and SQLJ supports the standard form of an
escape clause for TIME:
{t ’hh:mm:ss’}
In addition to the standard form, the DB2 JDBC Type 2 Driver supports the
following form of a TIME escape clause:
{ts ’hh:mm:ss’}
The IBM Data Server Driver for JDBC and SQLJ supports CALL statements in a
statement batch.
The DB2 JDBC Type 2 Driver does not support CALL statements in a statement
batch.
The IBM Data Server Driver for JDBC and SQLJ does not remove white-space
characters, such as spaces, tabs, and new-line characters, from SQL statement text
before it passes that text to the data source.
The DB2 JDBC Type 2 Driver removes white-space characters from SQLstatement
text before it passes that text to the data source.
The IBM Data Server Driver for JDBC and SQLJ driver does not support
compound SQL blocks.
The DB2 JDBC Type 2 Driver supports execution of compound SQL blocks with
PreparedStatement.executeUpdate or Statement.executeUpdate.
The IBM Data Server Driver for JDBC and SQLJ driver throws an exception after a
PreparedStatement.addBatch call if a parameter is not set.
The IBM Data Server Driver for JDBC and SQLJ driver does not let you call stored
procedures that are not defined in the DB2 catalog.
The DB2 JDBC Type 2 Driver lets you call stored procedures that are not defined in
the DB2 catalog.
With the IBM Data Server Driver for JDBC and SQLJ driver, if the data source does
not support dynamic execution of the CALL statement, you must specify CALL
statement parameters exactly as they are specified in the stored procedure
definition.
For example, DB2 for z/OS data sources do not support dynamic execution of
CALL statements. Suppose that the first parameter of a stored procedure on a DB2
for z/OS server is defined like this in the CREATE PROCEDURE statement:
OUT PARM1 DECIMAL(3,0)
The DB2 JDBC Type 2 Driver does not require that the parameter data types in a
calling application match the data types in the CREATE PROCEDURE statement.
When the IBM Data Server Driver for JDBC and SQLJ prepares an SQL statement,
it sends the statement to the data server with no extra processing. Therefore, if you
prepare an SQL statement that ends with a semicolon with the IBM Data Server
Driver for JDBC and SQLJ, you receive an error.
When the DB2 JDBC Type 2 Driver prepares an SQL statement that contains a final
semicolon, it strips the semicolon. Therefore, if the SQL statement has valid syntax,
it executes successfully.
For example, this code fails under the IBM Data Server Driver for JDBC and SQLJ
but executes successfully under the DB2 JDBC Type 2 Driver.
PreparedStatement pstmt1 = con.prepareStatement("SELECT c1,c2 FROM testtab;");
The number of Statement or PreparedStatement objects that you can leave open
concurrently is greater for the DB2 Type 2 Driver for Linux, UNIX, and Windows
than for the IBM Data Server Driver for JDBC and SQLJ. With the IBM Data Server
Driver for JDBC and SQLJ, you might receive error code -805 after you have
opened fewer Statement or PreparedStatement objects than with the DB2 Type 2
Driver for Linux, UNIX, and Windows. The difference is due to the way that the
drivers handle the underlying resources for those objects.
Supported methods
For a list of methods that the IBM Data Server Driver for JDBC and SQLJ supports,
see "Driver support for JDBC APIs".
For IBM Data Server Driver for JDBC and SQLJ, Version 3.50 and later, progressive
streaming, which is also known as dynamic data format, behavior is the default for
LOB retrieval, for connections to DB2 Database for Linux, UNIX, and Windows
Version 9.5 and later.
Progressive streaming is supported in the IBM Data Server Driver for JDBC and
SQLJ Version 3.1 and later, but for IBM Data Server Driver for JDBC and SQLJ
version 3.2 and later, progressive streaming behavior is the default for LOB and
XML retrieval, for connections to DB2 for z/OS Version 9.1 and later.
Previous versions of the IBM Data Server Driver for JDBC and SQLJ did not
support progressive streaming.
Important: With progressive streaming, when you retrieve a LOB or XML value
from a ResultSet into an application variable, you can manipulate the contents of
that application variable until you move the cursor or close the cursor on the
ResultSet. After that, the contents of the application variable are no longer
available to you. If you perform any actions on the LOB in the application variable,
you receive an SQLException. For example, suppose that progressive streaming is
enabled, and you execute statements like this:
...
ResultSet rs = stmt.executeQuery("SELECT CLOBCOL FROM MY_TABLE");
rs.next(); // Retrieve the first row of the ResultSet
Clob clobFromRow1 = rs.getClob(1);
// Put the CLOB from the first column of
// the first row in an application variable
String substr1Clob = clobFromRow1.getSubString(1,50);
// Retrieve the first 50 bytes of the CLOB
rs.next(); // Move the cursor to the next row.
// clobFromRow1 is no longer available.
// String substr2Clob = clobFromRow1.getSubString(51,100);
// This statement would yield an SQLException
Clob clobFromRow2 = rs.getClob(1);
// Put the CLOB from the first column of
// the second row in an application variable
rs.close(); // Close the ResultSet.
// clobFromRow2 is also no longer available.
After you execute rs.next() to position the cursor at the second row of the
ResultSet, the CLOB value in clobFromRow1 is no longer available to you.
Similarly, after you execute rs.close() to close the ResultSet, the values in
clobFromRow1 and clobFromRow2 are no longer available.
For the IBM Data Server Driver for JDBC and SQLJ version 4.0 and later, the
default behavior of ResultSetMetaData.getColumnName and
ResultSetMetaData.getColumnLabel differs from the default behavior for earlier
JDBC drivers.
If you need to use IBM Data Server Driver for JDBC and SQLJ version 4.0 or later,
but your applications need to return the ResultSetMetaData.getColumnName and
ResultSetMetaData.getColumnLabel values that were returned with older JDBC
drivers, you can set the useJDBC4ColumnNameAndLabelSemantics Connection
and DataSource property to DB2BaseDataSource.NO (2).
With the IBM Data Server Driver for JDBC and SQLJ version 3.52 or later,
preparing an SQL statement for retrieval of automatically generated keys is
supported.
With the IBM Data Server Driver for JDBC and SQLJ version 3.50 or version 3.51,
preparing an SQL statement for retrieval of automatically generated keys and
using the PreparedStatement object for batch updates causes an SQLException.
Versions of the IBM Data Server Driver for JDBC and SQLJ before Version 3.50 do
not throw an SQLException when an application calls the addBatch or
executeBatch method on a PreparedStatement object that is prepared to return
automatically generated keys. However, the PreparedStatement object does not
return automatically generated keys.
After you successfully invoke an executeBatch statement, the IBM Data Server
Driver for JDBC and SQLJ returns an array. The purpose of the array is to indicate
the number of rows that are affected by each SQL statement that is executed in the
batch.
If the following conditions are true, the IBM Data Server Driver for JDBC and SQLJ
returns Statement.SUCCESS_NO_INFO (-2) in the array elements:
v The application is connected to a subsystem that is in DB2 for z/OS Version 8
new-function mode, or later.
v The application is using Version 3.1 or later of the IBM Data Server Driver for
JDBC and SQLJ.
This occurs because with multi-row INSERT, the database server executes the
entire batch as a single operation, so it does not return results for individual SQL
statements.
If you are using an earlier version of the IBM Data Server Driver for JDBC and
SQLJ, or you are connected to a data source other than DB2 for z/OS Version 8 or
later, the array elements contain the number of rows that are affected by each SQL
statement.
Batch updates and deletes of data on DB2 for z/OS servers have
different size limitations in different driver versions
Before IBM Data Server Driver for JDBC and SQLJ version 3.59 or 4.9, a
DisconnectException with error code -4499 was thrown for IBM Data Server Driver
for JDBC and SQLJ type 4 connectivity to DB2 for z/OS if the size of an update or
delete batch was greater than 32KB. Starting with version 3.59 or 4.9, this
restriction no longer exists, and the exception is no longer thrown.
For a JDBC or SQLJ application that runs under the IBM Data Server Driver for
JDBC and SQLJ version 2.6 or later, using type 4 connectivity, the initial value for
the DB2 for z/OS CURRENT CLIENT_ACCTNG special register is the
concatenation of the DB2 for z/OS version and the value of the clientWorkStation
property. For any other JDBC driver, version, and connectivity, the initial value is
not set.
Before version 3.7 and version 3.51 of the IBM Data Server Driver for JDBC and
SQLJ, multi-row FETCH support was enabled and disabled through the
useRowsetCursor property, and was available only for scrollable cursors, and for
IBM Data Server Driver for JDBC and SQLJ type 4 connectivity to DB2 for z/OS.
Starting with version 3.7 and 3.51:
v For IBM Data Server Driver for JDBC and SQLJ type 2 connectivity on DB2 for
z/OS, the IBM Data Server Driver for JDBC and SQLJ uses only the
enableRowsetSupport property to determine whether to use multi-row FETCH
for scrollable or forward-only cursors.
v For IBM Data Server Driver for JDBC and SQLJ type 4 connectivity to DB2 for
z/OS or DB2 Database for Linux, UNIX, and Windows, or IBM Data Server
Driver for JDBC and SQLJ type 2 connectivity on DB2 Database for Linux,
UNIX, and Windows, the IBM Data Server Driver for JDBC and SQLJ uses the
enableRowsetSupport property to determine whether to use multi-row FETCH
for scrollable cursors, if enableRowsetSupport is set. If enableRowsetSupport is
not set, the driver uses the useRowsetCursor property to determine whether to
use multi-row FETCH.
Before version 3.7 and version 3.51 of the IBM Data Server Driver for JDBC and
SQLJ, multi-row FETCH from DB2 for z/OS tables was controlled by the
useRowsetCursor property. If an application contained JDBC 1 positioned update
Starting with version 3.7 and 3.51 of the IBM Data Server Driver for JDBC and
SQLJ, the enableRowsetSupport property enables or disables multi-row FETCH
from DB2 for z/OS tables or DB2 Database for Linux, UNIX, and Windows tables.
The enableRowsetSupport property overrides the useRowsetCursor property. If
multi-row FETCH is enabled through the enableRowsetSupport property, and an
application contains a JDBC 1 positioned update or delete operation, the IBM Data
Server Driver for JDBC and SQLJ throws an SQLException.
Starting with version 3.57 or version 4.7 of the IBM Data Server Driver for JDBC
and SQLJ, if you are inserting data into a view on a DB2 for z/OS data server, and
you want to retrieve automatically generated keys, you need to use one of the
following methods to prepare the SQL statement that inserts rows into the view:
Connection.prepareStatement(sql-statement, String [] columnNames);
Connection.prepareStatement(sql-statement, int [] columnIndexes);
Statement.executeUpdate(sql-statement, String [] columnNames);
Statement.executeUpdate(sql-statement, int [] columnIndexes);
The following examples show the values that are returned for IBM Data Server
Driver for JDBC and SQLJ Version 4.0, and for previous JDBC drivers, when the
useJDBC4ColumnNameAndLabelSemantics property is not set.
Example: The following query contains an AS CLAUSE, which defines a label for a
column in the result set:
SELECT MYCOL AS MYLABEL FROM MYTABLE
Example: On a DB2 for z/OS or DB2 for i data source, a LABEL ON statement is
used to define a label for a column:
LABEL ON COLUMN MYTABLE.MYCOL IS ’LABELONCOL’
The following query contains an AS CLAUSE, which defines a label for a column
in the ResultSet:
SELECT MYCOL AS MYLABEL FROM MYTABLE
Example: On a DB2 for z/OS or DB2 for i data source, a LABEL ON statement is
used to define a label for a column:
SQLJ differences between the IBM Data Server Driver for JDBC and
SQLJ and other DB2 JDBC drivers
The IBM Data Server Driver for JDBC and SQLJ differs in a number of ways from
older JDBC drivers. When you move to the IBM Data Server Driver for JDBC and
SQLJ, you need to modify your SQLJ programs to account for those differences.
Important: The DB2 JDBC Type 2 Driver for Linux, UNIX and Windows (DB2
JDBC Type 2 Driver) is deprecated. This information is provided to assist you in
moving your applications to the IBM Data Server Driver for JDBC and SQLJ.
SQLJ support in the IBM Data Server Driver for JDBC and SQLJ differs from SQLJ
support in the other DB2 JDBC drivers in the following areas:
The db2sqljcustomize utility that is part of the IBM Data Server Driver for JDBC
and SQLJ has a -collection parameter. The db2profc utility that is part of the DB2
JDBC Type 2 Driver does not have a -collection parameter. If the db2sqljcustomize
utility performs a bind operation on a DB2 for z/OS server, and the -collection
parameter contains any lowercase characters, db2sqljcustomize returns a -4499
error because collection IDs cannot contain lowercase characters in DB2 for z/OS.
This situation cannot occur with db2profc.
The DB2 JDBC Type 2 Driver and the IBM Data Server Driver for JDBC and SQLJ
produce different binary code when you execute their SQLJ translator and the
SQLJ customizer utilities. Therefore, SQLJ applications that you translated and
customized using the DB2 JDBC Type 2 Driver sqlj and db2profc utilities do not
run under the IBM Data Server Driver for JDBC and SQLJ. Before you can run
The DB2 JDBC Type 2 Driver supports the SQL VALUES statement in an SQLJ
statement clause, but the IBM Data Server Driver for JDBC and SQLJ does not.
Therefore, you need to modify your SQLJ applications that include VALUES
statements.
For the IBM Data Server Driver for JDBC and SQLJ, you need to change that
statement to something like this:
#sql [ctxt] {SELECT MY_ROUTINE(1) INTO :hv FROM SYSIBM.SYSDUMMY1};
The connection techniques that are available, and the driver names and URLs that
are used for those connection techniques, vary from driver to driver. See "Connect
to a data source using SQLJ" for more information.
SQLJ with the IBM Data Server Driver for JDBC and SQLJ supports scrollable and
updatable iterators.
The DB2 JDBC Type 2 Driver for Linux, UNIX and Windows (DB2 JDBC Type 2
Driver) supports scrollable cursors but not updatable iterators.
For WebSphere Application Server Version 5.0.1 and above, if you customize your
SQLJ program, SQL statements are executed statically.
The DB2 JDBC Type 2 Driver originally used the name db2profc for the SQLJ
profile customizer command, and the name db2profp for the SQLJ profile printer
command. For the IBM Data Server Driver for JDBC and SQLJ, the SQLJ profile
customizer command is named db2sqljcustomize, and the SQLJ profile printer
command is named db2sqljprint. In previous releases of DB2 Database for Linux,
UNIX, and Windows, db2profc was accepted as an alternative name for
db2sqljcustomize, and db2profp was accepted as an alternative name for
db2sqljprint. These alternative names are no longer accepted.
When you retrieve a DBCS substitution character, such as X'FCFC' in code page
Cp943, from a database table, the retrieved value differs, depending on whether
you are using an IBM SDK for Java or a Sun SDK for Java.
For a Sun SDK for Java, the substitution character is retrieved as U+0000. For an
IBM SDK for Java, the substitution character is retrieved as X'FFFD'.
IBM SDKs for Java support more DBCS code pages than Sun SDKs for Java.
Therefore, if you get errors because of unsupported code pages with a Sun SDK for
Java, try using an IBM SDK for Java.
The IBM SDKs for Java support 256-bit encryption, but the Sun SDKs for Java do
not have this support. Therefore, if you use any of the IBM Data Server Driver for
JDBC and SQLJ security mechanisms that include encryption, you need to use an
IBM SDK for Java.
Support for system monitoring in the IBM Data Server Driver for JDBC and SQLJ
includes collection of core driver time and network I/O time. Retrieval of this
information requires capabilities that are in any SDK for Java Version 5 or later.
However, the IBM SDK for Java Version 1.4.2 also has support that enables
collection of core driver time and network I/O time. If you use the IBM SDK for
Java Version 1.4.2, the core driver time and network I/O time are rounded to the
nearest microsecond. If you use an SDK for Java Version 5 or later, the core driver
time and network I/O time are rounded to the nearest nanosecond.
Error codes issued by the IBM Data Server Driver for JDBC and SQLJ
Error codes in the ranges +4200 to +4299, +4450 to +4499, -4200 to -4299, and -4450
to -4499 are reserved for the IBM Data Server Driver for JDBC and SQLJ.
When you call the SQLException.getMessage method after a IBM Data Server
Driver for JDBC and SQLJ error occurs, a string is returned that includes:
v Whether the connection is a type 2 or type 4 connection
v Diagnostic information for IBM Software Support
v The level of the driver
v An explanatory message
v The error code
v The SQLSTATE
For example:
Currently, the IBM Data Server Driver for JDBC and SQLJ issues the following
error codes:
Table 113. Error codes issued by the IBM Data Server Driver for JDBC and SQLJ
Error
Code Message text and explanation SQLSTATE
+4204 Errors were encountered and tolerated as specified by the 02506
RETURN DATA UNTIL clause.
The following table lists the SQLSTATEs that are generated or used by the IBM
Data Server Driver for JDBC and SQLJ.
Table 114. SQLSTATEs returned by the IBM Data Server Driver for JDBC and SQLJ
SQLSTATE
class SQLSTATE Description
01xxx Warning
02xxx No data
02501 The cursor position is not valid for a FETCH of the current
row.
02506 Tolerable error
08xxx Connection exception
08001 The application requester is unable to establish the
connection.
08003 A connection does not exist
08004 The application server rejected establishment of the
connection
08506 Client reroute exception
0Axxx Feature not supported
0A502 The action or operation is not enabled for this database
instance
0A504 The feature is not supported by the driver
22xxx Data exception
22007 The string representation of a datetime value is invalid
22021 A character is not in the coded character set
23xxx Constraint violation
23502 A value that is inserted into a column or updates a column is
null, but the column cannot contain null values.
24xxx Invalid cursor state
24501 The identified cursor is not open
28xxx Authorization exception
28000 Authorization name is invalid.
2Dxxx Invalid transaction termination
2D521 SQL COMMIT or ROLLBACK are invalid in the current
operating environment.
34xxx Invalid cursor name
34000 Cursor name is invalid.
3Bxxx Invalid savepoint
3B503 A SAVEPOINT, RELEASE SAVEPOINT, or ROLLBACK TO
SAVEPOINT statement is not allowed in a trigger or global
transaction.
40xxx Transaction rollback
How to find IBM Data Server Driver for JDBC and SQLJ version and
environment information
To determine the version of the IBM Data Server Driver for JDBC and SQLJ, as
well as information about the environment in which the driver is running, run the
DB2Jcc utility on the command line.
DB2Jcc syntax
java com.ibm.db2.jcc.DB2Jcc
-version -configuration -help
The following output is the result of invoking DB2Jcc with the -configuration
parameter.
Authorization
None
Command syntax
sqlj
-help -dir=directory -d=directory -props=properties-file
-ser2class -status -version -C-help
-Ccompiler-option
-JJVM-option SQLJ-source-file-name
All options are passed to the Java compiler and are not used by the SQLJ
translator, except for the following options:
-classpath
Specifies the user class path that is to be used by the SQLJ translator
and the Java compiler. This value overrides the CLASSPATH
environment variable.
Output
For each source file, program-name.sqlj, the SQLJ translator produces the following
files:
v The generated source program
The generated source file is named program-name.java.
v A serialized profile file for each connection context class that is used in an SQLJ
executable clause
A serialized profile name is of the following form:
program-name_SJProfileIDNumber.ser
v If the SQLJ translator invokes the Java compiler, the class files that the compiler
generates.
Examples
sqlj -encoding=UTF8 -C-O MyApp.sqlj
By default, db2sqljcustomize produces four DB2 packages: one for each isolation
level. db2sqljcustomize augments the profile with DB2-specific information for use
at run time.
Authorization
The privilege set of the process must include one of the following authorities:
v DBADM authority
v If the package does not exist, the BINDADD privilege, and one of the following
privileges:
– CREATEIN privilege
– IMPLICIT_SCHEMA authority on the database if the schema name of the
package does not exist
v If the package exists:
– ALTERIN privilege on the schema
– BIND privilege on the package
Command syntax
db2sqljcustomize
-help
-url jdbc:db2://server /database -user user-ID
: port
: property=value;
-datasource JNDI-name
-automaticbind YES
-password password -automaticbind NO -pkgversion AUTO
-pkgversion version-id
-bindoptions " options-string " -storebindoptions -collection collection-name
-onlinecheck YES
-onlinecheck NO -qualifier qualifier-name -rootpkgname package-name-stem
-singlepkgname package-name
-staticpositioned NO
-longpkgname -staticpositioned YES
-tracelevel TRACE_NONE
TRACE_CONNECTION_CALLS
TRACE_STATEMENT_CALLS
TRACE_RESULT_SET_CALLS
TRACE_DRIVER_CONFIGURATION
TRACE_CONNECTS
TRACE_DRDA_FLOWS
TRACE_RESULT_SET_META_DATA
TRACE_PARAMETER_META_DATA
TRACE_DIAGNOSTICS
TRACE_SQLJ
TRACE_XA_CALLS
TRACE_TRACEPOINTS
TRACE_ALL
-zosDescProcParms -zosProcedurePath procedure-path -genDBRM
serialized-profile-name
-DBRMDir directory-name file-name.grp
options-string:
DB2-for-z/OS-options
DB2-Database-for-Linux-UNIX-and-Windows-options
ACTION(REPLACE)
(1) REPLVER(version-id) DBPROTOCOL(DRDA) DEGREE(1)
ACTION(ADD) DBPROTOCOL(PRIVATE) DEGREE(ANY)
PATH( schema-name )
USER
Notes:
1 These options can be specified in any order.
SQLERROR NOPACKAGE
QUALIFIER qualifier-name QUERYOPT optimization-level SQLERROR CONTINUE
SQLERRORCHECK
Notes:
1 These options can be specified in any order.
Command parameters
-help
Specifies that the SQLJ customizer describes each of the options that the
customizer supports. If any other options are specified with -help, they are
ignored.
-url
Specifies the URL for the data source for which the profile is to be customized.
A connection is established to the data source that this URL represents if the
-automaticbind or -onlinecheck option is specified as YES or defaults to YES.
The variable parts of the -url value are:
server
The domain name or IP address of the z/OS system on which the DB2
subsystem resides.
Recommendation: If the target data source is DB2 for z/OS, use uppercase
characters for the package-name-stem or package-name value. DB2 for z/OS
systems that are defined with certain CCSID values cannot tolerate lowercase
characters in package names or collection names.
Table 115 shows the parts of a generated package name and the number of
bytes for each part.
The maximum length of a package name is maxlen. maxlen is 8 if -longpkgname
is not specified. maxlen is 128 if -longpkgname is specified.
Table 115. Parts of a package name that is generated by db2sqljcustomize
Package name part Number of bytes Value
Bytes-from-program-name m=min(Length(program-name), First m bytes of program-name, in
maxlen–1–Length(IDNumber)) uppercase
IDNumber Length(IDNumber) IDNumber
PkgIsolation 1 1, 2, 3, or 4. This value represents the
transaction isolation level for the
package. See Table 116.
Table 116 shows the values of the PkgIsolation portion of a package name that is
generated by db2sqljcustomize.
Table 116. PkgIsolation values and associated isolation levels
PkgNumber value Isolation level for package
1 Uncommitted read (UR)
2 Cursor stability (CS)
3 Read stability (RS)
4 Repeatable read (RR)
qualifier-name is the value of the -qualifier parameter, and user-ID is the value
of the -user parameter.
The DB2 database server tries the schema names in the SQL path from left to
right until it finds a match with the name of a stored procedure that exists on
that database server. If the DB2 database server finds a match, it obtains the
information about the parameters for that stored procedure from the DB2
catalog. If the DB2 database server does not find a match, SQLJ sets the
parameter data without any DB2 catalog information.
If -zosProcedurePath is not specified, the DB2 database server uses this SQL
path:
SYSIBM, SYSFUN, SYSPROC, qualifier-name, user-ID
If the -qualifier parameter is not specified, the SQL path does not include
qualifier-name.
-genDBRM
Specifies that db2sqljcustomize generates database request modules (DBRMs).
Those DBRMs can be used to create DB2 for z/OS plans and packages.
-genDBRM applies to programs that are to be run on DB2 for z/OS database
servers only.
If -genDBRM and -automaticbind NO are specified, db2sqljcustomize creates
the DBRMs but does not bind them into DB2 packages. If -genDBRM and
-automaticbind YES are specified, db2sqljcustomize creates the DBRMs and
binds them into DB2 packages.
One DBRM is created for each DB2 isolation level. The naming convention for
the generated DBRM files is the same as the naming convention for packages.
For example, if -rootpkgname SQLJSA0 is specified, and -genDBRM is also
specified, the names of the four DBRM files are:
v SQLJSA01
v SQLJSA02
v SQLJSA03
v SQLJSA04
-DBRMDir directory-name
When -genDBRM is specified, -DBRMDir specifies the local directory into
which db2sqljcustomize puts the generated DBRM files. The default is the
current directory.
-DBRMdir applies to programs that are to be run on DB2 for z/OS database
servers only.
-tracefile file-name
Enables tracing and identifies the output file for trace information. This option
should be specified only under the direction of IBM Software Support.
You can specify the serialized profile name with or without the .ser extension.
program-name is the name of the SQLJ source program, without the extension
.sqlj. n is an integer between 0 and m-1, where m is the number of serialized
profiles that the SQLJ translator generated from the SQLJ source program.
You can specify serialized profile names in one of the following ways:
v List the names in the db2sqljcustomize command. Multiple serialized profile
names must be separated by spaces.
v Specify the serialized profile names, one on each line, in a file with the name
file-name.grp, and specify file-name.grp in the db2sqljcustomize command.
If you specify more than one serialized profile name, and if you specify or use
the default value of -automaticbind YES, db2sqljcustomize binds a single DB2
package from the profiles. When you use db2sqljcustomize to create a single
DB2 package from multiple serialized profiles, you must also specify the
-rootpkgname or -singlepkgname option.
If you specify more than one serialized profile name, and you specify
-automaticbind NO, if you want to bind the serialized profiles into a single
DB2 package when you run db2sqljbind, you need to specify the same list of
serialized profile names, in the same order, in db2sqljcustomize and
db2sqljbind.
If you specify one or more file-name.grp files, and you specify -automaticbind
NO, when you run db2sqljbind, you must specify that same list of files, and in
the same order in which the files were customized.
You cannot run db2sqljcustomize on individual files, and then group those files
when you run db2sqljbind.
Output
Examples
db2sqljcustomize -user richler -password mordecai
-url jdbc:db2:/server:50000/sample -collection duddy
-bindoptions "EXPLAIN YES" pgmname_SJProfile0.ser
Usage notes
Using a customized serialized profile at one data source that was customized at
another data source: You can run db2sqljcustomize to produce a customized
serialized profile for an SQLJ program at one data source, and then use that profile
at another data source. You do this by running db2sqljbind multiple times on
customized serialized profiles that you created by running db2sqljcustomize once.
When you run the programs at these data sources, the DB2 objects that the
programs access must be identical at every data source. For example, tables at all
data sources must have the same encoding schemes and the same columns with
the same data types.
Using the -collection parameter: db2sqljcustomize stores the DB2 collection name
in each customized serialized profile that it produces. When an SQLJ program is
executed, the driver uses the collection name that is stored in the customized
serialized profile to search for packages to execute. The name that is stored in the
customized serialized profile is determined by the value of the -collection
parameter. Only one collection ID can be stored in the serialized profile. However,
you can bind the same serialized profile into multiple package collections by
specifying the COLLECTION option in the -bindoptions parameter. To execute a
package that is in a collection other than the collection that is specified in the
serialized profile, include a SET CURRENT PACKAGESET statement in the
program.
Binding packages and plans on DB2 for z/OS: You can use the db2sqljcustomize
-genDBRM parameter to create DBRMs on your local system. You can then transfer
those DBRMs to a DB2 for z/OS system, and bind them into packages or plans
there. If you plan to use this technique, you need to transfer the DBRM files to the
z/OS system as binary files, to a partitioned data set with record format FB and
record length 80. When you bind the packages or plans, you need to specify the
following bind option values:
ENCODING(EBCDIC)
The IBM Data Server Driver for JDBC and SQLJ on DB2 for z/OS requires
EBCDIC encoding for your packages and plans.
DYNAMICRULES(BIND)
This option ensures consistent authorization rules when SQLJ uses
dynamic SQL. SQLJ uses dynamic SQL for positioned UPDATE or DELETE
operations that involve multiple SQLJ programs.
DBPROTOCOL(DRDA)
Private protocol is deprecated in DB2 for z/OS Version 9.1, and no longer
supported in DB2 for z/OS Version 10. You should use
DBPROTOCOL(DRDA) for all applications.
Applications that run with the IBM Data Server Driver for JDBC and SQLJ require
packages but no plans. If the db2sqljcustomize -automaticbind option is specified
as YES or defaults to YES, db2sqljcustomize binds packages for you at the data
source that you specify in the -url parameter. However, if -automaticbind is NO, if
a bind fails when db2sqljcustomize runs, or if you want to create identical
packages at multiple locations for the same serialized profile, you can use the
db2sqljbind command to bind packages.
The privilege set of the process must include one of the following authorities:
v DBADM authority
v If the package does not exist, the BINDADD privilege, and one of the following
privileges:
– CREATEIN privilege
– IMPLICIT_SCHEMA authority on the database if the schema name of the
package does not exist
v If the package exists:
– ALTERIN privilege on the schema
– BIND privilege on the package
The user also needs all privileges that are required to compile any static SQL
statements in the application. Privileges that are granted to groups are not used for
authorization checking of static statements.
Command syntax
db2sqljbind -url jdbc:db2://server /database
-help : port
: property=value;
-staticpositioned NO
-staticpositioned YES -genDBRM -DBRMDir directory-name
-tracelevel TRACE_SQLJ
-tracefile file-name
,
-tracelevel TRACE_NONE
TRACE_CONNECTION_CALLS
TRACE_STATEMENT_CALLS
TRACE_RESULT_SET_CALLS
TRACE_DRIVER_CONFIGURATION
TRACE_CONNECTS
TRACE_DRDA_FLOWS
TRACE_RESULT_SET_META_DATA
TRACE_PARAMETER_META_DATA
TRACE_DIAGNOSTICS
TRACE_SQLJ
TRACE_XA_CALLS
TRACE_TRACEPOINTS
TRACE_ALL
options-string:
DB2-for-z/OS-options
DB2-Database-for-Linux-UNIX-and-Windows-options
ACTION(REPLACE)
(1) REPLVER(version-id) DBPROTOCOL(DRDA) DEGREE(1)
ACTION(ADD) DBPROTOCOL(PRIVATE) DEGREE(ANY)
OWNER(authorization-ID) , QUALIFIER(qualifier-name)
PATH( schema-name )
USER
Notes:
1 These options can be specified in any order.
Notes:
1 These options can be specified in any order.
Command parameters
-help
Specifies that db2sqljbind describes each of the options that it supports. If any
other options are specified with -help, they are ignored.
-url
Specifies the URL for the data source for which the profile is to be customized.
A connection is established to the data source that this URL represents if the
-automaticbind or -onlinecheck option is specified as YES or defaults to YES.
The variable parts of the -url value are:
server
The domain name or IP address of the operating system on which the
database server resides.
port
The TCP/IP server port number that is assigned to the database server.
The default is 446.
database
A name for the database server for which the profile is to be customized.
If the connection is to a DB2 for z/OS server, database is the DB2 location
name that is defined during installation. All characters in this value must
be uppercase characters. You can determine the location name by executing
the following SQL statement on the server:
SELECT CURRENT SERVER FROM SYSIBM.SYSDUMMY1;
If the connection is to a DB2 Database for Linux, UNIX, and Windows
server, database is the database name that is defined during installation.
If the connection is to an IBM Cloudscape server, the database is the
fully-qualified name of the file that contains the database. This name must
be enclosed in double quotation marks ("). For example:
"c:/databases/testdb"
property=value;
A property for the JDBC connection.
-user user-ID
Specifies the user ID to be used to connect to the data source for binding the
package.
-password password
Specifies the password to be used to connect to the data source for binding the
package.
program-name is the name of the SQLJ source program, without the extension
.sqlj. n is an integer between 0 and m-1, where m is the number of serialized
profiles that the SQLJ translator generated from the SQLJ source program.
You can specify serialized profile names in one of the following ways:
v List the names in the db2sqljcustomize command. Multiple serialized profile
names must be separated by spaces.
v Specify the serialized profile names, one on each line, in a file with the name
file-name.grp, and specify file-name.grp in the db2sqljbind command.
If you specify more than one serialized profile name to bind a single DB2
package from several serialized profiles, you must have specified the same
serialized profile names, in the same order, when you ran db2sqljcustomize.
If you specify one or more file-name.grp files, you must have run
db2sqljcustomize once with that same list of files. The order in which you
specify the files in db2sqljbind must be the same as the order in
db2sqljcustomize.
You cannot run db2sqljcustomize on individual files, and then group those files
when you run db2sqljbind.
Examples
db2sqljbind -user richler -password mordecai
-url jdbc:db2://server:50000/sample -bindoptions "EXPLAIN YES"
pgmname_SJProfile0.ser
Usage notes
Package names produced by db2sqljbind: The names of the packages that are
created by db2sqljbind are the names that you specified using the-rootpkgname or
-singlepkgname parameter when you ran db2sqljcustomize. If you did not specify
-rootpkgname or -singlepkgname, the package names are the first seven bytes of
the profile name, appended with the isolation level character.
Authorization
None
Command syntax
db2sqljprint profilename
Command parameters
profilename
Specifies the relative or absolute name of an SQLJ profile file. When an
SQLJ file is translated into a Java source file, information about the SQL
operations it contains is stored in SQLJ-generated resource files called
profiles. Profiles are identified by the suffix _SJProfileN (where N is an
integer) following the name of the original input file. They have a .ser
extension. Profile names can be specified with or without the .ser
extension.
Examples
db2sqljprint pgmname_SJProfile0.ser
Note: The DB2 Information Center topics are updated more frequently than either
the PDF or the hard-copy books. To get the most current information, install the
documentation updates as they become available, or refer to the DB2 Information
Center at ibm.com®.
You can access additional DB2 technical information such as technotes, white
papers, and IBM Redbooks® publications online at ibm.com. Access the DB2
Information Management software library site at http://www.ibm.com/software/
data/sw-library/.
Documentation feedback
We value your feedback on the DB2 documentation. If you have suggestions for
how to improve the DB2 documentation, send an email to [email protected].
The DB2 documentation team reads all of your feedback, but cannot respond to
you directly. Provide specific examples wherever possible so that we can better
understand your concerns. If you are providing feedback on a specific topic or
help file, include the topic title and URL.
Do not use this email address to contact DB2 Customer Support. If you have a DB2
technical issue that the documentation does not resolve, contact your local IBM
service center for assistance.
If you would like to help IBM make the IBM Information Management products
easier to use, take the Consumability Survey: http://www.ibm.com/software/
data/info/consumability-survey/.
Although the tables identify books available in print, the books might not be
available in your country or region.
The form number increases each time a manual is updated. Ensure that you are
reading the most recent version of the manuals, as listed in the following table.
Note: The DB2 Information Center is updated more frequently than either the PDF
or the hard-copy books.
Table 117. DB2 technical information
Name Form Number Available in print Last updated
Administrative API SC23-5842-03 Yes December, 2010
Reference
Administrative Routines SC23-5843-03 No December, 2010
and Views
Call Level Interface SC23-5844-03 Yes December, 2010
Guide and Reference,
Volume 1
Call Level Interface SC23-5845-03 Yes December, 2010
Guide and Reference,
Volume 2
Command Reference SC23-5846-03 Yes December, 2010
Data Movement Utilities SC23-5847-03 Yes December, 2010
Guide and Reference
Data Recovery and High SC23-5848-03 Yes December, 2010
Availability Guide and
Reference
Data Servers, Databases, SC23-5849-03 Yes December, 2010
and Database Objects
Guide
Database Security Guide SC23-5850-03 Yes December, 2010
Developing ADO.NET SC23-5851-02 Yes April, 2009
and OLE DB
Applications
Developing Embedded SC23-5852-02 Yes April, 2009
SQL Applications
Developing Java SC23-5853-03 Yes December, 2010
Applications
Developing Perl and SC23-5854-02 No April, 2009
PHP Applications
Developing User-defined SC23-5855-03 Yes December, 2010
Routines (SQL and
External)
Printed versions of many of the DB2 books available on the DB2 PDF
Documentation DVD can be ordered for a fee from IBM. Depending on where you
are placing your order from, you may be able to order books online, from the IBM
Publications Center. If online ordering is not available in your country or region,
you can always order printed DB2 books from your local IBM representative. Note
that not all books on the DB2 PDF Documentation DVD are available in print.
Note: The most up-to-date and complete DB2 documentation is maintained in the
DB2 Information Center at http://publib.boulder.ibm.com/infocenter/db2luw/
v9r5.
To invoke SQL state help, open the command line processor and enter:
? sqlstate or ? class code
where sqlstate represents a valid five-digit SQL state and class code represents the
first two digits of the SQL state.
For example, ? 08003 displays help for the 08003 SQL state, and ? 08 displays help
for the 08 class code.
For DB2 Version 9.7 topics, the DB2 Information Center URL is http://
publib.boulder.ibm.com/infocenter/db2luw/v9r7/.
For DB2 Version 9.5 topics, the DB2 Information Center URL is http://
publib.boulder.ibm.com/infocenter/db2luw/v9r5.
For DB2 Version 9.1 topics, the DB2 Information Center URL is http://
publib.boulder.ibm.com/infocenter/db2luw/v9/.
For DB2 Version 8 topics, go to the DB2 Information Center URL at:
http://publib.boulder.ibm.com/infocenter/db2luw/v8/.
Note: Adding a language does not guarantee that the computer has the
fonts required to display the topics in the preferred language.
– To move a language to the top of the list, select the language and click the
Move Up button until the language is first in the list of languages.
3. Clear the browser cache and then refresh the page to display the DB2
Information Center in your preferred language.
v To display topics in your preferred language in a Firefox or Mozilla browser:
1. Select the button in the Languages section of the Tools —> Options —>
Advanced dialog. The Languages panel is displayed in the Preferences
window.
2. Ensure your preferred language is specified as the first entry in the list of
languages.
– To add a new language to the list, click the Add... button to select a
language from the Add Languages window.
– To move a language to the top of the list, select the language and click the
Move Up button until the language is first in the list of languages.
3. Clear the browser cache and then refresh the page to display the DB2
Information Center in your preferred language.
On some browser and operating system combinations, you might have to also
change the regional settings of your operating system to the locale and language of
your choice.
To update the DB2 Information Center installed on your computer or intranet server:
1. Stop the DB2 Information Center.
v On Windows, click Start → Control Panel → Administrative Tools → Services.
Then right-click on DB2 Information Center service and select Stop.
v On Linux, enter the following command:
/etc/init.d/db2icdv95 stop
2. Start the Information Center in stand-alone mode.
v On Windows:
a. Open a command window.
b. Navigate to the path where the Information Center is installed. By
default, the DB2 Information Center is installed in the
Program_files\IBM\DB2 Information Center\Version 9.5 directory,
where Program_files represents the location of the Program Files directory.
c. Navigate from the installation directory to the doc\bin directory.
d. Run the help_start.bat file:
help_start.bat
v On Linux:
a. Navigate to the path where the Information Center is installed. By
default, the DB2 Information Center is installed in the /opt/ibm/db2ic/V9.5
directory.
b. Navigate from the installation directory to the doc/bin directory.
c. Run the help_start script:
help_start
The systems default Web browser launches to display the stand-alone
Information Center.
3. Click the Update button ( ). On the right hand panel of the Information
Center, click Find Updates. A list of updates for existing documentation
displays.
4. To initiate the installation process, check the selections you want to install, then
click Install Updates.
5. After the installation process has completed, click Finish.
6. Stop the stand-alone Information Center:
Note: The help_end batch file contains the commands required to safely
terminate the processes that were started with the help_start batch file. Do
not use Ctrl-C or any other method to terminate help_start.bat.
v On Linux, navigate to the installation directory's doc/bin directory, and run
the help_end script:
help_end
The updated DB2 Information Center displays the new and updated topics.
DB2 tutorials
The DB2 tutorials help you learn about various aspects of DB2 products. Lessons
provide step-by-step instructions.
You can view the XHTML version of the tutorial from the Information Center at
http://publib.boulder.ibm.com/infocenter/db2help/.
Some lessons use sample data or code. See the tutorial for a description of any
prerequisites for its specific tasks.
DB2 tutorials
Personal use: You may reproduce these Publications for your personal, non
commercial use provided that all proprietary notices are preserved. You may not
distribute, display or make derivative work of these Publications, or any portion
thereof, without the express consent of IBM.
Commercial use: You may reproduce, distribute and display these Publications
solely within your enterprise provided that all proprietary notices are preserved.
You may not make derivative works of these Publications, or reproduce, distribute
or display these Publications or any portion thereof outside your enterprise,
without the express consent of IBM.
IBM reserves the right to withdraw the permissions granted herein whenever, in its
discretion, the use of the Publications is detrimental to its interest or, as
determined by IBM, the above instructions are not being properly followed.
You may not download, export or re-export this information except in full
compliance with all applicable laws and regulations, including all United States
export laws and regulations.
IBM may not offer the products, services, or features discussed in this document in
other countries. Consult your local IBM representative for information on the
products and services currently available in your area. Any reference to an IBM
product, program, or service is not intended to state or imply that only that IBM
product, program, or service may be used. Any functionally equivalent product,
program, or service that does not infringe any IBM intellectual property right may
be used instead. However, it is the user's responsibility to evaluate and verify the
operation of any non-IBM product, program, or service.
IBM may have patents or pending patent applications covering subject matter
described in this document. The furnishing of this document does not give you
any license to these patents. You can send license inquiries, in writing, to:
For license inquiries regarding double-byte (DBCS) information, contact the IBM
Intellectual Property Department in your country/region or send inquiries, in
writing, to:
The following paragraph does not apply to the United Kingdom or any other
country/region where such provisions are inconsistent with local law:
INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS
PUBLICATION “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS
FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or
implied warranties in certain transactions; therefore, this statement may not apply
to you.
This document may provide links or references to non-IBM Web sites and
resources. IBM makes no representations, warranties, or other commitments
whatsoever about any non-IBM Web sites or third-party resources that may be
referenced, accessible from, or linked from this document. A link to a non-IBM
Web site does not mean that IBM endorses the content or use of such Web site or
IBM may use or distribute any of the information you supply in any way it
believes appropriate without incurring any obligation to you.
Licensees of this program who wish to have information about it for the purpose
of enabling: (i) the exchange of information between independently created
programs and other programs (including this one) and (ii) the mutual use of the
information that has been exchanged, should contact:
The licensed program described in this document and all licensed material
available for it are provided by IBM under terms of the IBM Customer Agreement,
IBM International Program License Agreement, or any equivalent agreement
between us.
All statements regarding IBM's future direction or intent are subject to change or
withdrawal without notice, and represent goals and objectives only.
This information may contain examples of data and reports used in daily business
operations. To illustrate them as completely as possible, the examples include the
names of individuals, companies, brands, and products. All of these names are
fictitious, and any similarity to the names and addresses used by an actual
business enterprise is entirely coincidental.
COPYRIGHT LICENSE:
Each copy or any portion of these sample programs or any derivative work must
include a copyright notice as follows:
© (your company name) (year). Portions of this code are derived from IBM Corp.
Sample Programs. © Copyright IBM Corp. _enter the year or years_. All rights
reserved.
Trademarks
IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of
International Business Machines Corp., registered in many jurisdictions worldwide.
Other product and service names might be trademarks of IBM or other companies.
A current list of IBM trademarks is available on the Web at Copyright and
trademark information at www.ibm.com/legal/copytrade.shtml.
A C
alternative security mechanism CallableStatement class 58
IBM Data Server Driver for JDBC and SQLJ 178 client affinities
applets .NET 224, 237
JDBC CLI 224, 237
building 191 IBM Data Server Driver for JDBC and SQLJ 224, 237, 238
SQLJ client affinities, example of enabling
building 193 Java clients 225, 238
usage 194 client application
application development automatic client reroute 215
high availability high availability 215
connections to IDS 236 transaction-level load balancing 215
direct connections to DB2 for z/OS servers 248 client configuration, automatic client reroute support
JDBC DB2 Database for Linux, UNIX, and Windows 216
application programming 21 client configuration, high-availability support
SQLJ 113 IDS 228
application programming for high availability client configuration, Sysplex workload balancing
connections to DB2 Database for Linux, UNIX, and DB2 for z/OS 242
Windows 223 client info properties
applications IBM Data Server Driver for JDBC and SQLJ 84, 85
Java 2 Platform, Enterprise Edition 249 clients
ARRAY parameters automatic client reroute
invoking stored procedures from JDBC programs 74 connections to DB2 for z/OS 247
invoking stored procedures from SQLJ programs 153 connections to IDS 232
assignment-clause commands
SQLJ 363 db2sqljbind 506
auto-generated keys db2sqljprint 512
retrieving for DELETE, JDBC application 79 sqlj 491
retrieving for INSERT, JDBC application 77 SQLJ 491
retrieving for MERGE, JDBC application 79 comments
retrieving for UPDATE, JDBC application 79 SQLJ applications 123
retrieving in JDBC application 76 commits
autocommit modes SQLJ transactions 163
default JDBC 100 transactions
automatic client reroute JDBC 99
client applications 215 configuration
DB2 for z/OS 247 JDBC 16
IDS servers 232 SQLJ 16
automatic client reroute support, client operation 220 configuration properties
automatically generated keys customizing 16
retrieving details 312
DELETE statement, JDBC application 79 parameters 16
INSERT statement, JDBC application 77 connection context
JDBC applications 76 class 115
MERGE statement, JDBC application 79 closing 164
UPDATE statement, JDBC application 79 default 115
object 115
connection declaration clause
B SQLJ 357
batch queries connection pooling
JDBC 47 overview 259
Index 529
isolation levels JDBC (continued)
JDBC 99 configuring 16
SQLJ 162 connections 33
iterator conversion clause data type mappings 261
SQLJ 364 DB2 for z/OS servers 17
iterator declaration clause drivers
SQLJ 357 details 2
iterators differences 464, 474, 479
obtaining JDBC result sets from 147 environment variables 16
positioned DELETE 124 executeUpdate methods 40
positioned UPDATE 124 executing SQL 37
extensions 388
IBM Data Server Driver for JDBC and SQLJ installation 5
J isolation levels 99
named parameter markers 80, 82
Java
named parameters 60
applets
objects
building (JDBC) 191
creating 38
building (SQLJ) 193
modifying 38
using 194
optimistic locking 87
applications
problem diagnosis 199
accessing z/OS servers 17
ResultSet holdability 51
building 191
ResultSets
building (JDBC) 191
delete holes 56
building (overview) 191
holdability 50
building (SQLJ) 193
inserting row 57, 58
overview 1
routines
distributed transactions 256
building (procedure) 192
Enterprise Java Beans 257
scrollable ResultSet 50, 51
environment
SQLWarning 106
customization 16
transactions
routines
committing 99
building (JDBC) 192
default autocommit modes 100
building (SQLJ) 196
rolling back 99
Java 2 Platform, Enterprise Edition
updatable ResultSet 50, 51
application support 249
JNDI (Java Naming and Directory Interface)
containers 250
details 251
database requirements 251
JTA (Java Transaction API) 251
Enterprise Java Beans 257
JTS (Java Transaction Service) 251
overview 249
requirements 251
server 250
transaction management 251 K
Java Naming and Directory Interface (JNDI) Kerberos authentication protocol
details 251 IBM Data Server Driver for JDBC and SQLJ 173
Java Transaction API (JTA) 251
Java Transaction Service (JTS) 251
JDBC
4.0
L
large objects (LOBs)
getColumnLabel change 477
compatible Java data types
getColumnName change 477
JDBC applications 70
accessing packages 35
SQLJ applications 146
APIs 326
IBM Data Server Driver for JDBC and SQLJ 66, 68, 145
applets
locators
building 191
IBM Data Server Driver for JDBC and SQLJ 67, 68
using 194
SQLJ 145
applications
24 as hour value 267
building 191
data retrieval 45 M
example 21 monitoring
invalid Gregorian date 267 system
programming overview 21 IBM Data Server Driver for JDBC and SQLJ 209
transaction control 99 multi-row operations 54
variables 37 multiple result sets
batch errors 107 retrieving from stored procedure in JDBC application
batch queries 47 keeping result sets open 64
batch updates 41 known number 62
Index 531
scrollable ResultSets SQLJ (continued)
JDBC 50 host expressions 122, 354
SDKs implements clause 355
differences 481 installing runtime environment 16
version 1.5 160 isolation levels 162
security iterator conversion clause 364
DB2 JDBC Type 2 Driver 189 iterator declaration clause 357
IBM Data Server Driver for JDBC and SQLJ multiple instances of iterator 139
encrypted security-sensitive data 171 multiple iterators on table 138
encrypted user ID or encrypted password 171 problem diagnosis 199
Kerberos 173 Profile Binder command 506
security mechanisms 167 Profile Printer command 512
user ID and password 169 program preparation 491
user ID only 170 result set iterator 133
plug-ins retrieving SQLCA 163
JDBC support 176 routines
SQLJ program preparation 186 compiler options (UNIX) 196
SET TRANSACTION clause 362 compiler options (Windows) 197
setTransactionTimeout method 256 scrollable iterators 140
SQL statements SDK for Java Version 5 functions 160
displaying help 517 security 186
error handling SET TRANSACTION clause 362
SQLJ applications 163 SQLWarning 164
executing statement reference 354
JDBC interfaces 37 transactions 163
SQLJ applications 124, 151 translator command 491
SQLException variable names 122
DB2 JDBC Type 2 Driver 109 with-clause 355
IBM Data Server Driver for JDBC and SQLJ 103 sqlj command 491
SQLJ SQLJ variable names
accessing packages for 121 restrictions 122
applets sqlj.runtime package 364
building 193 sqlj.runtime.AsciiStream 376, 386
using 194 sqlj.runtime.BinaryStream 376
applications sqlj.runtime.CharacterStream 377
24 as hour value 267 sqlj.runtime.ConnectionContext 365
building 193 sqlj.runtime.ExecutionContext 378
compiler options (UNIX) 195 sqlj.runtime.ForUpdate 370
compiler options (Windows) 195 sqlj.runtime.NamedIterator 370
examples 113 sqlj.runtime.PositionedIterator 371
invalid Gregorian date 267 sqlj.runtime.ResultSetIterator 371
programming 113 sqlj.runtime.Scrollable 374
transaction control 162 sqlj.runtime.SQLNullException 386
assignment clause 363 sqlj.runtime.UnicodeStream 387
batch updates 129 SQLSTATE
building routines 196 IBM Data Server Driver for JDBC and SQLJ errors 488
calling stored procedures 143 SQLWarning
clauses 354 DB2 JDBC Type 2 Driver 109
collecting trace data 199 IBM Data Server Driver for JDBC and SQLJ 106
comments 123 SQLJ applications 164
connecting to data source 115 SSID
connecting using default context 121 IBM Data Server Driver for JDBC and SQLJ 312
connection declaration clause 357 SSL
context clause 359, 360 configuring
DataSource interface 118, 120 Java Runtime Environment 183
DB2 tables IBM Data Server Driver for JDBC and SQLJ 182
creating 124 sslConnection property 182
modifying 124 sslConnection property 182
DriverManager interface 115, 117 Statement.executeQuery 45
drivers 2 stored procedures
environment variables 16 calling
error handling 163 CallableStatement class 58
executable clauses 359 JDBC applications 74
executing SQL 124 SQLJ applications 143, 153
execution context 151 DB2 for z/OS 58
execution control 151 keeping result sets open in JDBC applications 64
existing connections 121
T X
terms and conditions
use of publications 521 XML
time value adjustment IBM Data Server Driver for JDBC and SQLJ 155
JDBC applications 267 parameters
SQLJ applications 267 invoking routines from Java programs 95
trace controller 211 XML data
traces Java applications 89
IBM Data Server Driver for JDBC and SQLJ 199, 201 updating
transaction control tables in Java applications 90, 156
JDBC 99 XML data retrieval
SQLJ 162 Java applications 92, 157
transaction-level load balancing XML schemas
client application 215 registering 97
troubleshooting removing 97
online information 520 XMLCAST
tutorials 520 SQLJ applications 159
trusted contexts
JDBC support 180
tutorials
problem determination 520
troubleshooting 520
Visual Explain 520
U
UNIX
SQLJ applications 195
SQLJ routines 196
updatable ResultSet
inserting row 57
JDBC 50, 51
testing for delete hole 56
testing for inserted row 58
updates
data
PreparedStatement.executeUpdate method 39
DB2 Information Center 518
URL format
DB2BaseDataSource class 27, 29
user ID and password security
IBM Data Server Driver for JDBC and SQLJ 169
user ID-only security
IBM Data Server Driver for JDBC and SQLJ 170
V
Visual Explain
tutorial 520
Index 533
534 Developing Java Applications
Printed in USA
SC23-5853-03
Spine information:
DB2 Version 9.5 for Linux, UNIX, and Windows Version 9 Release 5 Developing Java Applications