For Linux, Unix, and Windows: Call Level Interface Guide and Reference, 1
For Linux, Unix, and Windows: Call Level Interface Guide and Reference, 1
DB2 Version 9
for Linux, UNIX, and Windows
SC10-4224-00
DB2 ®
DB2 Version 9
for Linux, UNIX, and Windows
SC10-4224-00
Before using this information and the product it supports, be sure to read the general information under Notices.
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 International Business Machines Corporation 1993, 2006. All rights reserved.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract
with IBM Corp.
Contents
Part 1. CLI background information 1 Cursors in CLI applications . . . . . . . . 65
Cursor considerations for CLI applications . . . 68
Result sets . . . . . . . . . . . . . . . 70
Chapter 1. Introduction to CLI . . . . . 3 Result set terminology in CLI applications . . . 70
Introduction to DB2 CLI and ODBC . . . . . . 3 Rowset retrieval examples in CLI applications . . 71
DB2 Call Level Interface (CLI) versus embedded SQL 4 Specifying the rowset returned from the result set 73
DB2 CLI and ODBC drivers . . . . . . . . . 7 Retrieving data with scrollable cursors in a CLI
application . . . . . . . . . . . . . 76
Chapter 2. DB2 CLI and ODBC . . . . . 9 Bookmarks . . . . . . . . . . . . . . 78
Comparison of DB2 CLI and Microsoft ODBC . . . 9 Bookmarks in CLI applications . . . . . . . 78
Retrieving data with bookmarks in a CLI
application . . . . . . . . . . . . . 79
Part 2. Programming CLI
applications . . . . . . . . . . . . 13 Chapter 6. Array input and output . . . 81
Array input . . . . . . . . . . . . . . 81
Chapter 3. Writing a basic CLI Binding parameter markers in CLI applications
application . . . . . . . . . . . . . 15 with column-wise array input . . . . . . . 81
Initialization . . . . . . . . . . . . . . 15 Binding parameter markers in CLI applications
Handles in CLI . . . . . . . . . . . . 15 with row-wise array input . . . . . . . . 82
Initialization and termination in CLI overview. . 17 Parameter diagnostic information in CLI
Initializing CLI applications . . . . . . . . 18 applications . . . . . . . . . . . . . 83
Transaction processing . . . . . . . . . . . 20 Changing parameter bindings in CLI applications
Transaction processing in CLI overview . . . . 20 with offsets . . . . . . . . . . . . . 84
Allocating statement handles in CLI applications 22 Array output . . . . . . . . . . . . . . 85
Issuing SQL statements in CLI applications . . . 23 Column binding in CLI applications . . . . . 85
Preparing and executing SQL statements in CLI Result set retrieval into arrays in CLI applications 87
applications . . . . . . . . . . . . . 24 Retrieving array data in CLI applications using
Deferred prepare in CLI applications . . . . . 26 column-wise binding . . . . . . . . . . 89
Parameter marker binding in CLI applications . . 26 Retrieving array data in CLI applications using
Binding parameter markers in CLI applications 29 row-wise binding . . . . . . . . . . . 90
Commit modes in CLI applications . . . . . 30 Changing column bindings in a CLI application
When to call the CLI SQLEndTran() function . . 32 with column binding offsets . . . . . . . . 91
Retrieving query results in CLI applications . . 33
Updating and deleting data in CLI applications 35 Chapter 7. Working with large amounts
Freeing statement resources in CLI applications 37 of data . . . . . . . . . . . . . . . 93
Handle freeing in CLI applications . . . . . 38
Specifying parameter values at execute time for long
Data types and data conversion in CLI
data manipulation in CLI applications . . . . . 93
applications . . . . . . . . . . . . . 39
Data retrieval in pieces in CLI applications . . . . 95
SQL symbolic and default data types for CLI
Large object usage in CLI applications . . . . . 96
applications . . . . . . . . . . . . . 41
LOB locators in CLI applications . . . . . . . 98
C data types for CLI applications . . . . . . 43
Fetching LOB data with LOB locators in CLI
String handling in CLI applications . . . . . 47
applications . . . . . . . . . . . . . . 99
Diagnostics in CLI applications overview . . . 49
Direct file input and output for LOB handling in
CLI function return codes . . . . . . . . 50
CLI applications . . . . . . . . . . . . 101
SQLSTATES for DB2 CLI . . . . . . . . . 51
LOB usage in ODBC applications . . . . . . . 102
Termination . . . . . . . . . . . . . . 53
Bulk data manipulation . . . . . . . . . . 103
Terminating a CLI application . . . . . . . 53
Long data for bulk inserts and updates in CLI
applications . . . . . . . . . . . . . 103
Chapter 4. Programming hints and tips 55 Retrieving bulk data with bookmarks using
Programming hints and tips for CLI applications . . 55 SQLBulkOperations() in CLI applications . . . 105
Reduction of network flows with CLI array input Inserting bulk data with bookmarks using
chaining . . . . . . . . . . . . . . . 62 SQLBulkOperations() in CLI applications . . . 106
Updating bulk data with bookmarks using
Chapter 5. Cursors . . . . . . . . . 65 SQLBulkOperations() in CLI applications . . . 107
Cursors . . . . . . . . . . . . . . . . 65
Chapter 30. Configuring the IBM DB2 Chapter 35. CLI/ODBC configuration
Driver for ODBC and CLI . . . . . . 249 keywords . . . . . . . . . . . . . 277
Configuring the IBM DB2 Driver for ODBC and db2cli.ini initialization file . . . . . . . . . 277
CLI . . . . . . . . . . . . . . . . . 249 CLI/ODBC configuration keywords listing by
Configuring environment variables for the IBM category . . . . . . . . . . . . . . . 279
DB2 Driver for ODBC and CLI . . . . . . . 250 AllowGetDataLOBReaccess CLI/ODBC
Configuring environment variables for the IBM configuration keyword . . . . . . . . . . 284
DB2 Driver for ODBC and CLI . . . . . . 250 AltHostName CLI/ODBC configuration keyword 284
Environment variables supported by the IBM AltPort CLI/ODBC configuration keyword . . . 285
DB2 Driver for ODBC and CLI . . . . . . 251 AppendAPIName CLI/ODBC configuration
db2oreg1.exe overview . . . . . . . . . . 252 keyword . . . . . . . . . . . . . . . 285
Registering the IBM DB2 Driver for ODBC and CLI AppendRowColToErrorMessage CLI/ODBC
with the Microsoft DTC . . . . . . . . . . 253 configuration keyword . . . . . . . . . . 286
Registering the IBM DB2 Driver for ODBC and CLI AppendForFetchOnly CLI/ODBC configuration
with the Microsoft ODBC driver manager . . . . 254 keyword . . . . . . . . . . . . . . . 287
AppUsesLOBLocator CLI/ODBC configuration
Chapter 31. Connecting to databases keyword . . . . . . . . . . . . . . . 287
with the IBM DB2 Driver for ODBC ArrayInputChain CLI/ODBC configuration
keyword . . . . . . . . . . . . . . . 288
and CLI . . . . . . . . . . . . . . 257
Contents v
AsyncEnable CLI/ODBC configuration keyword 289 DisableKeysetCursor CLI/ODBC configuration
Authentication CLI/ODBC configuration keyword 290 keyword . . . . . . . . . . . . . . . 321
AutoCommit CLI/ODBC configuration keyword 290 DisableMultiThread CLI/ODBC configuration
BIDI CLI/ODBC configuration keyword . . . . 291 keyword . . . . . . . . . . . . . . . 322
BitData CLI/ODBC configuration keyword . . . 292 DisableUnicode CLI/ODBC configuration keyword 322
BlockForNRows CLI/ODBC configuration DSN CLI/ODBC configuration keyword . . . . 323
keyword . . . . . . . . . . . . . . . 292 FileDSN CLI/ODBC configuration keyword . . . 323
BlockLobs CLI/ODBC configuration keyword . . 293 FloatPrecRadix CLI/ODBC configuration keyword 324
CheckForFork CLI/ODBC configuration keyword 294 GranteeList CLI/ODBC configuration keyword . . 324
ClientAcctStr CLI/ODBC configuration keyword 294 GrantorList CLI/ODBC configuration keyword . . 325
ClientApplName CLI/ODBC configuration Graphic CLI/ODBC configuration keyword . . . 326
keyword . . . . . . . . . . . . . . . 295 Hostname CLI/ODBC configuration keyword . . 327
ClientBuffersUnboundLOBS CLI/ODBC IgnoreWarnings CLI/ODBC configuration keyword 327
configuration keyword . . . . . . . . . . 296 IgnoreWarnList CLI/ODBC configuration keyword 328
ClientUserID CLI/ODBC configuration keyword 297 Instance CLI/ODBC configuration keyword . . . 328
ClientWrkStnName CLI/ODBC configuration Interrupt CLI/ODBC configuration keyword . . . 329
keyword . . . . . . . . . . . . . . . 298 KeepDynamic CLI/ODBC configuration keyword 329
CLIPkg CLI/ODBC configuration keyword . . . 299 KRBPlugin CLI/ODBC configuration keyword . . 330
ConnectNode CLI/ODBC configuration keyword 299 LoadXAInterceptor CLI/ODBC configuration
ConnectTimeout CLI/ODBC configuration keyword . . . . . . . . . . . . . . . 330
keyword . . . . . . . . . . . . . . . 300 LOBCacheSize CLI/ODBC configuration keyword 331
ConnectType CLI/ODBC configuration keyword 301 LOBFileThreshold CLI/ODBC configuration
CurrentFunctionPath CLI/ODBC configuration keyword . . . . . . . . . . . . . . . 332
keyword . . . . . . . . . . . . . . . 302 LOBMaxColumnSize CLI/ODBC configuration
CurrentImplicitXMLParseOption CLI/ODBC keyword . . . . . . . . . . . . . . . 332
configuration keyword . . . . . . . . . . 302 LockTimeout CLI/ODBC configuration keyword 333
CurrentMaintainedTableTypesForOpt CLI/ODBC LongDataCompat CLI/ODBC configuration
configuration keyword . . . . . . . . . . 303 keyword . . . . . . . . . . . . . . . 333
CurrentPackagePath CLI/ODBC configuration MapBigintCDefault CLI/ODBC configuration
keyword . . . . . . . . . . . . . . . 304 keyword . . . . . . . . . . . . . . . 334
CurrentPackageSet CLI/ODBC configuration MapCharToWChar CLI/ODBC configuration
keyword . . . . . . . . . . . . . . . 305 keyword . . . . . . . . . . . . . . . 335
CurrentRefreshAge CLI/ODBC configuration MapDateCDefault CLI/ODBC configuration
keyword . . . . . . . . . . . . . . . 306 keyword . . . . . . . . . . . . . . . 336
CurrentSchema CLI/ODBC configuration keyword 306 MapDateDescribe CLI/ODBC configuration
CurrentSQLID CLI/ODBC configuration keyword 306 keyword . . . . . . . . . . . . . . . 337
CursorHold CLI/ODBC configuration keyword 307 MapDecimalFloatDescribe CLI/ODBC
CursorTypes CLI/ODBC configuration keyword 308 configuration keyword . . . . . . . . . . 338
Database CLI/ODBC configuration keyword . . . 309 MapGraphicDescribe CLI/ODBC configuration
DateTimeStringFormat CLI/ODBC configuration keyword . . . . . . . . . . . . . . . 339
keyword . . . . . . . . . . . . . . . 310 MapTimeCDefault CLI/ODBC configuration
DB2Degree CLI/ODBC configuration keyword . . 311 keyword . . . . . . . . . . . . . . . 340
DB2Explain CLI/ODBC configuration keyword . . 311 MapTimeDescribe CLI/ODBC configuration
DB2NETNamedParam CLI/ODBC configuration keyword . . . . . . . . . . . . . . . 340
keyword . . . . . . . . . . . . . . . 312 MapTimestampCDefault CLI/ODBC configuration
DB2Optimization CLI/ODBC configuration keyword . . . . . . . . . . . . . . . 342
keyword . . . . . . . . . . . . . . . 313 MapTimestampDescribe CLI/ODBC configuration
DBAlias CLI/ODBC configuration keyword . . . 313 keyword . . . . . . . . . . . . . . . 342
DBName CLI/ODBC configuration keyword . . . 314 MapXMLCDefault CLI/ODBC configuration
DecimalFloatRoundingMode CLI/ODBC keyword . . . . . . . . . . . . . . . 343
configuration keyword . . . . . . . . . . 315 MapXMLDescribe CLI/ODBC configuration
DeferredPrepare CLI/ODBC configuration keyword . . . . . . . . . . . . . . . 344
keyword . . . . . . . . . . . . . . . 316 MaxLOBBlockSize CLI/ODBC configuration
DescribeCall CLI/ODBC configuration keyword 317 keyword . . . . . . . . . . . . . . . 345
DescribeInputOnPrepare CLI/ODBC configuration Mode CLI/ODBC configuration keyword . . . . 346
keyword . . . . . . . . . . . . . . . 318 NotifyLevel CLI/ODBC configuration keyword 346
DescribeOutputLevel CLI/ODBC configuration OleDbReportIsLongForLongTypes CLI/ODBC
keyword . . . . . . . . . . . . . . . 318 configuration keyword . . . . . . . . . . 347
DescribeParam CLI/ODBC configuration keyword 320 OleDbReturnCharAsWChar CLI/ODBC
DiagLevel CLI/ODBC configuration keyword . . 321 configuration keyword . . . . . . . . . . 348
DiagPath CLI/ODBC configuration keyword . . . 321
Contents vii
viii CLI Guide and Reference, Volume 1
Part 1. CLI background information
The DB2 CLI driver also acts as an ODBC driver when loaded by an ODBC driver
manager. It conforms to ODBC 3.51.
The X/Open Company and the SQL Access Group jointly developed a specification
for a callable SQL interface referred to as the X/Open Call Level Interface. The goal of
this interface is to increase the portability of applications by enabling them to
become independent of any one database vendor’s programming interface. Most of
the X/Open Call Level Interface specification has been accepted as part of the ISO
Call Level Interface International Standard (ISO/IEC 9075-3:1995 SQL/CLI).
The DB2 CLI load library can be loaded as an ODBC driver by an ODBC driver
manager. For ODBC application development, you must obtain an ODBC Software
Development Kit. For the Windows® platform, the ODBC SDK is available as part
of the Microsoft Data Access Components (MDAC) SDK, available for download
from http://www.microsoft.com/data/. For non-Windows platforms, the ODBC
SDK is provided by other vendors. When developing ODBC applications that may
connect to DB2 servers, use the Call Level Interface Guide and Reference, Volume
1 and the Call Level Interface Guide and Reference, Volume 2 (for information on
DB2 specific extensions and diagnostic information), in conjunction with the ODBC
Programmer’s Reference and SDK Guide available from Microsoft.
Applications written directly to DB2 CLI link directly to the DB2 CLI load library.
DB2 CLI includes support for many ODBC and ISO SQL/CLI functions, as well as
DB2 specific functions.
The following DB2 features are available to both ODBC and DB2 CLI applications:
v double byte (graphic) data types
v stored procedures
v Distributed Unit of Work (DUOW), two phase commit
v compound SQL
v user defined types (UDT)
v user defined functions (UDF)
Related concepts:
v “Comparison of DB2 CLI and Microsoft ODBC” on page 9
v “DB2 Call Level Interface (CLI) versus embedded SQL” on page 4
and
When deciding whether to create your applications using DB2 CLI or embedded
SQL, consider the following strengths and weaknesses of DB2 CLI and embedded
SQL:
v DB2 CLI applications are easier to deploy and compatible across database
management systems:
– Embedded SQL applications must be precompiled, and are therefore
dependant on precompiler software. DB2 CLI applications do not need to be
precompiled.
– You must bind embedded SQL applications to target databases, but you do
not need to bind CLI applications to target databases. There are bind files
shipped with DB2 CLI that need to be bound to target databases once for all
CLI applications.
– CLI provides a consistent interface to query catalog information contained in
DBMS catalog tables; and the result sets returned are consistent across
DBMSs. There is no such consistent interface available with embedded SQL.
v DB2 CLI is more flexible at runtime:
– You can use parameter markers in CLI applications, but not in embedded
SQL applications. CLI applications can process statements with parameter
markers, and obtain data type information for those parameters using
describe information.
– CLI provides enhanced parameter input and fetching capability, allowing
arrays of data to be specified on input, retrieving multiple rows of a result set
directly into an array, and executing statements that generate multiple result
sets.
v Some functionality is easier to achieve using DB2 CLI than using embedded
SQL:
– CLI objects like connection handles allow you to easily connect to multiple
databases, and have multiple connections to the same database in a CLI
application. To do the same thing in an embedded SQL application, you must
use multi-threading, which entails using DB2 context management APIs to be
thread-safe.
See: Mixed multithreaded CLI applications
– Cursor management can be easier with DB2 CLI than with embedded SQL.
For example, DB2 CLI does not require the explicit declaration of cursors, it
has a pool or cursors that get used as needed. Also, you do not need to open
cursors in CLI applications, the execution of a SELECT statement
automatically causes a cursor to be opened. Finally, CLI has more extensive
support for scrollable cursors, including using scrollable cursors with array
output.
– Embedded SQL applications use complex data areas, such as SQLDA and
SQLCA. DB2 CLI provides handles to reference the same kind of information.
For example, environment handles, connection handles, statement handles,
and descriptor handles provide a means to refer to information like global
variables, connection specific information, the parameters of an SQL
statement, or the columns of a result set.
New with DB2 Version 9, there is also a separate CLI and ODBC driver called the
IBM® DB2 Driver for ODBC and CLI. The IBM DB2 Driver for ODBC and CLI
provides runtime support for the DB2 CLI and ODBC APIs. However, this driver is
installed and configured separately, and supports a subset of the functionality of
the DB2 clients, such as connectivity, in addition to the CLI and ODBC API
support.
Information that applies to the CLI and ODBC driver that is part of the DB2 client
generally applies to the IBM DB2 Driver for ODBC and CLI too. However, there
are some restrictions and some functionality that is unique to the IBM DB2 Driver
for ODBC and CLI. Information that applies only to the IBM DB2 Driver for ODBC
and CLI will use the full title of the driver to distinguish it from general
information that applies to the ODBC and CLI driver that comes with the DB2
clients.
For more information about the IBM DB2 Driver for ODBC and CLI, see: IBM
DB2 Driver for ODBC and CLI overview.
Related concepts:
v Chapter 27, “IBM DB2 Driver for ODBC and CLI overview,” on page 241
v “Introduction to DB2 CLI and ODBC” on page 3
Figure 1 below compares DB2 CLI and the DB2 ODBC driver. The left side shows
an ODBC driver under the ODBC Driver Manager, and the right side illustrates
DB2 CLI, the callable interface designed for DB2 specific applications.
DB2 Client refers to all available DB2 Clients. DB2 refers to all DB2 Database for
Linux®, UNIX®, and Windows products.
Application Application
DBMS
B DB2
Server
DB2 Connect
DB2 (MVS)
SQL/DS
SQL/400
Other DRDA
DBMS
Isolation levels:
The following table map IBM RDBMs isolation levels to ODBC transaction
isolation levels. The SQLGetInfo() function indicates which isolation levels are
available.
Table 2. Isolation levels under ODBC
IBM isolation level ODBC isolation level
Cursor stability SQL_TXN_READ_COMMITTED
Repeatable read SQL_TXN_SERIALIZABLE_READ
Read stability SQL_TXN_REPEATABLE_READ
Uncommitted read SQL_TXN_READ_UNCOMMITTED
No commit (no equivalent in ODBC)
Note: SQLSetConnectAttr() and SQLSetStmtAttr() will return SQL_ERROR with an
SQLSTATE of HY009 if you try to set an unsupported isolation level.
Restriction:
Mixing ODBC and DB2 CLI features and function calls in an application is not
supported on the Windows 64-bit operating system.
Related concepts:
v “Introduction to DB2 CLI and ODBC” on page 3
v “Isolation levels” in SQL Reference, Volume 1
Related reference:
v “CLI function return codes” on page 50
v “SQL symbolic and default data types for CLI applications” on page 41
v “CLI and ODBC function summary” in Call Level Interface Guide and Reference,
Volume 2
Initialization
Handles in CLI
A CLI handle is a variable that refers to a data object allocated and managed by
DB2 CLI. Using handles relieves the application from having to allocate and
manage global variables or data structures, such as the SQLDA.
On operating systems that support multiple threads, applications can use the same
environment, connection, statement, or descriptor handle on different threads. DB2
CLI provides thread safe access for all handles and function calls. The application
itself might experience unpredictable behavior if the threads it creates do not
co-ordinate their use of DB2 CLI resources.
Related concepts:
v “Descriptors in CLI applications” on page 151
v “Handle freeing in CLI applications” on page 38
Related tasks:
v “Allocating statement handles in CLI applications” on page 22
v “Freeing statement resources in CLI applications” on page 37
v “Initializing CLI applications” on page 18
Related reference:
v “SQLDA (SQL descriptor area)” in SQL Reference, Volume 1
The termination task consists of disconnecting from the data source and freeing
those handles that were allocated during the initialization phase. The connection
handle should be freed before freeing the environment handle.
Allocate Connection
SQLAllocHandle() Initialization
Connect
SQLConnect()
or
SQLDriverConnect()
Transaction
Processing
}
Disconnect
SQLDisconnect()
Free Connection
Termination
SQLFreeHandle()
Free Environment
SQLFreeHandle()
Related concepts:
v “Handles in CLI” on page 15
v “Transaction processing in CLI overview” on page 20
Related reference:
v “SQLAllocHandle function (CLI) - Allocate handle” in Call Level Interface Guide
and Reference, Volume 2
v “SQLConnect function (CLI) - Connect to a data source” in Call Level Interface
Guide and Reference, Volume 2
v “SQLDisconnect function (CLI) - Disconnect from a data source” in Call Level
Interface Guide and Reference, Volume 2
v “SQLDriverConnect function (CLI) - (Expanded) Connect to a data source” in
Call Level Interface Guide and Reference, Volume 2
v “SQLFreeHandle function (CLI) - Free handle resources” in Call Level Interface
Guide and Reference, Volume 2
where SQL_NTS is a special string length value that indicates the referenced
string is null-terminated.
v SQLDriverConnect(): extended connect function that allows additional
connect options and offers Graphical User Interface support. For example:
char * connStr = "DSN=SAMPLE;UID=;PWD=;";
Now that your application has been initialized, you can proceed to processing
transactions.
Related concepts:
Chapter 3. Writing a basic CLI application 19
v “Handles in CLI” on page 15
v “Transaction processing in CLI overview” on page 20
Related reference:
v “Environment attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “SQLAllocHandle function (CLI) - Allocate handle” in Call Level Interface Guide
and Reference, Volume 2
v “SQLBrowseConnect function (CLI) - Get required attributes to connect to data
source” in Call Level Interface Guide and Reference, Volume 2
v “SQLConnect function (CLI) - Connect to a data source” in Call Level Interface
Guide and Reference, Volume 2
v “SQLDriverConnect function (CLI) - (Expanded) Connect to a data source” in
Call Level Interface Guide and Reference, Volume 2
v “SQLSetConnectAttr function (CLI) - Set connection attributes” in Call Level
Interface Guide and Reference, Volume 2
v “SQLSetEnvAttr function (CLI) - Set environment attribute” in Call Level Interface
Guide and Reference, Volume 2
Related samples:
v “clihandl.c -- How to allocate and free handles”
v “dbcongui.c -- How to connect to a database with a graphical user interface
(GUI)”
v “dbconn.c -- How to connect to and disconnect from a database”
Transaction processing
SQLAllocHandle()
Execute a Statement
SQLExecute()
SQLDescribeCol()
or
SQLColAttribute()
SQLBindCol()
SQLFetch()
SQLGetData()
SQLEndTran() SQLFreeHandle()
(Statement)
Related concepts:
v “Commit modes in CLI applications” on page 30
Prerequisites:
Before you begin allocating statement handles, you must allocate an environment
handle and a connection handle. This is part of the task of initializing your CLI
application.
Procedure:
After allocating environment, connection, and statement handles, you can now
prepare, issue, or execute SQL statements.
Related concepts:
v “Transaction processing in CLI overview” on page 20
Related tasks:
v “Initializing CLI applications” on page 18
v “Issuing SQL statements in CLI applications” on page 23
v “Preparing and executing SQL statements in CLI applications” on page 24
Related reference:
v “SQLAllocHandle function (CLI) - Allocate handle” in Call Level Interface Guide
and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
Related samples:
v “clihandl.c -- How to allocate and free handles”
Before you issue an SQL statement, ensure you have allocated a statement handle.
Procedure:
or
SQLExecDirect (hstmt, (SQLCHAR *) "SELECT deptname, location FROM org",
SQL_NTS);
v To issue multiple SQL statements on the same statement handle, either initialize
an array of SQLCHAR elements, where each element represents an individual
SQL statement, or initialize a single SQLCHAR variable that contains the
multiple statements delimited by a ″;″ character. For example:
SQLCHAR * multiple_stmts[] = {
(SQLCHAR *) "SELECT deptname, location FROM org",
(SQLCHAR *) "SELECT id, name FROM staff WHERE years > 5",
(SQLCHAR *) "INSERT INTO org VALUES (99,’Hudson’,20,’Western’,’Seattle’)"
};
or
SQLCHAR * multiple_stmts =
"SELECT deptname, location FROM org;
SELECT id, name FROM staff WHERE years > 5;
INSERT INTO org VALUES (99, ’Hudson’, 20, ’Western’, ’Seattle’)";
Note: When a list of SQL statements is specified, only one statement is executed
at a time, starting with the first statement in the list. Each subsequent
statement is executed in the order it appears. (To execute subsequent
statements, you must call SQLMoreResults().)
v To issue SQL statements with parameter markers, see Binding Parameter
Markers.
v To capture and convert SQL statements dynamically executed with DB2 CLI
(dynamic SQL) to static SQL, see Creating Static SQL.
Related concepts:
v “Parameter marker binding in CLI applications” on page 26
Related tasks:
v “Binding parameter markers in CLI applications” on page 29
v “Creating static SQL with CLI/ODBC/JDBC Static Profiling” on page 185
v “Allocating statement handles in CLI applications” on page 22
Related samples:
v “dbuse.c -- How to use a database”
Prerequisites:
Before preparing and executing your SQL statement or XQuery expression, ensure
you have allocated a statement handle for it.
Procedure:
Note: For XQuery expressions, you cannot specify parameter markers in the
expression itself. You can, however, use the XMLQUERY function to bind
parameter markers to XQuery variables. The values of the bound
parameter markers will then be passed to the XQuery expression
specified in XMLQUERY for execution.
3. Execute the prepared statement by calling SQLExecute().
Use this method when:
v The same SQL statement or XQuery expression will be executed repeatedly
(usually with different parameter values). This avoids having to prepare the
same statement or expression more than once. The subsequent executions make
use of the access plans already generated by the prepare, thus increasing driver
efficiency and delivering better application performance.
v The application requires information about the parameters or columns in the
result set prior to statement execution.
Note: For XQuery expressions, you cannot specify parameter markers in the
expression itself. You can, however, use the XMLQUERY function to bind
parameter markers to XQuery variables. The values of the bound
parameter markers will then be passed to the XQuery expression
specified in XMLQUERY for execution.
2. Prepare and execute the statement or expression by calling SQLExecDirect()
with the SQL statement or XQuery expression as the StatementText argument.
Related concepts:
v “Deferred prepare in CLI applications” on page 26
v “Transaction processing in CLI overview” on page 20
Related tasks:
v “Allocating statement handles in CLI applications” on page 22
Related reference:
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLExecDirect function (CLI) - Execute a statement directly” in Call Level
Interface Guide and Reference, Volume 2
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLMoreResults function (CLI) - Determine if there are more result sets” in
Call Level Interface Guide and Reference, Volume 2
v “SQLPrepare function (CLI) - Prepare a statement” in Call Level Interface Guide
and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
v “XMLQUERY scalar function” in SQL Reference, Volume 1
Related samples:
v “dbuse.c -- How to use a database”
When deferred prepare is on, the prepare request is not sent to the server until the
corresponding execute request is issued. The two requests are then combined into
one command/reply flow (instead of two) to minimize network flow and to
improve performance. Because of this behavior, any errors that would typically be
generated by SQLPrepare() will appear at execute time, and SQLPrepare() will
always return SQL_SUCCESS. Deferred prepare is of greatest benefit when the
application generates queries where the answer set is very small, and the overhead
of separate requests and replies is not spread across multiple blocks of query data.
Related tasks:
v “Preparing and executing SQL statements in CLI applications” on page 24
Related reference:
v “CLI function return codes” on page 50
v “DeferredPrepare CLI/ODBC configuration keyword” on page 316
v “SQLDescribeCol function (CLI) - Return a set of attributes for a column” in Call
Level Interface Guide and Reference, Volume 2
v “SQLDescribeParam function (CLI) - Return description of a parameter marker”
in Call Level Interface Guide and Reference, Volume 2
v “SQLPrepare function (CLI) - Prepare a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
The application must bind an application variable to each parameter marker in the
SQL statement before it executes that statement. Binding is carried out by calling
the SQLBindParameter() function with a number of arguments to indicate:
v the ordinal position of the parameter,
v the SQL type of the parameter,
v the type of parameter (input, output, or inout),
v the C data type of the variable,
v a pointer to the application variable,
v the length of the variable.
The bound application variable and its associated length are called deferred input
arguments because only the pointers are passed when the parameter is bound; no
data is read from the variable until the statement is executed. Deferred arguments
allow the application to modify the contents of the bound parameter variables, and
re-execute the statement with the new values.
By default, DB2 CLI does not verify the type of the parameter marker. If the
application indicates an incorrect type for the parameter marker, it could cause:
v an extra conversion by the DBMS
v an error at the DBMS which forces DB2 CLI to describe the statement being
executed and re-execute it, resulting in extra network traffic
v an error returned to the application if the statement cannot be described, or the
statement cannot be re-executed successfully.
Information about the parameter markers can be accessed using descriptors. If you
enable automatic population of the implementation parameter descriptor (IPD)
then information about the parameter markers will be collected. The statement
attribute SQL_ATTR_ENABLE_AUTO_IPD must be set to SQL_TRUE for this to
work.
After the SQL statement has been executed, and the results processed, the
application may wish to reuse the statement handle to execute a different SQL
statement. If the parameter marker specifications are different (number of
parameters, length or type) then SQLFreeStmt() should be called with
SQL_RESET_PARAMS to reset or clear the parameter bindings.
Related concepts:
v “Data types and data conversion in CLI applications” on page 39
v “Descriptors in CLI applications” on page 151
v “Handles in CLI” on page 15
v “Large object usage in CLI applications” on page 96
v “User-defined type (UDT) usage in CLI applications” on page 148
Related reference:
v “SQLBindFileToParam function (CLI) - Bind LOB file reference to LOB
parameter” in Call Level Interface Guide and Reference, Volume 2
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLFreeHandle function (CLI) - Free handle resources” in Call Level Interface
Guide and Reference, Volume 2
v “SQLFreeStmt function (CLI) - Free (or reset) a statement handle” in Call Level
Interface Guide and Reference, Volume 2
v “SQLNumParams function (CLI) - Get number of parameters in a SQL
statement” in Call Level Interface Guide and Reference, Volume 2
Related samples:
v “dbuse.c -- How to use a database”
v “dtlob.c -- How to read and write LOB data”
v “spclient.c -- Call various stored procedures”
v “tbmod.c -- How to modify table data”
Prerequisites:
Before you bind parameter markers, ensure you have initialized your application.
Procedure:
Related concepts:
v “Parameter marker binding in CLI applications” on page 26
Related tasks:
Related reference:
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
Related samples:
v “dbuse.c -- How to use a database”
v “tbmod.c -- How to modify table data”
Transactions are started implicitly with the first access to the database using
SQLPrepare(), SQLExecDirect(), SQLGetTypeInfo(), or any function that returns a
result set, such as catalog functions. At this point a transaction has begun, even if
the call failed.
/* set AUTOCOMMIT on */
sqlrc = SQLSetConnectAttr( hdbc,
SQL_ATTR_AUTOCOMMIT,
(SQLPOINTER)SQL_AUTOCOMMIT_ON, SQL_NTS) ;
/* ... */
/* ... */
/* ... */
Related concepts:
v “Catalog functions for querying system catalog information in CLI applications”
on page 167
v “Cursors in CLI applications” on page 65
v “DB2 as transaction manager in CLI applications” on page 138
v “Multisite updates (two phase commit) in CLI applications” on page 137
Related tasks:
v “Calling stored procedures from CLI applications” on page 113
v “Updating and deleting data in CLI applications” on page 35
Related reference:
v “SQLEndTran function (CLI) - End transactions of a connection or an
Environment” in Call Level Interface Guide and Reference, Volume 2
v “SQLExecDirect function (CLI) - Execute a statement directly” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetTypeInfo function (CLI) - Get data type information” in Call Level
Interface Guide and Reference, Volume 2
Related concepts:
v “Column binding in CLI applications” on page 85
v “Commit modes in CLI applications” on page 30
v “Cursors in CLI applications” on page 65
v “Handles in CLI” on page 15
v “Multisite updates (two phase commit) in CLI applications” on page 137
v “Parameter marker binding in CLI applications” on page 26
Related reference:
v “SQLDisconnect function (CLI) - Disconnect from a data source” in Call Level
Interface Guide and Reference, Volume 2
Related samples:
v “dbmcon.c -- How to use multiple databases”
v “dbuse.c -- How to use a database”
Prerequisites:
Before you retrieve results, ensure you have initialized your application and
prepared and executed the necessary SQL statements.
Procedure:
Note: Performing this step can reduce performance if done before the query
has been executed, because it forces CLI to describe the query’s columns.
Information about the result set’s columns is available after successful
execution, and describing the result set does not incur any additional
overhead if the describe is performed after successful execution.
2. Bind an application variable to each column of the result set, by calling
SQLBindCol(), ensuring that the variable type matches the column type. For
example:
struct
{
SQLINTEGER ind;
SQLSMALLINT val;
}
deptnumb; /* variable to be bound to the DEPTNUMB column */
struct
{
SQLINTEGER ind;
SQLCHAR val[15];
}
location; /* variable to be bound to the LOCATION column */
/* ... */
if (cliRC == SQL_NO_DATA_FOUND)
{
printf("\n Data not found.\n");
}
while (cliRC != SQL_NO_DATA_FOUND)
{
printf(" %-8d %-14.14s \n", deptnumb.val, location.val);
if (cliRC == SQL_NO_DATA_FOUND)
{
printf("\n Data not found.\n");
}
while (cliRC != SQL_NO_DATA_FOUND)
{
/* use SQLGetData() to get the results */
/* get data from column 1 */
cliRC = SQLGetData(hstmt,
1,
SQL_C_SHORT,
&deptnumb.val,
0,
&deptnumb.ind);
STMT_HANDLE_CHECK(hstmt, hdbc, cliRC);
Note: Applications perform better if columns are bound, rather than having
them retrieved as unbound columns using SQLGetData(). However, an
application may be constrained in the amount of long data it can retrieve
and handle at one time. If this is a concern, then SQLGetData() may be
the better choice.
Related concepts:
v “Data types and data conversion in CLI applications” on page 39
Related tasks:
v “Initializing CLI applications” on page 18
v “Preparing and executing SQL statements in CLI applications” on page 24
v “Retrieving array data in CLI applications using column-wise binding” on page
89
v “Retrieving array data in CLI applications using row-wise binding” on page 90
Related reference:
v “C data types for CLI applications” on page 43
v “CLI function return codes” on page 50
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLDescribeCol function (CLI) - Return a set of attributes for a column” in Call
Level Interface Guide and Reference, Volume 2
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
v “SQLGetData function (CLI) - Get data from a column” in Call Level Interface
Guide and Reference, Volume 2
v “SQLNumResultCols function (CLI) - Get number of result columns” in Call
Level Interface Guide and Reference, Volume 2
Related samples:
v “tbread.c -- How to read data from tables”
Prerequisites:
Before you perform a positioned update or delete operation, ensure that you have
initialized your CLI application.
Procedure:
Related tasks:
v “Initializing CLI applications” on page 18
v “Issuing SQL statements in CLI applications” on page 23
v “Preparing and executing SQL statements in CLI applications” on page 24
Related reference:
v “DELETE statement” in SQL Reference, Volume 2
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
Related samples:
v “spserver.c -- Definition of various types of stored procedures”
v “tbmod.c -- How to modify table data”
Prerequisites:
Before you can free statement resources, you must have initialized your CLI
application and allocated a statement handle.
Procedure:
To free statement resources with SQLFreeStmt(), you need to call SQLFreeStmt() for
each task (depending on how the application was implemented, all of these tasks
may not be necessary):
v To close the open cursor, call SQLCloseCursor(), or call SQLFreeStmt() with the
SQL_CLOSE Option and statement handle as arguments. This closes the cursor
and discards any pending results.
v To unbind column bindings, call SQLFreeStmt() with an Option of SQL_UNBIND
and the statement handle. This unbinds all columns for this statement handle
except the bookmark column.
v To unbind parameter bindings, call SQLFreeStmt() with an Option of
SQL_RESET_PARAMS and the statement handle. This releases all parameter
bindings for this statement handle.
v To free the statement handle, call SQLFreeStmt() with an Option of SQL_DROP
and the statement handle to be freed. This invalidates this statement handle.
Related concepts:
v “Handle freeing in CLI applications” on page 38
v “Handles in CLI” on page 15
Related tasks:
v “Allocating statement handles in CLI applications” on page 22
v “Initializing CLI applications” on page 18
Related reference:
v “SQLCloseCursor function (CLI) - Close cursor and discard pending results” in
Call Level Interface Guide and Reference, Volume 2
v “SQLFreeHandle function (CLI) - Free handle resources” in Call Level Interface
Guide and Reference, Volume 2
v “SQLFreeStmt function (CLI) - Free (or reset) a statement handle” in Call Level
Interface Guide and Reference, Volume 2
Related samples:
v “utilcli.c -- Utility functions used by DB2 CLI samples”
Connection handle:
Statement handle:
Descriptor Handle:
Related concepts:
v “Descriptors in CLI applications” on page 151
Related tasks:
v “Freeing statement resources in CLI applications” on page 37
v “Terminating a CLI application” on page 53
Related reference:
v “CLI function return codes” on page 50
v “Descriptor header and record field initialization values (CLI)” in Call Level
Interface Guide and Reference, Volume 2
v “SQLDisconnect function (CLI) - Disconnect from a data source” in Call Level
Interface Guide and Reference, Volume 2
v “SQLFreeHandle function (CLI) - Free handle resources” in Call Level Interface
Guide and Reference, Volume 2
To facilitate this, DB2 CLI provides symbolic names for the various data types, and
manages the transfer of data between the DBMS and the application. It also
performs data conversion (from a C character string to an SQL INTEGER type, for
example) if required. DB2 CLI needs to know both the source and target data type.
This requires the application to identify both data types using symbolic names.
Because the data source contains SQL data types and the CLI application works
with C data types, the data to be retrieved needs to be handled with the correct
The data types are now consistent, because the result data type SQL_C_SHORT
represents the C type SQLSMALLINT.
Data conversion:
DB2 CLI manages the transfer and any required conversion of data between the
application and the DBMS. Before the data transfer actually takes place, either the
source, the target or both data types are indicated when calling
SQLBindParameter(), SQLBindCol() or SQLGetData(). These functions use the
symbolic type names to identify the data types involved.
For example, to bind a parameter marker that corresponds to an SQL data type of
DECIMAL(5,3), to an application’s C buffer type of double, the appropriate
SQLBindParameter() call would look like:
SQLBindParameter (hstmt, 1, SQL_PARAM_INPUT, SQL_C_DOUBLE,
SQL_DECIMAL, 5, 3, double_ptr, 0, NULL);
The functions mentioned in the previous paragraph can be used to convert data
from the default to other data types, but not all data conversions are supported or
make sense.
The rules that specify limits on precision and scale, as well as truncation and
rounding rules for type conversions apply in DB2 CLI, with the following
exception: truncation of values to the right of the decimal point for numeric values
may return a truncation warning, whereas truncation to the left of the decimal
point returns an error. In cases of error, the application should call
SQLGetDiagRec() to obtain the SQLSTATE and additional information on the
failure. When moving and converting floating point data values between the
application and DB2 CLI, no correspondence is guaranteed to be exact as the
values may change in precision and scale.
Related concepts:
v “SQLSTATES for DB2 CLI” on page 51
Related samples:
v “dtinfo.c -- How get information about data types”
Related concepts:
v “Data types and data conversion in CLI applications” on page 39
v “LOB locators in CLI applications” on page 98
v “XML data type” in XML Guide
Related reference:
v “C data types for CLI applications” on page 43
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLGetData function (CLI) - Get data from a column” in Call Level Interface
Guide and Reference, Volume 2
Note: SQL file reference data types (used in embedded SQL) are not needed in DB2 CLI.
Table 5. C structures
C type Generic structure Windows structure
DATE_STRUCT
typedef struct DATE_STRUCT typedef struct tagDATE_STRUCT
{ {
SQLSMALLINT year; SWORD year;
SQLUSMALLINT month; UWORD month;
SQLUSMALLINT day; UWORD day;
} DATE_STRUCT; } DATE_STRUCT;
As well as the data types that map to SQL data types, there are also C symbolic
types used for other function arguments such as pointers and handles. Both the
generic and ODBC data types are shown below.
Note: There are two kinds of drivers that ship with the product: the DB2 CLI
driver, and the 64-bit ODBC driver. The 64-bit ODBC Driver handles the
differences with type definitions between various ODBC Managers.
Table 6. C Data types and base C data types
Defined C type Base C type Typical usage
SQLPOINTER void * Pointer to storage for data and parameters.
SQLHANDLE 1. 1. void * Handle used to reference all 4 types of handle
information.
2. 32-bit integer
1. 64-bit value for Windows 64-bit ODBC Driver
and UNIX 64-bit ODBC Driver
2. 32-bit value for all 32-bit platforms and 64-bit
DB2 CLI Drivers
SQLHENV 1. 1. void * Handle referencing environment information.
2. 32-bit integer 1. 64-bit value for Windows 64-bit ODBC Driver
and UNIX 64-bit ODBC Driver
2. 32-bit value for all 32-bit platforms and 64-bit
DB2 CLI Drivers
SQLHDBC 1. 1. void * Handle referencing database connection
information.
2. 32-bit integer
1. 64-bit value for Windows 64-bit ODBC Driver
and UNIX 64-bit ODBC Driver
2. 32-bit value for all 32-bit platforms and 64-bit
DB2 CLI Drivers
SQLHSTMT 1. 1. void * Handle referencing statement information.
2. 32-bit integer 1. 64-bit value for Windows 64-bit ODBC Driver
and UNIX 64-bit ODBC Driver
2. 32-bit value for all 32-bit platforms and 64-bit
DB2 CLI Drivers
SQLUSMALLINT unsigned 16-bit Function input argument for unsigned short
integer integer values.
Related concepts:
v “Data types and data conversion in CLI applications” on page 39
v “LOB locators in CLI applications” on page 98
Related reference:
v “SQL symbolic and default data types for CLI applications” on page 41
Input strings can have an associated length argument which indicates either the
exact length of the string (not including the null terminator), the special value
SQL_NTS to indicate a null-terminated string, or SQL_NULL_DATA to pass a
NULL value. If the length is set to SQL_NTS, DB2 CLI will determine the length of
the string by locating the null terminator.
Output strings have two associated length arguments: an input length argument to
specify the length of the allocated output buffer, and an output length argument to
return the actual length of the string returned by DB2 CLI. The returned length
value is the total length of the string available for return, regardless of whether it
fits in the buffer or not.
For SQL column data, if the output is a null value, SQL_NULL_DATA is returned
in the length argument and the output buffer is untouched. The descriptor field
SQL_DESC_INDICATOR_PTR is set to SQL_NULL_DATA if the column value is a
null value. For more information, including which other fields are set, see the
descriptor FieldIdentifier argument values.
Performance hint:
If the length argument (StrLen_or_IndPtr) and the output buffer (TargetValuePtr) are
contiguous in memory, DB2 CLI can return both values more efficiently, improving
application performance. For example, if the following structure is defined:
struct
{ SQLINTEGER pcbValue;
SQLCHAR rgbValue [BUFFER_SIZE];
} buffer;
Null-termination of strings:
By default, every character string that DB2 CLI returns is terminated with a null
terminator (hex 00), except for strings returned from graphic and DBCLOB data
types into SQL_C_CHAR application variables. Graphic and DBCLOB data types
that are retrieved into SQL_C_DBCHAR application variables are null terminated
with a double byte null terminator. Also, string data retrieved into
SQL_C_WCHAR are terminated with the Unicode null terminator 0x0000. This
requires that all buffers allocate enough space for the maximum number of bytes
expected, plus the null terminator.
String truncation:
If an output string does not fit into a buffer, DB2 CLI will truncate the string to the
size of the buffer, and write the null terminator. If truncation occurs, the function
will return SQL_SUCCESS_WITH_INFO and an SQLSTATE of 01004 indicating
truncation. The application can then compare the buffer length to the output length
to determine which string was truncated.
DB2 UDB Version 8.1.4 and later do not pad strings with blanks to fit the column
size, as was the behavior in releases of DB2 UDB from Version 8.1 through to
Version 8.1.4. With DB2 UDB Version 8.1.4 and later, a string may have a length
which differs from the length defined for the CHAR column if code page
conversion occurred. For releases of DB2 UDB before Version 8.1.4, strings would
be padded with blanks to fill the column size; these blanks would be returned as
part of the string data when the string was fetched from the CHAR column.
Related concepts:
v “SQLSTATES for DB2 CLI” on page 51
Related reference:
v “C data types for CLI applications” on page 43
v “CLI function return codes” on page 50
v “Descriptor header and record field initialization values (CLI)” in Call Level
Interface Guide and Reference, Volume 2
v “Patch1 CLI/ODBC configuration keyword” on page 350
v “SQL symbolic and default data types for CLI applications” on page 41
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
v “SQLGetDiagField function (CLI) - Get a field of diagnostic data” in Call Level
Interface Guide and Reference, Volume 2
v “SQLSetEnvAttr function (CLI) - Set environment attribute” in Call Level Interface
Guide and Reference, Volume 2
Each CLI function returns the function return code as a basic diagnostic. Both
SQLGetDiagRec() and SQLGetDiagField() provide more detailed diagnostic
information. If the diagnostic originates at the DBMS, the SQLGetSQLCA() function
provides access to the SQLCA. This arrangement lets applications handle the basic
flow control based on return codes, and use the SQLSTATES along with the
SQLCA to determine the specific causes of failure and to perform specific error
handling.
SQLGetSQLCA() returns the SQLCA for access to specific fields, but should only be
used when SQLGetDiagRec() or SQLGetDiagField() cannot provide the desired
information.
Related concepts:
v “SQLSTATES for DB2 CLI” on page 51
Related reference:
v “CLI function return codes” on page 50
v “SQLCA (SQL communications area)” in SQL Reference, Volume 1
v “SQLGetDescRec function (CLI) - Get multiple field settings of descriptor
record” in Call Level Interface Guide and Reference, Volume 2
v “SQLGetDiagField function (CLI) - Get a field of diagnostic data” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetSQLCA function (CLI) - Get SQLCA data structure” in Call Level
Interface Guide and Reference, Volume 2
Related concepts:
v “Diagnostics in CLI applications overview” on page 49
v “Handles in CLI” on page 15
Related reference:
v “CLI and ODBC function summary” in Call Level Interface Guide and Reference,
Volume 2
v “SQLGetDiagField function (CLI) - Get a field of diagnostic data” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetDiagRec function (CLI) - Get multiple fields settings of diagnostic
record” in Call Level Interface Guide and Reference, Volume 2
Note: Versions of DB2 CLI before Version 5 returned SQLSTATEs with a class of
’S1’ rather than ’HY’. To force the CLI driver to return ’S1’ SQLSTATEs, the
application should set the environment attribute
SQL_ATTR_ODBC_VERSION to the value SQL_OV_ODBC2.
DB2 CLI SQLSTATEs include both additional IBM defined SQLSTATEs that are
returned by the database server, and DB2 CLI defined SQLSTATEs for conditions
that are not defined in the ODBC version 3 and ISO SQL/CLI specifications. This
allows for the maximum amount of diagnostic information to be returned. When
running applications in an ODBC environment, it is also possible to receive ODBC
defined SQLSTATEs.
The following code segment from utilcli.c shows how diagnostic information,
such as SQLSTATEs, can be retrieved and displayed:
void HandleDiagnosticsPrint(SQLSMALLINT htype, /* handle type identifier */
SQLHANDLE hndl /* handle */ )
{
SQLCHAR message[SQL_MAX_MESSAGE_LENGTH + 1];
SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1];
SQLINTEGER sqlcode;
SQLSMALLINT length, i;
i = 1;
printf("-------------------------\n");
}
You can use the CLI/ODBC trace facility to gain a better understanding of how
your application calls DB2, including any errors that may occur.
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
Related reference:
v “CLI function return codes” on page 50
v “SQLGetDiagRec function (CLI) - Get multiple fields settings of diagnostic
record” in Call Level Interface Guide and Reference, Volume 2
Related samples:
v “utilcli.c -- Utility functions used by DB2 CLI samples”
Prerequisites:
Before terminating your application, you should have initialized your CLI
application and completed processing of all transactions.
Procedure:
Related concepts:
v “Transaction processing in CLI overview” on page 20
Related tasks:
v “Freeing statement resources in CLI applications” on page 37
v “Initializing CLI applications” on page 18
Related reference:
v “SQLDisconnect function (CLI) - Disconnect from a data source” in Call Level
Interface Guide and Reference, Volume 2
v “SQLFreeHandle function (CLI) - Free handle resources” in Call Level Interface
Guide and Reference, Volume 2
Related samples:
v “dbconn.c -- How to connect to and disconnect from a database”
v “dbmcon.c -- How to use multiple databases”
v “utilcli.c -- Utility functions used by DB2 CLI samples”
SQLSetConnectAttr(hDbc,
SQL_ATTR_CURRENT_PACKAGE_SET,
(SQLPOINTER) "KEEPDYNC",
SQL_NTS);
Refer to the DB2 for OS/390 and z/OS documentation for further information on
KEEPDYNAMIC behavior and configuration.
The following connection attributes might need to be set by DB2 CLI applications:
v SQL_ATTR_AUTOCOMMIT - Generally this attribute should be set to
SQL_AUTOCOMMIT_OFF, since each commit request can generate extra
network flow. Only leave SQL_AUTOCOMMIT_ON on if specifically needed.
The following statement attributes might need to be set by DB2 CLI applications:
v SQL_ATTR_MAX_ROWS - Setting this attribute limits the number of rows
returned to the application from query operations. This can be used to avoid
overwhelming an application with a very large result set generated
inadvertently, which is especially useful for applications on clients with limited
memory resources.
Setting SQL_ATTR_MAX_ROWS while connected to DB2 for z/OS and OS/390
Version 7 and later will add “OPTIMIZE FOR n ROWS” and “FETCH FIRST n
ROWS ONLY” clauses to the statement. For versions of DB2 for OS/390 prior to
Version 7 and any DBMS that does not support the “FETCH FIRST n ROWS
ONLY” clause, the full result set is still generated at the server using the
“OPTIMIZE FOR n ROWS” clause, however DB2 CLI will count the rows on the
client and only fetch up to SQL_ATTR_MAX_ROWS rows.
v SQL_ATTR_CURSOR_HOLD - This statement attribute determines if the cursor
for this statement will be declared by DB2 CLI using the WITH HOLD clause.
Resources associated with statement handles can be better utilized by the server
if the statements that do not require cursor-hold behavior have this attribute set
to SQL_CURSOR_HOLD_OFF. The efficiency gains obtained by the proper use
of this attribute are considerable on OS/390 and z/OS.
Each time a CLI application declares a statement handle, the DB2 CLI driver
allocates and then initializes an underlying data structure for that handle. To
increase performance, CLI applications can reuse statement handles with different
statements, thereby avoiding the costs associated with statement handle allocation
and initialization.
Note: Before reusing statement handles, memory buffers and other resources used
by the previous statement might need to be released by calling the
SQLFreeStmt() function. Also, statement attributes previously set on a
statement handle (for example, SQL_ATTR_PARAMSET_SIZE) need to be
explicitly reset, otherwise they might be inherited by all future statements
using the statement handle.
Catalog functions, such as SQLTables(), force the DB2 CLI driver to query the
DBMS catalog tables for information. The queries issued are complex and the
DBMS catalog tables can be very large. In general, try to limit the number of times
the catalog functions are called, and limit the number of rows returned.
The number of catalog function calls can be reduced by calling the function once,
and having the application store (cache) the data.
The column names of the result sets generated by catalog and information
functions might change as the ODBC and CLI standards evolve. The position of the
columns, however, will not change.
The ODBC Driver Manager maintains its own set of statement handles which it
maps to the CLI statement handles on each call. When a DB2 CLI function is called
directly, it must be passed to the CLI driver statement handle, as the CLI driver
does not have access to the ODBC mapping.
Call SQLGetInfo() with the SQL_DRIVER_HSTMT option to obtain the DB2 CLI
statement handle (HSTMT). The DB2 CLI functions can then be called directly
from the shared library or DLL, passing the HSTMT argument where required.
DB2 servers at version 5 or later for UNIX or Windows have a global dynamic
statement cache. This cache is used to store the most popular access plans for
prepared dynamic SQL statements.
Before each statement is prepared, the server automatically searches this cache to
see if an access plan has already been created for this exact SQL statement (by this
application or any other application or client). If so, the server does not need to
generate a new access plan, but will use the one in the cache instead. There is now
no need for the application to cache connections at the client unless connecting to a
server that does not have a global dynamic statement cache.
The methods that describe using arrays to bind parameters and retrieve data use
compound SQL to optimize network flow. Use these methods as much as possible.
Use LOB data types and the supporting functions for long strings whenever
possible. Unlike LONG VARCHAR, LONG VARBINARY, and LONG
VARGRAPHIC types, LOB data values can use LOB locators and functions such as
SQLGetPosition() and SQLGetSubString() to manipulate large data values at the
server.
All database object identifiers, such as table names, view names and column names
are stored in the catalog tables in uppercase unless the identifier is delimited. If an
identifier is created using a delimited name, the exact case of the name is stored in
the catalog tables.
The second statement below will fail with TABLE NOT FOUND since there is no table
named YOURTABLE:
SELECT * FROM "YourTable" (id INTEGER) // executes without error
SELECT * FROM YourTable (id INTEGER) // error, table not found
All DB2 CLI catalog function arguments treat the names of objects as case sensitive,
that is, as if each name was delimited.
If an application uses its own dialog boxes to query the connect information, the
user should be able to specify additional connect options in the connection string.
The string should also be stored and used as a default on subsequent connections.
DB2 CLI by default, scans each SQL statement searching for vendor escape clause
sequences.
If the application does not generate SQL statements that contain vendor escape
clause sequences, then the SQL_ATTR_NOSCAN statement attribute should be set
to SQL_NOSCAN_ON at the connection level so that DB2 CLI does not perform a
scan for vendor escape clauses.
Applications that need to deal with complex transaction management issues might
benefit from establishing multiple concurrent connections to the same database.
For example, all open cursors within a transaction get closed if a problem causes
the transaction to be rolled back. An application can use multiple connections to
the same database to separate statements with open cursors; since the cursors are
in separate transactions, a rollback on one statement does not affect the cursors of
the other statements.
However, using multiple connections might mean bringing some data across to the
client on one connection, and then sending it back to the server on the other
connection. For example:
v Suppose in connection #1 you are accessing large object columns and have
created LOB locators that map to portions of large object values.
v If in connection #2, you want to use (for example to insert) the portion of the
LOB values represented by the LOB locators, you would have to move the LOB
values in connection #1 first to the application, and then pass them to the tables
that you are working with in connection #2. This is because connection #2 does
not know anything about the LOB locators in connection #1.
v If you only had one connection, then you could just use the LOB locators
directly. However, you would lose the LOB locators as soon as you rolled back
your transaction.
This also simplifies error handling since prepare errors can be handled outside of
the compound statement.
Suppose also that the following SQL statement was then issued:
This statement would fail because the parameter marker cannot be of type CNUM
and thus the comparison fails due to incompatible types.
Casting the column to integer (its base SQL type), allows the comparison to work
since a parameter can be provided for type integer:
SELECT first_name, last_name, phone_num from customer
where cast( cust_num as integer ) = ?
Alternatively the parameter marker can be cast to INTEGER and the server can
then apply the INTEGER to CNUM conversion:
SELECT first_name, last_name, phone_num FROM customer
where cust_num = cast( ? as integer )
In DB2 CLI, deferred prepare is on by default. The PREPARE request is not sent to
the server until the corresponding execute request is issued. The two requests are
then combined into one command/reply flow (instead of two) to minimize
network flow and to improve performance. This is of greatest benefit when an
application generates queries with very small answer sets, because the overhead of
requests and replies flowing over the network represents a large percentage of the
processing time. In an environment where a DB2 Connect or DDCS gateway is
used, there is a greater opportunity for cost reduction because four request and
reply combinations are reduced to two.
Related concepts:
v “Catalog functions for querying system catalog information in CLI applications”
on page 167
v “Cursors in CLI applications” on page 65
v “Handles in CLI” on page 15
v “Large object usage in CLI applications” on page 96
v “Reduction of network flows with CLI array input chaining” on page 62
v “Vendor escape clauses in CLI applications” on page 171
Related tasks:
v “Executing compound SQL statements in CLI applications” on page 123
v “Retrieving array data in CLI applications using column-wise binding” on page
89
v “Retrieving array data in CLI applications using row-wise binding” on page 90
Related reference:
v “CLI and ODBC function summary” in Call Level Interface Guide and Reference,
Volume 2
SQLPrepare (statement2)
/* enable chaining */
SQLSetStmtAttr (statement2, SQL_ATTR_CHAINGING_BEGIN)
SQLExecute (statement2)
SQLExecute (statement2)
SQLExecute (statement2)
/* end chaining */
SQLSetStmtAttr (statement2, SQL_ATTR_CHAINING_END)
/* the three execution requests for statement2 are sent to the server
in a single network flow, instead of three separate flows */
Related concepts:
v “Programming hints and tips for CLI applications” on page 55
Related reference:
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLGetDiagField function (CLI) - Get a field of diagnostic data” in Call Level
Interface Guide and Reference, Volume 2
Cursors
Types of cursors:
Cursor attributes:
a Forward-only is the default behavior for a scrollable cursor without the FOR UPDATE
clause. Specifying FOR UPDATE on a forward-only cursor creates an updatable, lock
concurrency, non-scrollable cursor.
b Values concurrency is the default behavior, however, DB2 on Linux, UNIX and
Windows will also support lock concurrency, which will result with pessimistic locking.
Related concepts:
v “Result set terminology in CLI applications” on page 70
v “Cursor considerations for CLI applications” on page 68
Chapter 5. Cursors 67
Related reference:
v “DELETE statement” in SQL Reference, Volume 2
v “SQLExecDirect function (CLI) - Execute a statement directly” in Call Level
Interface Guide and Reference, Volume 2
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLExtendedFetch function (CLI) - Extended fetch (fetch array of rows)” in Call
Level Interface Guide and Reference, Volume 2
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
v “UPDATE statement” in SQL Reference, Volume 2
v “CursorHold CLI/ODBC configuration keyword” on page 307
v “CursorTypes CLI/ODBC configuration keyword” on page 308
The first decision to make is between a forward-only cursor and a scrollable cursor.
A forward-only cursor incurs less overhead than a scrollable cursor, and scrollable
cursors have the potential for decreased concurrency. If your application does not
need the additional features of a scrollable cursor, then you should use a
non-scrollable cursor.
If a scrollable cursor is required then you have to decide between a static cursor, a
keyset-driven cursor, or a dynamic cursor. A static cursor involves the least
overhead. If the application does not need the additional features of a
keyset-driven or dynamic cursor then a static cursor should be used.
Note: Currently, dynamic cursors are only supported when accessing servers that
are DB2 for z/OS Version 8.1 and later.
If the application needs to detect changes to the underlying data or needs to add,
update, or delete data from the cursor, then the application must use either a
keyset-driven or dynamic cursor. To perform updates and deletions on rows in a
dynamic scrollable cursor’s result set, the UPDATE or DELETE statement must
include all the columns of at least one unique key in the base table. This can be the
primary key or any other unique key. Because dynamic cursors incur more
overhead and might have less concurrency than keyset-driven cursors, only choose
dynamic cursors if the application needs to detect both changes made and rows
inserted by other cursors.
To determine the attributes of the types of cursors supported by the driver and
DBMS, the application should call SQLGetInfo() with an InfoType of:
v SQL_DYNAMIC_CURSOR_ATTRIBUTES1
By default, the DB2 CLI driver declares all cursors as WITH HOLD. This means
that any open cursor will persist across COMMITs, thereby requiring the
application to explicitly close each cursor. Be aware, however, that if a cursor is
closed in autocommit mode, then any other open cursors that are not defined with
the WITH HOLD option will be closed and all remaining open cursors will become
unpositioned. (This means that no positioned updates or deletes can be performed
without issuing another fetch.) There are two ways to change whether a cursor is
declared WITH HOLD:
v Set the statement attribute SQL_ATTR_CURSOR_HOLD to
SQL_CURSOR_HOLD_ON (default) or SQL_CURSOR_HOLD_OFF. This setting
only affects cursors opened on the statement handle after this value has been set.
It will not affect cursors already open.
v Set the CLI/ODBC configuration keyword CursorHold to change the default
DB2 CLI driver behavior. Setting CursorHold=1 preserves the default behavior
of cursors declared as WITH HOLD, and CursorHold=0 results in cursors being
closed when each transaction is committed. You can override this keyword by
setting the SQL_ATTR_CURSOR_HOLD statement attribute described above.
Note: A ROLLBACK will close all cursors, including those declared WITH HOLD.
Chapter 5. Cursors 69
Table 9. Configuration keyword values restoring application behavior before scrollable cursor
support (continued)
Configuration keyword Description
setting
DisableKeysetCursor=1 Disables keyset-driven scrollable cursors. This can be used
to force the CLI driver to give the application a static
cursor when a keyset-driven or dynamic cursor is
requested.
Related concepts:
v “Commit modes in CLI applications” on page 30
v “Cursors in CLI applications” on page 65
v “Result set terminology in CLI applications” on page 70
Related reference:
v “COMMIT statement” in SQL Reference, Volume 2
v “ROLLBACK statement” in SQL Reference, Volume 2
v “SQLGetInfo function (CLI) - Get general information” in Call Level Interface
Guide and Reference, Volume 2
v “CursorHold CLI/ODBC configuration keyword” on page 307
v “CursorTypes CLI/ODBC configuration keyword” on page 308
v “DisableKeysetCursor CLI/ODBC configuration keyword” on page 321
v “Patch2 CLI/ODBC configuration keyword” on page 352
Result sets
2 key 2
4 . key 4
.
5 bookmark 1 . key 5
8 key 8
9 key 9
10 key 10
11 key 11
12 key 12
13 key 13
Rows added after
14
. key 14
the keyset-driven
cursor was opened
.
become part of the 15 . key 15
result set.
16 key 16
Related concepts:
v “Bookmarks in CLI applications” on page 78
v “Cursor considerations for CLI applications” on page 68
v “Cursors in CLI applications” on page 65
Related reference:
v “SELECT statement” in SQL Reference, Volume 2
v “SQLBulkOperations function (CLI) - Add, update, delete or fetch a set of rows”
in Call Level Interface Guide and Reference, Volume 2
v “SQLExtendedFetch function (CLI) - Extended fetch (fetch array of rows)” in Call
Level Interface Guide and Reference, Volume 2
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
When working with rowsets, you should verify what portion of the result set
returned contains meaningful data. The application cannot assume that the entire
Chapter 5. Cursors 71
rowset will contain data. It must check the row status array after each rowset is
created to determine the number of rows returned, because there are instances
where the rowset will not contain a complete set of rows. For instance, consider
the case where the rowset size is set to 10, and SQLFetchScroll() is called using
SQL_FETCH_ABSOLUTE and FetchOffset is set to -3. This will attempt to return 10
rows starting 3 rows from the end of the result set. Only the first three rows of the
rowset will contain meaningful data, however, and the application must ignore the
rest of the rows.
row 1
}
2
3
Result Set
}
n-2
Valid rows n-1
n
Invalid rows
} Rowset
(FetchOffset = -3)
3. SQL_FETCH_NEXT
4. SQL_FETCH_RELATIVE
(FetchOffset = -1)
5. SQL_FETCH_ABSOLUTE
(FetchOffset = 11)
n-2
1. n-1n-1 SQL_FETCH_LAST
n
Related concepts:
v “Result set terminology in CLI applications” on page 70
Related reference:
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
Prerequisites:
Before specifying the rowset, ensure that you have initialized your CLI application.
Procedure:
Chapter 5. Cursors 73
#define ROWSET_SIZE 35
/* ... */
rc = SQLSetStmtAttr(hstmt,
SQL_ATTR_ROW_ARRAY_SIZE,
(SQLPOINTER) ROWSET_SIZE,
0);
2. Set up a variable that will store the number of rows returned. Declare a
variable of type SQLUINTEGER and set the
SQL_ATTR_ROWS_FETCHED_PTR statement attribute to point to this variable.
In the following example, rowsFetchedNb will hold the number of rows returned
in the rowset after each call to SQLFetchScroll():
/* ... */
SQLUINTEGER rowsFetchedNb;
/* ... */
rc = SQLSetStmtAttr(hstmt,
SQL_ATTR_ROWS_FETCHED_PTR,
&rowsFetchedNb,
0);
3. Set up the row status array. Declare an array of type SQLUSMALLINT with the
same number of rows as the size of the rowset (as determined in Step 1). Then
specify the address of this array with the statement attribute
SQL_ATTR_ROW_STATUS_PTR. For example:
/* ... */
SQLUSMALLINT row_status[ROWSET_SIZE];
/* ... */
/* Set a pointer to the array to use for the row status */
rc = SQLSetStmtAttr(
hstmt,
SQL_ATTR_ROW_STATUS_PTR,
(SQLPOINTER) row_status,
0);
The row status array provides additional information about each row in the
rowset. After each call to SQLFetch() or SQLFetchScroll(), the array is updated.
If the call to SQLFetch() or SQLFetchScroll() does not return SQL_SUCCESS or
SQL_SUCCESS_WITH_INFO, then the contents of the row status array are
undefined. Otherwise, any of the row status array values will be returned (refer
to the row status array section of the SQLFetchScroll() documentation for a
complete list of values).
4. Position the rowset within the result set, indicating the position you want the
rowset to begin. Specify this position by calling SQLFetch(), or
SQLFetchScroll() with FetchOrientation and FetchOffset values. For example, the
following call generates a rowset starting on the 11th row in the result set:
SQLFetchScroll(hstmt, /* Statement handle */
SQL_FETCH_ABSOLUTE, /* FetchOrientation value */
11); /* Offset value */
Scroll bar operations of a screen-based application can be mapped directly to
the positioning of a rowset. By setting the rowset size to the number of lines
displayed on the screen, the application can map the movement of the scroll
bar to calls to SQLFetchScroll().
Note: If the application can buffer data in the display and regenerate the result
set to see updates, then use a forward-only cursor instead. This yields
better performance for small result sets.
5. Check the rows fetched pointer after each rowset is created to determine the
number of rows returned. Check the row status array for the status of each
row, because there are instances where the rowset will not contain a complete
set of rows. The application cannot assume that the entire rowset will contain
data.
For instance, consider the case where the rowset size is set to 10, and
SQLFetchScroll() is called using SQL_FETCH_ABSOLUTE and FetchOffset is
set to -3. This will attempt to return 10 rows starting 3 rows from the end of
the result set. Only the first three rows of the rowset will contain meaningful
data, however, and the application must ignore the rest of the rows.
Related concepts:
v “Cursor considerations for CLI applications” on page 68
v “Result set terminology in CLI applications” on page 70
Related tasks:
v “Initializing CLI applications” on page 18
v “Retrieving data with bookmarks in a CLI application” on page 79
v “Retrieving data with scrollable cursors in a CLI application” on page 76
Related reference:
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
v “C data types for CLI applications” on page 43
v “CLI function return codes” on page 50
Chapter 5. Cursors 75
Related samples:
v “tbread.c -- How to read data from tables”
Prerequisites:
Before you retrieve data using scrollable cursors, ensure that you have initialized
your CLI application.
Procedure:
SQLUINTEGER rowsFetchedNb;
/* ... */
rc = SQLSetStmtAttr(hstmt,
SQL_ATTR_ROWS_FETCHED_PTR,
&rowsFetchedNb,
0);
4. Set up the row status array. Declare an array of type SQLUSMALLINT with
the same number of rows as the size of the rowset (as determined in Step 1).
Then specify the address of this array with the statement attribute
SQL_ATTR_ROW_STATUS_PTR. For example:
The row status array provides additional information about each row in the
rowset. After each call to SQLFetchScroll(), the array is updated. If the call to
SQLFetchScroll() does not return SQL_SUCCESS or
SQL_SUCCESS_WITH_INFO, then the contents of the row status array are
undefined. Otherwise, any of the row status array values will be returned
(refer to the row status array section of the SQLFetchScroll() documentation
for a complete list of values).
5. Optional: If you want to use bookmarks with the scrollable cursor, set the
SQL_ATTR_USE_BOOKMARKS statement attribute to SQL_UB_VARIABLE.
For example:
sqlrc = SQLSetStmtAttr (hstmt,
SQL_ATTR_USE_BOOKMARKS,
(SQLPOINTER) SQL_UB_VARIABLE,
0);
6. Issue an SQL SELECT statement.
7. Execute the SQL SELECT statement.
8. Bind the result set using either column-wise or row-wise binding.
9. Fetch a rowset of rows from the result set.
a. Call SQLFetchScroll() to fetch a rowset of data from the result set.
Position the rowset within the result set indicating the position you want
the rowset to begin. Specify this position by calling SQLFetchScroll() with
FetchOrientation and FetchOffset values. For example, the following call
generates a rowset starting on the 11th row in the result set:
SQLFetchScroll(hstmt, /* Statement handle */
SQL_FETCH_ABSOLUTE, /* FetchOrientation value */
11); /* Offset value */
b. Check the row status array after each rowset is created to determine the
number of rows returned, because there are instances where the rowset
will not contain a complete set of rows. The application cannot assume
that the entire rowset will contain data.
For instance, consider the case where the rowset size is set to 10, and
SQLFetchScroll() is called using SQL_FETCH_ABSOLUTE and FetchOffset
is set to -3. This will attempt to return 10 rows starting 3 rows from the
end of the result set. Only the first three rows of the rowset will contain
meaningful data, however, and the application must ignore the rest of the
rows.
c. Display or manipulate the data in the rows returned.
10. Close the cursor by calling SQLCloseCursor() or free the statement handle by
calling SQLFreeHandle() with a HandleType of SQL_HANDLE_STMT.
Freeing the statement handles is not required every time retrieval has finished.
The statement handles can be freed at a later time, when the application is
freeing other handles.
Related concepts:
v “Bookmarks in CLI applications” on page 78
Chapter 5. Cursors 77
v “Cursor considerations for CLI applications” on page 68
v “Cursors in CLI applications” on page 65
Related tasks:
v “Initializing CLI applications” on page 18
v “Issuing SQL statements in CLI applications” on page 23
v “Preparing and executing SQL statements in CLI applications” on page 24
Related reference:
v “SQLCloseCursor function (CLI) - Close cursor and discard pending results” in
Call Level Interface Guide and Reference, Volume 2
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
v “C data types for CLI applications” on page 43
v “CLI function return codes” on page 50
Related samples:
v “tbread.c -- How to read data from tables”
Bookmarks
Once you have positioned the cursor to a row in a rowset using SQLSetPos(), you
can obtain the bookmark value starting from column 0 using SQLGetData(). In
most cases you will not want to bind column 0 and retrieve the bookmark value
for every row, but use SQLGetData() to retrieve the bookmark value for the specific
row you require.
A bookmark is only valid within the result set in which it was created. The
bookmark value will be different if you select the same row from the same result
set in two different cursors.
Related concepts:
v “Cursor considerations for CLI applications” on page 68
v “Result set terminology in CLI applications” on page 70
Prerequisites:
Before you retrieve data with bookmarks, ensure that you have initialized your
CLI application. The steps explained here should be performed in addition to those
described in ″Retrieving Data with Scrollable Cursors in a CLI Application″.
Procedure:
In most cases, you will not want to bind column 0 and retrieve the bookmark
value for every row, but use SQLGetData() to retrieve the bookmark value for
the specific row you require.
3. Store the bookmark location for the next call to SQLFetchScroll(). Set the
SQL_ATTR_FETCH_BOOKMARK statement attribute to the variable that
contains the bookmark value. For example, continuing from the example above,
bookmark.val stores the bookmark value, so call SQLSetStmtAttr() as follows:
sqlrc = SQLSetStmtAttr(hstmt,
SQL_ATTR_FETCH_BOOKMARK_PTR,
(SQLPOINTER) bookmark.val,
0);
4. Retrieve a rowset based on the bookmark. Once the bookmark value is stored,
the application can continue to use SQLFetchScroll() to retrieve data from the
result set. The application can then move throughout the result set, but still
retrieve a rowset based on the location of the bookmarked row at any point
before the cursor is closed.
Chapter 5. Cursors 79
The following call to SQLFetchScroll() retrieves a rowset starting from the
bookmarked row:
sqlrc = SQLFetchScroll(hstmt, SQL_FETCH_BOOKMARK, 0);
The value 0 specifies the offset. You would specify -3 to begin the rowset 3
rows before the bookmarked row, or specify 4 to begin 4 rows after. For
example, the following call from retrieves a rowset 4 rows after the
bookmarked row:
sqlrc = SQLFetchScroll(hstmt, SQL_FETCH_BOOKMARK, 4);
Note that the variable used to store the bookmark value is not specified in the
SQLFetchScroll() call. It was set in the previous step using the statement
attribute SQL_ATTR_FETCH_BOOKMARK_PTR.
Related concepts:
v “Bookmarks in CLI applications” on page 78
v “Cursor considerations for CLI applications” on page 68
v “Result set terminology in CLI applications” on page 70
Related tasks:
v “Initializing CLI applications” on page 18
v “Retrieving data with scrollable cursors in a CLI application” on page 76
Related reference:
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
v “SQLGetData function (CLI) - Get data from a column” in Call Level Interface
Guide and Reference, Volume 2
v “SQLSetPos function (CLI) - Set the cursor position in a rowset” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Related samples:
v “tbread.c -- How to read data from tables”
Array input
Prerequisites:
Before binding parameter markers with column-wise binding, ensure that you have
initialized your CLI application.
Restrictions:
For character and binary input data, the application uses the maximum input
buffer size argument (BufferLength) of the SQLBindParameter() call to indicate to
DB2 CLI the location of values in the input array. For other input data types, the
length of each element in the array is assumed to be the size of the C data type.
Procedure:
Related concepts:
Related tasks:
v “Initializing CLI applications” on page 18
Related reference:
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Prerequisites:
Before binding parameter markers with row-wise binding, ensure that you have
initialized your CLI application.
Procedure:
/* Parameter B */
/* Parameter C */
rc = SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR,
3, 0, R[0].C, 3, &R.Lc);
Related concepts:
v “Parameter diagnostic information in CLI applications” on page 83
v “Parameter marker binding in CLI applications” on page 26
Related tasks:
v “Initializing CLI applications” on page 18
Related reference:
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
DB2 CLI updates the elements in the parameter status array with the following
values:
v SQL_PARAM_SUCCESS: The SQL statement was successfully executed for this
set of parameters.
v SQL_PARAM_SUCCESS_WITH_INFO: The SQL statement was successfully
executed for this set of parameters, however, warning information is available in
the diagnostics data structure.
v SQL_PARAM_ERROR: An error occurred in processing this set of parameters.
Additional error information is available in the diagnostics data structure.
v SQL_PARAM_UNUSED: This parameter set was unused, possibly because a
previous parameter set caused an error that aborted further processing.
v SQL_PARAM_DIAG_UNAVAILABLE: Diagnostic information is not available,
possibly because an error was detected before the parameter set was even used
(for example, an SQL statement syntax error).
Once the application has determined what parameters had errors, it can use the
statement attribute SQL_ATTR_PARAM_OPERATION_PTR, or the corresponding
APD descriptor header field SQL_DESC_ARRAY_STATUS_PTR, (both of which
point to an array of values) to control which sets of parameters are ignored in a
second call to SQLExecute() or SQLExecDirect().
Related tasks:
v “Binding parameter markers in CLI applications” on page 29
Related reference:
v “Descriptor FieldIdentifier argument values (CLI)” in Call Level Interface Guide
and Reference, Volume 2
v “SQLExecDirect function (CLI) - Execute a statement directly” in Call Level
Interface Guide and Reference, Volume 2
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLSetDescField function (CLI) - Set a single field of a descriptor record” in
Call Level Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Prerequisites:
Before changing your parameter bindings, ensure that your application has been
initialized.
Procedure:
Related concepts:
v “Cursors in CLI applications” on page 65
Related tasks:
v “Binding parameter markers in CLI applications with column-wise array input”
on page 81
v “Binding parameter markers in CLI applications with row-wise array input” on
page 82
v “Initializing CLI applications” on page 18
v “Preparing and executing SQL statements in CLI applications” on page 24
Related reference:
v “C data types for CLI applications” on page 43
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLExecDirect function (CLI) - Execute a statement directly” in Call Level
Interface Guide and Reference, Volume 2
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Array output
The application can query the attributes (such as data type and length) of the
column by first calling SQLDescribeCol() or SQLColAttribute(). This information
can then be used to allocate a storage location of the correct data type and length,
to indicate data conversion to another data type, or in the case of LOB data types,
optionally return a locator.
An application can choose not to bind every column, or even not to bind any
columns. Data in any of the columns can also be retrieved using SQLGetData()
after the bound columns have been fetched for the current row. It is usually more
efficient to bind application variables or file references to result sets than to use
SQLGetData(). When the data is in a LOB column, LOB functions are preferable to
SQLGetData() . Use SQLGetData() when the data value is large variable-length data
that:
v must be received in pieces, or
v may not need to be retrieved.
Instead of multiple calls to SQLBindCol(), DB2 CLI also supports column binding
offsets. Rather than re-binding each time, an offset can be used to specify new
buffer and length/indicator addresses which will be used in a subsequent call to
SQLFetch() or SQLFetchScroll(). This can only be used with row wise binding, but
will work whether the application retrieves a single row or multiple rows at a
time.
When binding any variable length column, DB2 CLI will be able to write
StrLen_or_IndPtr and TargetValuePtr in one operation if they are allocated
contiguously. For example:
struct { SQLINTEGER StrLen_or_IndPtr;
SQLCHAR TargetValuePtr[MAX_BUFFER];
} column;
The most recent bind column function call determines the type of binding that is in
effect.
Related concepts:
v “LOB locators in CLI applications” on page 98
Related tasks:
Related reference:
v “FREE LOCATOR statement” in SQL Reference, Volume 2
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLBindFileToCol function (CLI) - Bind LOB file reference to LOB column” in
Call Level Interface Guide and Reference, Volume 2
v “SQLDescribeCol function (CLI) - Return a set of attributes for a column” in Call
Level Interface Guide and Reference, Volume 2
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
v “SQLGetData function (CLI) - Get data from a column” in Call Level Interface
Guide and Reference, Volume 2
Alternatively, applications can eliminate the overhead of extra data copies or extra
SQLBindCol() calls by retrieving multiple rows of data (called a rowset) at one time
into an array.
Note: A third method of reducing overhead, which can be used on its own or with
arrays, is to specify a binding offset. Rather than re-binding each time, an
offset can be used to specify new buffer and length/indicator addresses
which will be used in a subsequent call to SQLFetch() or SQLFetchScroll().
This can only be used with row offset binding.
When retrieving a result set into an array, SQLBindCol() is also used to assign
storage for application array variables. By default, the binding of rows is in
column-wise fashion: this is similar to using SQLBindParameter() to bind arrays of
input parameter values. Figure 6 on page 88 is a logical view of column-wise
binding.
}
1 Fetch Scroll, Column-Wise Binding
2 10 XYZ Abcde
3
...
...
...
...
n Column A Column B Column C
Data Length Data Length Data Length
1 1 1
Column: Data Type:
A INTEGER 2 10 4 2 XYZ 3 2 Abcde 5
B CHAR(3)
C CHAR(10) 3 3 3
...
...
...
...
...
...
...
...
...
n n n
The application can also do row-wise binding which associates an entire row of the
result set with a structure. In this case the rowset is retrieved into an array of
structures, each of which holds the data in one row and the associated length
fields. Figure 7 gives a pictorial view of row-wise binding.
Result Set
A B C Fetch Scroll, Row-Wise Binding
}
1
2 10 XYZ Abcde
3
...
...
...
...
...
...
...
C CHAR(10)
n
Related tasks:
v “Changing column bindings in a CLI application with column binding offsets”
on page 91
v “Retrieving array data in CLI applications using column-wise binding” on page
89
v “Retrieving array data in CLI applications using row-wise binding” on page 90
Related reference:
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
Prerequisites:
Before using column-wise binding to retrieve data into arrays, ensure you have
initialized your CLI application.
Procedure:
Related concepts:
v “Result set retrieval into arrays in CLI applications” on page 87
Related tasks:
v “Initializing CLI applications” on page 18
v “Preparing and executing SQL statements in CLI applications” on page 24
v “Retrieving array data in CLI applications using row-wise binding” on page 90
Related reference:
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
Related samples:
v “tbread.c -- How to read data from tables”
Prerequisites:
Before using row-wise binding to retrieve data into arrays, ensure you have
initialized your CLI application.
Procedure:
Related concepts:
v “Result set retrieval into arrays in CLI applications” on page 87
Related tasks:
v “Initializing CLI applications” on page 18
v “Preparing and executing SQL statements in CLI applications” on page 24
v “Retrieving array data in CLI applications using column-wise binding” on page
89
Related reference:
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Related samples:
v “tbread.c -- How to read data from tables”
Prerequisites:
Before using column binding offsets to change result set bindings, ensure you have
initialized your CLI application.
Restrictions:
This method can only be used with row-wise binding, but will work whether the
application retrieves a single row or multiple rows at a time.
Procedure:
Related concepts:
v “Column binding in CLI applications” on page 85
Related tasks:
v “Initializing CLI applications” on page 18
v “Retrieving array data in CLI applications using row-wise binding” on page 90
Related reference:
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Prerequisites:
Before specifying parameter values at execute time, ensure you have initialized
your CLI application.
Restrictions:
While the data-at-execution flow is in progress, the only DB2 CLI functions the
application can call are:
v SQLParamData() and SQLPutData() as given in the sequence below.
v The SQLCancel() function which is used to cancel the flow and force an exit
from the loops described below without executing the SQL statement.
v The SQLGetDiagRec() function.
Procedure:
For example:
/* dtlob.c */
/* ... */
else
{ sqlrc = SQLParamData( hstmt, (SQLPOINTER *) &valuePtr);
/* ... */
Related tasks:
v “Initializing CLI applications” on page 18
Related reference:
Related samples:
v “dtlob.c -- How to read and write LOB data”
For example:
/* dtlob.c */
/* ... */
sqlrc = SQLGetData(hstmt, 1, SQL_C_BINARY, (SQLPOINTER) buffer,
BUFSIZ, &bufInd);
/* ... */
while( sqlrc == SQL_SUCCESS_WITH_INFO || sqlrc == SQL_SUCCESS )
{ if ( bufInd > BUFSIZ) /* full buffer */
{ fwrite( buffer, sizeof(char), BUFSIZ, pFile);
}
else /* partial buffer on last GetData */
{ fwrite( buffer, sizeof(char), bufInd, pFile);
}
Related concepts:
v “Large object usage in CLI applications” on page 96
Related samples:
v “dtlob.c -- How to read and write LOB data”
Since LOB values can be very large, transfer of data using the piecewise sequential
method provided by SQLGetData() and SQLPutData() can be quite time consuming.
Applications dealing with such data will often do so in random access segments
using LOB locators or via direct file input and output.
To determine if any of the LOB functions are supported for the current server, call
SQLGetFunctions() with the appropriate function name argument value, or
SQLGetTypeInfo() with the particular LOB data type.
SQLPrepare
SQLBindCol SQLBindFileToCol
locator
SQLExecute SQLExecute
CLOB
locator SQLFetch
SQLFetch
CLOB
SQLGetLength
locator
SQLGetPosition
"string", locator
SQLGetSubString
locator, buffer buffer
SQLExecDirect
"FREE LOCATOR"
SQLFreeHandle
(Statement)
Related concepts:
v “Data retrieval in pieces in CLI applications” on page 95
v “LOB locators in CLI applications” on page 98
Related reference:
v “SQLGetData function (CLI) - Get data from a column” in Call Level Interface
Guide and Reference, Volume 2
v “SQLGetFunctions function (CLI) - Get functions” in Call Level Interface Guide and
Reference, Volume 2
v “SQLGetTypeInfo function (CLI) - Get data type information” in Call Level
Interface Guide and Reference, Volume 2
v “SQLPutData function (CLI) - Passing data value for a parameter” in Call Level
Interface Guide and Reference, Volume 2
A LOB locator is a token value, defined as type SQLINTEGER, that allows for
efficient random access of a large object. When a LOB locator is used, the server
performs the query and instead of placing the value of the LOB column in the
result set, it updates the LOB locator with an integer that corresponds to the value
of the LOB. When the application later requests the result, the application then
passes the locator to the server and the server returns the LOB result.
A LOB locator is not stored in the database. It refers to a LOB value during a
transaction, and does not persist beyond the transaction in which it was created. It
is a simple token value created to reference a single large object value, and not a
column in a row. There is no operation that could be performed on a locator that
would have an effect on the original LOB value stored in the row.
Each of the three LOB locator types has its own C data type
(SQL_C_BLOB_LOCATOR, SQL_C_CLOB_LOCATOR,
SQL_C_DBCLOB_LOCATOR). These types are used to enable transfer of LOB
locator values to and from the database server.
LOB locators also provide an efficient method of moving data from one column of
a table in a database to another column (of the same or different table) without
having to pull the data first into application memory and then sending it back to
the server. For example, the following INSERT statement inserts a LOB value that
is a concatenation of 2 LOB values as represented by their locators:
INSERT INTO lobtable values (CAST ? AS CLOB(4k) || CAST ? AS CLOB(5k))
LOB locators can in general be treated as any other data type, but there are some
important differences:
v Locators are generated at the server when a row is fetched and a LOB locator C
data type is specified on SQLBindCol(), or when SQLGetSubString() is called to
define a locator on a portion of another LOB. Only the locator is transferred to
the application.
v The value of the locator is only valid within the current transaction. You cannot
store a locator value and use it beyond the current transaction, even if the cursor
used to fetch the LOB locator has the WITH HOLD attribute.
v A locator can also be freed before the end of the transaction with the FREE
LOCATOR statement.
For a given LOB column in the result set, the binding can be to a:
v storage buffer for holding the entire LOB data value,
v LOB locator, or
v LOB file reference (using SQLBindFileToCol()).
Related concepts:
v “Large object usage in CLI applications” on page 96
v “Parameter marker binding in CLI applications” on page 26
Related tasks:
v “Fetching LOB data with LOB locators in CLI applications” on page 99
Related reference:
v “C data types for CLI applications” on page 43
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLGetData function (CLI) - Get data from a column” in Call Level Interface
Guide and Reference, Volume 2
v “SQLGetLength function (CLI) - Retrieve length of a string value” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetPosition function (CLI) - Return starting position of string” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetSubString function (CLI) - Retrieve portion of a string value” in Call
Level Interface Guide and Reference, Volume 2
Prerequisites:
Before fetching LOB data with LOB locators, ensure you have initialized your CLI
application.
Procedure:
/* ... */
sqlrc = SQLBindCol( hstmtClobFetch, 1, SQL_C_CLOB_LOCATOR,
&clobLoc, 0, &pcbValue);
2. Fetch the locator using SQLFetch():
sqlrc = SQLFetch( hstmtClobFetch );
3. Call SQLGetLength() to get the length of a string that is represented by a LOB
locator. For example:
sqlrc = SQLGetLength( hstmtLocUse, SQL_C_CLOB_LOCATOR,
clobLoc, &clobLen, &ind ) ;
4. Call SQLGetPosition() to get the position of a search string within a source
string where the source string is represented by a LOB locator. The search
string can also be represented by a LOB locator. For example:
sqlrc = SQLGetPosition( hstmtLocUse,
SQL_C_CLOB_LOCATOR,
clobLoc,
0,
( SQLCHAR * ) "Interests",
strlen( "Interests"),
1,
&clobPiecePos,
&ind ) ;
5. Call SQLGetSubString() to retrieve the substring. For example:
sqlrc = SQLGetSubString( hstmtLocUse,
SQL_C_CLOB_LOCATOR,
clobLoc,
clobPiecePos,
clobLen - clobPiecePos,
SQL_C_CHAR,
buffer,
clobLen - clobPiecePos + 1,
&clobPieceLen,
&ind ) ;
6. Free the locator. All LOB locators are implicitly freed when a transaction ends.
The locator can be explicitly freed before the end of a transaction by executing
the FREE LOCATOR statement.
Although this statement cannot be prepared dynamically, DB2 CLI will accept it
as a valid statement on SQLPrepare() and SQLExecDirect(). The application
uses SQLBindParameter() with the SQL data type argument set to the
appropriate SQL and C symbolic data types. For example,
sqlrc = SQLSetParam( hstmtLocFree,
1,
SQL_C_CLOB_LOCATOR,
SQL_CLOB_LOCATOR,
0,
0,
&clobLoc,
NULL ) ;
/* ... */
sqlrc = SQLExecDirect( hstmtLocFree, stmtLocFree, SQL_NTS ) ;
Related concepts:
v “LOB locators in CLI applications” on page 98
100 CLI Guide and Reference, Volume 1
Related tasks:
v “Initializing CLI applications” on page 18
Related reference:
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “C data types for CLI applications” on page 43
v “FREE LOCATOR statement” in SQL Reference, Volume 2
v “SQL symbolic and default data types for CLI applications” on page 41
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
v “SQLGetData function (CLI) - Get data from a column” in Call Level Interface
Guide and Reference, Volume 2
v “SQLGetLength function (CLI) - Retrieve length of a string value” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetPosition function (CLI) - Return starting position of string” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetSubString function (CLI) - Retrieve portion of a string value” in Call
Level Interface Guide and Reference, Volume 2
Related samples:
v “dtlob.c -- How to read and write LOB data”
Direct file input and output for LOB handling in CLI applications
As an alternative to using LOB locators, if an application requires the entire LOB
column value, it can request direct file input and output for LOBs. Database
queries, updates, and inserts may involve transfer of single LOB column values
into and from files. The two DB2 CLI LOB file access functions are:
SQLBindFileToCol()
Binds (associates) a LOB column in a result set with a file name.
Example:
SQLUINTEGER fileOption = SQL_FILE_OVERWRITE;
SQLINTEGER fileInd = 0;
SQLSMALLINT fileNameLength = 14;
/* ... */
SQLCHAR fileName[14] = "";
/* ... */
rc = SQLBindFileToCol(hstmt, 1, fileName, &fileNameLength,
&fileOption, 14, NULL, &fileInd);
SQLBindFileToParam()
Binds (associates) a LOB parameter marker with a file name.
Example:
SQLUINTEGER fileOption = SQL_FILE_OVERWRITE;
SQLINTEGER fileInd = 0;
SQLSMALLINT fileNameLength = 14;
/* ... */
SQLCHAR fileName[14] = "";
/* ... */
The file name is either the complete path name of the file (which is recommended),
or a relative file name. If a relative file name is provided, it is appended to the
current path (of the operating environment) of the client process. On execute or
fetch, data transfer to and from the file would take place, in a similar way to that
of bound application variables. A file options argument associated with these 2
functions indicates how the files are to be handled at time of transfer.
Note: DB2 CLI uses a temporary file when inserting LOB data in pieces. If the
data originates in a file, the use of a temporary file can be avoided by using
SQLBindFileToParam(). Call SQLGetFunctions() to query if support is
provided for SQLBindFileToParam(), since SQLBindFileToParam() is not
supported against servers that do not support LOBs.
Related concepts:
v “Large object usage in CLI applications” on page 96
v “LOB locators in CLI applications” on page 98
Related reference:
v “SQLBindFileToCol function (CLI) - Bind LOB file reference to LOB column” in
Call Level Interface Guide and Reference, Volume 2
v “SQLBindFileToParam function (CLI) - Bind LOB file reference to LOB
parameter” in Call Level Interface Guide and Reference, Volume 2
v “SQLGetFunctions function (CLI) - Get functions” in Call Level Interface Guide and
Reference, Volume 2
v “SQLPutData function (CLI) - Passing data value for a parameter” in Call Level
Interface Guide and Reference, Volume 2
Related samples:
v “dtlob.c -- How to read and write LOB data”
With mapping in effect, ODBC applications can retrieve and input LOB data by
using the SQLGetData(), SQLPutData() and related functions.
Related concepts:
v “Large object usage in CLI applications” on page 96
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “LOBMaxColumnSize CLI/ODBC configuration keyword” on page 332
v “LongDataCompat CLI/ODBC configuration keyword” on page 333
v “SQL symbolic and default data types for CLI applications” on page 41
v “SQLGetData function (CLI) - Get data from a column” in Call Level Interface
Guide and Reference, Volume 2
v “SQLPutData function (CLI) - Passing data value for a parameter” in Call Level
Interface Guide and Reference, Volume 2
v “SQLSetConnectAttr function (CLI) - Set connection attributes” in Call Level
Interface Guide and Reference, Volume 2
If the application calls SQLCancel() while CLI still needs data for data-at-execution
columns, CLI cancels the operation. The application can then call
SQLBulkOperations() again; canceling does not affect the cursor state or the current
cursor position.
Related reference:
Prerequisites:
Before fetching bulk data using bookmarks and SQLBulkOperations(), ensure you
have initialized your CLI application.
Restrictions:
Bookmarks in DB2 CLI do not persist across cursor close operations. This means
that an application cannot use bookmarks that it has stored from a previous cursor.
Instead, it has to call SQLFetch() or SQLFetchScroll() to retrieve the bookmarks
before updating with bookmarks.
Procedure:
Related tasks:
v “Deleting bulk data with bookmarks using SQLBulkOperations() in CLI
applications” on page 109
v “Initializing CLI applications” on page 18
v “Inserting bulk data with bookmarks using SQLBulkOperations() in CLI
applications” on page 106
v “Updating bulk data with bookmarks using SQLBulkOperations() in CLI
applications” on page 107
Related reference:
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLBulkOperations function (CLI) - Add, update, delete or fetch a set of rows”
in Call Level Interface Guide and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Prerequisites:
Before inserting bulk data with SQLBulkOperations(), ensure you have initialized
your CLI application.
Restrictions:
Bookmarks in DB2 CLI do not persist across cursor close operations. This means
that an application cannot use bookmarks that it has stored from a previous cursor.
Instead, it has to call SQLFetch() or SQLFetchScroll() to retrieve the bookmarks
before updating with bookmarks.
Procedure:
Related concepts:
v “Bookmarks in CLI applications” on page 78
Related tasks:
v “Deleting bulk data with bookmarks using SQLBulkOperations() in CLI
applications” on page 109
v “Initializing CLI applications” on page 18
v “Retrieving bulk data with bookmarks using SQLBulkOperations() in CLI
applications” on page 105
v “Updating bulk data with bookmarks using SQLBulkOperations() in CLI
applications” on page 107
Related reference:
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLBulkOperations function (CLI) - Add, update, delete or fetch a set of rows”
in Call Level Interface Guide and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Prerequisites:
Before updating data in bulk, ensure you have initialized your CLI application.
Restrictions:
Bookmarks in DB2 CLI do not persist across cursor close operations. This means
that an application cannot use bookmarks that it has stored from a previous cursor.
Instead, it has to call SQLFetch() or SQLFetchScroll() to retrieve the bookmarks
before updating with bookmarks.
Related concepts:
v “Bookmarks in CLI applications” on page 78
Related tasks:
v “Deleting bulk data with bookmarks using SQLBulkOperations() in CLI
applications” on page 109
v “Initializing CLI applications” on page 18
v “Inserting bulk data with bookmarks using SQLBulkOperations() in CLI
applications” on page 106
v “Retrieving bulk data with bookmarks using SQLBulkOperations() in CLI
applications” on page 105
Related reference:
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
Prerequisites:
Before deleting data in bulk, ensure you have initialized your CLI application.
Restrictions:
Bookmarks in DB2 CLI do not persist across cursor close operations. This means
that an application cannot use bookmarks that it has stored from a previous cursor.
Instead, it has to call SQLFetch() or SQLFetchScroll() to retrieve the bookmarks
before updating by bookmarks.
Procedure:
Related concepts:
v “Bookmarks in CLI applications” on page 78
Related tasks:
v “Initializing CLI applications” on page 18
v “Inserting bulk data with bookmarks using SQLBulkOperations() in CLI
applications” on page 106
Related reference:
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLBulkOperations function (CLI) - Add, update, delete or fetch a set of rows”
in Call Level Interface Guide and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Prerequisites:
Before importing data with the CLI LOAD utility, ensure you have initialized your
CLI application.
Restrictions:
v Unlike the IBM DB2 LOAD utility, the CLI LOAD utility does not load data
directly from an input file. Instead, if desired, the application should retrieve the
data from the input file and insert it into the appropriate application parameters
that correspond to the parameter markers in the prepared statement.
v If the prepared SQL statement for inserting data contains a SELECT clause,
parameter markers are not supported.
v The prepared SQL statement for inserting data must include parameter markers
for all columns in the target table, unless a fullselect is used instead of the
VALUES clause in the INSERT statement.
v The insertion of data is non-atomic because the load utility precludes atomicity.
LOAD might not be able to successfully insert all the rows passed to it. For
example, if a unique key constraint is violated by a row being inserted, LOAD
will not insert this row but will continue loading the remaining rows.
v A COMMIT will be issued by LOAD. Therefore, if the insertion of the data
completes successfully, the LOAD and any other statements within the
transaction cannot be rolled back.
v The error reporting for the CLI LOAD interface differs from that of array insert.
Non-severe errors or warnings, such as errors with specific rows, will only
appear in the LOAD message file.
Procedure:
Related tasks:
v “Binding parameter markers in CLI applications with column-wise array input”
on page 81
v “Binding parameter markers in CLI applications with row-wise array input” on
page 82
v “Initializing CLI applications” on page 18
Related reference:
v “db2Load API - Load data into a table” in Administrative API Reference
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
v “LOAD command” in Command Reference
Related samples:
v “tbload.c -- How to insert data using the CLI LOAD utility ”
Prerequisites:
Before calling a stored procedure, ensure that you have initialized your CLI
application.
Restrictions:
If the stored procedure being called is uncataloged, ensure that it does not call any
of the CLI schema functions. Calling CLI schema functions from uncataloged
stored procedures is not supported.
Procedure:
For optimal performance, applications should use parameter markers for stored
procedure arguments in the CALL procedure string and then bind the host
variables to those parameter markers. If inbound stored procedure arguments
must be specified as string literals rather than parameter markers, however,
include the ODBC call escape clause delimiters { } in the CALL procedure
statement. For example:
SQLCHAR *stmt = (SQLCHAR *)"{CALL IN_PARAM (123, ’Hello World!’)}";
When string literals and the ODBC escape clause are used in a CALL procedure
statement, the string literals can only be specified as IN mode stored procedure
arguments. INOUT and OUT mode stored procedure arguments must still be
specified using parameter markers.
4. Optional: Prepare the CALL statement by calling SQLPrepare().
5. Bind each parameter of the CALL procedure statement by calling
SQLBindParameter().
Once you have executed the CALL statement, you can retrieve result sets from the
stored procedure if applicable.
Note:
The numeric month and day parts of a DATETYPE data type value will
appear to be reversed in procedure result sets that are returned to DB2 CLI
applications if the values are not returned in ISO format. For example, this
can happen if a local format is used instead. To ensure that DATETYPE data
type value information is correctly intepreted by a client application, the
procedures should be bound to the database with a locale-independent
DATETIME format such as ISO. For example:
db2set DB2_SQLROUTINE_PREPOPTS=“DATETIME ISO”
Note:
DB2 CLI packages are automatically bound to databases when the databases
are created or migrated. If a FixPak is applied to either the client or the
server, however, then you must rebind db2cli.lst by issuing the following
command:
UNIX
db2 bind <BNDPATH>/@db2cli.lst blocking all grant public
Related concepts:
v “Routines: Procedures” in Developing SQL and External Routines
Related tasks:
v “Binding parameter markers in CLI applications” on page 29
v “Initializing CLI applications” on page 18
v “Preparing and executing SQL statements in CLI applications” on page 24
v “Setting up the CLI environment” on page 209
Related reference:
v “CALL statement” in SQL Reference, Volume 2
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLExecDirect function (CLI) - Execute a statement directly” in Call Level
Interface Guide and Reference, Volume 2
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLGetDiagField function (CLI) - Get a field of diagnostic data” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetDiagRec function (CLI) - Get multiple fields settings of diagnostic
record” in Call Level Interface Guide and Reference, Volume 2
v “CLI function return codes” on page 50
v “DB2 CLI bind files and package names” on page 203
v “DB2 CLI stored procedure commit behavior” on page 115
Related samples:
v “spcall.c -- Call individual stored procedures”
v “spclient.c -- Call various stored procedures”
v “spclires.c -- Contrast stored procedure multiple result set handling methods”
v “spserver.c -- Definition of various types of stored procedures”
Related concepts:
v “Routines: Procedures” in Developing SQL and External Routines
Related tasks:
v “Calling stored procedures from CLI applications” on page 113
Related reference:
v “CALL statement” in SQL Reference, Volume 2
When an XML value is retrieved into an application data buffer, the DB2 server
performs an implicit serialization on the XML value to convert it from its stored
hierarchical form to the serialized string form. For character typed buffers, the
XML value is implicitly serialized to the application character code page associated
with the character type.
XQuery expressions and SQL/XML functions can be issued and executed in DB2
CLI applications. SQL/XML functions are issued and executed like any other SQL
statements. XQuery expressions must either be prepended with the case-insensitive
keyword ″XQUERY″, or the SQL_ATTR_XQUERY_STATEMENT statement attribute
must be set for the statement handle associated with the XQuery expression.
Related concepts:
v “Application programming language support for XML” in XML Guide
v “XML column inserts and updates in CLI applications” on page 118
v “XML data encoding” in XML Guide
v “XML data retrieval in CLI applications” on page 119
v “XML data type” in XML Guide
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
For XML data, when you use SQLBindParameter() to bind parameter markers to
input data buffers, you can specify the data type of the input data buffer as
SQL_C_BINARY, SQL_C_CHAR, SQL_C_DBCHAR or SQL_C_WCHAR.
When you bind a data buffer that contains XML data as SQL_C_BINARY, DB2 CLI
processes the XML data as internally encoded data. This is the preferred method
because it avoids the overhead and potential data loss of character conversion
when character types are used.
Important: If the XML data is encoded in an encoding scheme and CCSID other
than the application code page encoding scheme, you need to include
internal encoding in the data and bind the data as SQL_C_BINARY to
avoid character conversion.
When you bind a data buffer that contains XML data as SQL_C_CHAR,
SQL_C_DBCHAR or SQL_C_WCHAR, DB2 CLI processes the XML data as
externally encoded data. DB2 CLI determines the encoding of the data as follows:
v If the C type is SQL_C_WCHAR, DB2 CLI assumes that the data is encoded as
UCS-2.
v If the C type is SQL_C_CHAR or SQL_C_DBCHAR, DB2 CLI assumes that the
data is encoded in the application code page encoding scheme.
If you want the database server to implicitly parse the data before storing it in an
XML column, the parameter marker data type in SQLBindParameter() should be
specified as SQL_XML.
The following example shows how to update XML data in an XML column using
the recommended SQL_C_BINARY type.
char xmlBuffer[10240];
integer length;
// Assume a table named dept has been created with the following statement:
// CREATE TABLE dept (id CHAR(8), deptdoc XML)
Related concepts:
v “Application programming language support for XML” in XML Guide
v “Creation of tables with XML columns” in XML Guide
v “Updates of XML columns” in XML Guide
Related reference:
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLPrepare function (CLI) - Prepare a statement” in Call Level Interface Guide
and Reference, Volume 2
v “XMLPARSE scalar function” in SQL Reference, Volume 1
v “Data conversions supported in CLI” on page 397
For XML data, when you use SQLBindCol() to bind columns in a query result set to
application variables, you can specify the data type of the application variables as
SQL_C_BINARY, SQL_C_CHAR, SQL_C_DBCHAR or SQL_C_WCHAR. When
retrieving a result set from an XML column, it is recommended that you bind your
application variable to the SQL_C_BINARY type. Binding to character types can
result in possible data loss resulting from code page conversion. Data loss can
occur when characters in the source code page cannot be represented in the target
code page. Binding your variable to the SQL_C_BINARY C type avoids these
issues.
XML data is returned to the application as internally encoded data. DB2 CLI
determines the encoding of the data as follows:
v If the C type is SQL_C_BINARY, DB2 CLI returns the data in the UTF-8
encoding scheme.
v If the C type is SQL_C_CHAR or SQL_C_DBCHAR, DB2 CLI returns the data in
the application code page encoding scheme.
v If the C type is SQL_C_WCHAR, DB2 CLI returns the data in the UCS-2
encoding scheme.
The database server performs an implicit serialization of the data before returning
it to the application. You can explicitly serialize the XML data to a specific data
type by calling the XMLSERIALIZE function. Implicit serialization is
recommended, however, because explicitly serializing to character types with
XMLSERIALIZE can introduce encoding issues.
The following example shows how to retrieve XML data from an XML column into
a binary application variable.
char xmlBuffer[10240];
// xmlBuffer is used to hold the retrieved XML document
integer length;
// Assume a table named dept has been created with the following statement:
// CREATE TABLE dept (id CHAR(8), deptdoc XML)
Related concepts:
v “XML data handling in CLI applications - Overview” on page 117
v “Application programming language support for XML” in XML Guide
v “XML data encoding” in XML Guide
v “XML data querying” in XML Guide
v “XML data type” in XML Guide
v “XML serialization” in XML Guide
Related reference:
v “Data conversions supported in CLI” on page 397
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLCloseCursor function (CLI) - Close cursor and discard pending results” in
Call Level Interface Guide and Reference, Volume 2
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLFetch function (CLI) - Fetch next row” in Call Level Interface Guide and
Reference, Volume 2
v “XMLSERIALIZE scalar function” in SQL Reference, Volume 1
MapXMLDescribe specifies which SQL data type is returned when XML columns
or parameter markers are described.
Related concepts:
v “Data types and data conversion in CLI applications” on page 39
v “XML data handling in CLI applications - Overview” on page 117
v “XML data type” in XML Guide
Related reference:
Restrictions:
v Compound SQL does not guarantee the order in which the substatements are
executed, therefore there must not be any dependencies among the
substatements.
v Compound SQL statements cannot be nested.
v The BEGIN COMPOUND and END COMPOUND statements must be executed
with the same statement handle.
v The value specified in the STOP AFTER FIRST ? STATEMENTS clause of the
BEGIN COMPOUND SQL statement must be of type SQL_INTEGER, and you
can only bind an application buffer of type SQL_C_INTEGER or
SQL_C_SMALLINT for this value.
v Each substatement must have its own statement handle.
v All statement handles must belong to the same connection and have the same
isolation level.
v Atomic array input is not supported within a BEGIN COMPOUND and END
COMPOUND block of SQL statements. Atomic array input refers to the behavior
where all inserts will be undone if any single insert fails.
v All statement handles must remain allocated until the END COMPOUND
statement is executed.
v SQLEndTran() cannot be called for the same connection or any connect requests
between BEGIN COMPOUND and END COMPOUND.
v Only the following functions may be called using the statement handles
allocated for the compound substatements:
– SQLAllocHandle()
– SQLBindParameter()
– SQLBindFileToParam()
– SQLExecute()
– SQLParamData()
– SQLPrepare()
– SQLPutData()
Procedure:
If the application is not operating in auto-commit mode and the COMMIT option
is not specified, the sub-statements will not be committed. If the application is
operating in auto-commit mode, however, then the sub-statements will be
committed at END COMPOUND, even if the COMMIT option is not specified.
Related tasks:
v “Allocating statement handles in CLI applications” on page 22
v “Binding parameter markers in CLI applications with column-wise array input”
on page 81
v “Binding parameter markers in CLI applications with row-wise array input” on
page 82
v “Freeing statement resources in CLI applications” on page 37
v “Preparing and executing SQL statements in CLI applications” on page 24
Related reference:
Related samples:
v “dbuse.c -- How to use a database”
ATOMIC
v SQL_SUCCESS: all substatements have executed without any warnings or errors.
v SQL_SUCCESS_WITH_INFO: all substatements executed successfully with one
or more warnings. Call SQLGetDiagRec() or SQLGetDiagField() to retrieve
additional information on the error or warning. The handle used by
SQLGetDiagRec() or SQLGetDiagField() must be the same one used to process
the BEGIN COMPOUND and END COMPOUND statements.
v SQL_NO_DATA_FOUND: BEGIN COMPOUND and END COMPOUND
statements executed without any substatements, or none of the substatements
affected any rows.
v SQL_ERROR: one or more substatements failed and all substatements were
rolled back.
NOT ATOMIC
v SQL_SUCCESS: all substatements executed without any errors.
v SQL_SUCCESS_WITH_INFO: the COMPOUND statement executed with one or
more warnings returned by one or more substatements. Call SQLGetDiagRec() or
SQLGetDiagField() to retrieve additional information on the error or warning.
The handle used by SQLGetDiagRec() or SQLGetDiagField() must be the same
one used to process the BEGIN COMPOUND and END COMPOUND
statements.
v SQL_NO_DATA_FOUND: the BEGIN COMPOUND and END COMPOUND
statements executed without any substatements, or none of the substatements
affected any rows.
Related tasks:
v “Executing compound SQL statements in CLI applications” on page 123
Related reference:
v “Compound SQL (Dynamic) statement” in SQL Reference, Volume 2
v “SQLCA (SQL communications area)” in SQL Reference, Volume 1
v “SQLError function (CLI) - Retrieve error information” in Call Level Interface
Guide and Reference, Volume 2
v “SQLExecDirect function (CLI) - Execute a statement directly” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetSQLCA function (CLI) - Get SQLCA data structure” in Call Level
Interface Guide and Reference, Volume 2
Once a function has been called asynchronously, only the original function,
SQLAllocHandle(), SQLCancel(), SQLGetDiagField(), or SQLGetDiagRec() can be
called on the statement or the connection associated with StatementHandle, until the
original function returns a code other than SQL_STILL_EXECUTING. Any other
function called on StatementHandle or the connection associated with
StatementHandle returns SQL_ERROR with an SQLSTATE of HY010 (Function
sequence error.).
The application can issue a request to cancel any function that is running
asynchronously by calling SQLCancel(). A function that has already finished
executing cannot be cancelled.
The return code from the SQLCancel() call indicates whether the cancel request
was received, not whether the execution of the asynchronous function was
stopped.
The only way to tell if the function was canceled is to call it again, using the
original arguments.
v If the cancel was successful, the function will return SQL_ERROR and an
SQLSTATE of HY008 (Operation was cancelled.).
v If the cancel was not successful, the function will return a value other than
SQL_ERROR with an SQLSSTATE of HY008. For example, the function might
return SQL_STILL_EXECUTING.
Related tasks:
v “Executing functions asynchronously in CLI applications” on page 129
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Header and record fields for the DiagIdentifier argument (CLI)” in Call Level
Interface Guide and Reference, Volume 2
v “SQLCancel function (CLI) - Cancel statement” in Call Level Interface Guide and
Reference, Volume 2
v “SQLGetDiagField function (CLI) - Get a field of diagnostic data” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetDiagRec function (CLI) - Get multiple fields settings of diagnostic
record” in Call Level Interface Guide and Reference, Volume 2
v “SQLGetInfo function (CLI) - Get general information” in Call Level Interface
Guide and Reference, Volume 2
v “SQLSetConnection function (CLI) - Set connection handle” in Call Level Interface
Guide and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
Prerequisites:
Before you begin setting up your CLI application for asynchronous execution, you
must allocate an environment handle and a connection handle. This is part of the
task of initializing your CLI application.
Restrictions:
Procedure:
1. Call SQLGetInfo() with InfoType SQL_ASYNC_MODE to ensure that functions
can be called asynchronously. For example:
/* See what type of Asynchronous support is available. */
rc = SQLGetInfo( hdbc, /* Connection handle */
SQL_ASYNC_MODE, /* Query the support available */
&ubuffer, /* Store the result in this variable */
4,
&outlen);
The call to the SQLGetInfo() function will return one of the following values:
v SQL_AM_STATEMENT: asynchronous execution can be turned on or off at a
statement level.
v SQL_AM_CONNECTION: asynchronous execution can be turned on or off at
a connection level.
v SQL_AM_NONE: asynchronous execution is not supported. Your application
cannot be set up for asynchronous execution. This will be returned for one of
two reasons:
– The datasource itself does not support asynchronous execution.
– The DB2 CLI/ODBC configuration keyword ASYNCENABLE has been
specifically set to disable asynchronous execution.
2. Set the SQL_ATTR_ASYNC_ENABLE attribute using SQLSetStmtAttr() or
SQLSetConnectAttr() to enable your application for asynchronous execution if
the return value from SQLGetInfo() is either SQL_AM_STATEMENT or
SQL_AM_CONNECTION.
v If the return value is SQL_AM_STATEMENT, set
SQL_ATTR_ASYNC_ENABLE to SQL_ASYNC_ENABLE_ON using
SQLSetStmtAttr(). For example:
Related concepts:
v “Asynchronous execution of CLI functions” on page 127
Related tasks:
v “Initializing CLI applications” on page 18
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “SQLExecDirect function (CLI) - Execute a statement directly” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetInfo function (CLI) - Get general information” in Call Level Interface
Guide and Reference, Volume 2
v “SQLSetConnectAttr function (CLI) - Set connection attributes” in Call Level
Interface Guide and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Note: If you are writing applications that use DB2 CLI calls and either embedded
SQL or DB2 API calls, see the documentation for multithreaded mixed
applications.
Concurrent execution means that two threads can run independently of each other
(on a multi-processor machine they may run simultaneously). For example, an
application could implement a database-to-database copy in the following way:
v One thread connects to database A and uses SQLExecute() and SQLFetch() calls
to read data from one connection into a shared application buffer.
v The other thread connects to database B and concurrently reads from the shared
buffer and inserts the data into database B.
In contrast, if DB2 CLI serializes all function calls, only one thread may be
executing a DB2 CLI function at a time. All other threads would have to wait until
the current thread is done before it would get a chance to execute.
The most common reason to create another thread in a DB2 CLI application is so a
thread other than the one executing can be used to call SQLCancel() (to cancel a
long running query for example).
Most GUI-based applications use threads in order to ensure that user interaction
can be handled on a higher priority thread than other application tasks. The
application can simply delegate one thread to run all DB2 CLI functions (with the
exception of SQLCancel()). In this case there are no thread-related application
design issues since only one thread will be accessing the data buffers that are used
to interact with DB2 CLI.
Applications that use multiple connections, and are executing statements that may
take some time to execute, should consider executing DB2 CLI functions on
Programming tips:
This means that once a thread starts executing a function with a connection handle,
or child of a connection handle, any other thread will block and wait for the
executing thread to return. The one exception to this is SQLCancel(), which must
be able to cancel a statement currently executing on another thread. For this
reason, the most natural design is to map one thread per connection, plus one
thread to handle SQLCancel() requests. Each thread can then execute
independently of the others.
If an object is shared across threads, application timing issues may arise. For
example, if a thread is using a handle in one thread, and another thread frees that
handle between function calls, the next attempt to use that handle would result in
a return code of SQL_INVALID_HANDLE.
Notes:
1. Thread safety for handles only applies for DB2 CLI applications. ODBC
applications may trap since the handle in this case is a pointer and the pointer
may no longer be valid if another thread has freed it. For this reason, it is best
when writing an ODBC application to follow the application model for
multithreaded CLI applications.
2. There may be platform or compiler specific link options required for
multi-threaded applications. Refer to your compiler documentation for further
details.
Related concepts:
v “Application model for multithreaded CLI applications” on page 134
v “Mixed multithreaded CLI applications” on page 136
Related reference:
v “CLI function return codes” on page 50
v “SQLCancel function (CLI) - Cancel statement” in Call Level Interface Guide and
Reference, Volume 2
This model allows the master thread to have more threads than connections if the
threads are also used to perform non-SQL related tasks, or more connections than
threads if the application wants to maintain a pool of active connections to various
databases, but limit the number of active tasks.
Note: A multithreaded DB2 CLI stored procedure can only connect to the database
where the stored procedure is currently executing.
Most importantly, this ensures that two threads are not trying to use the same
connection handle at any one time. Although DB2 CLI controls access to its
resources, the application resources such as bound columns and parameter buffers
are not controlled by DB2 CLI, and the application must guarantee that a pointer
to a buffer is not being used by two threads at any one time. Any deferred
arguments must remain valid until the column or parameter has been unbound.
If it is necessary for two threads to share a data buffer, the application must
implement some form of synchronization mechanism. For example, in the
database-to-database copy scenario where one thread connects to database A and
reads data from one connection into a shared application buffer while the other
thread connects to database B and concurrently reads from the shared buffer and
inserts data into database B, the use of the shared buffer must be synchronized by
the application.
Application deadlocks:
DB2 can detect deadlocks at the server and rollback one or more transactions to
resolve them. An application may still deadlock if:
v two threads are connected to the same database, and
v one thread is holding an application resource ’A’ and is waiting for a database
resource ’B’, and
v the other thread has a lock on the database resource ’B’ while waiting for the
application resource ’A’.
In this case the DB2 server is only going to see a lock, not a deadlock, and unless
the database LockTimeout configuration keyword is set, the application will wait
forever.
The model suggested above avoids this problem by not sharing application
resources between threads once a thread starts executing on a connection.
Related concepts:
v “Mixed multithreaded CLI applications” on page 136
v “Multithreaded CLI applications” on page 133
Related reference:
v “locktimeout - Lock timeout configuration parameter” in Performance Guide
v “SQLCancel function (CLI) - Cancel statement” in Call Level Interface Guide and
Reference, Volume 2
The DB2 CLI driver automatically calls the DB2 context APIs to allocate and
manage contexts for the application. This means that any application that calls
SQLAllocEnv() before calling any other DB2 API or embedded SQL will be
initialized with the context type set to SQL_CTX_MULTI_MANUAL.
In this case the application should allow DB2 CLI to allocate and manage all
contexts. Use DB2 CLI to allocate all connection handles and to perform all
connections. Call the SQLSetConnect() function in each thread prior to calling any
embedded SQL. DB2 APIs can be called after any DB2 CLI function has been
called in the same thread.
The DB2 CLI driver does not automatically call the DB2 context APIs if the
application calls any DB2 API or embedded SQL functions before a CLI function.
This means that any thread that calls a DB2 API or embedded SQL function must
be attached to a context, otherwise the call will fail with an SQLCODE of
SQL1445N. This can be done by calling the DB2 API sqleAttachToCtx() which will
explicitly attach the thread to a context, or by calling any DB2 CLI function
(SQLSetConnection() for example). In this case, the application must explicitly
manage all contexts.
Use the context APIs to allocate and attach to contexts prior to calling DB2 CLI
functions (SQLAllocEnv() will use the existing context as the default context). Use
the SQL_ATTR_CONN_CONTEXT connection attribute to explicitly set the context
that each DB2 CLI connection should use.
Note: It is recommended that you do not use the default application stack size, but
instead increase the stack size to at least 256 000. DB2 requires a minimum
application stack size of 256 000 when calling a DB2 function. You must
ensure therefore, that you allocate a total stack size that is large enough for
both your application and the minimum requirements for a DB2 function
call.
Related concepts:
v “Application model for multithreaded CLI applications” on page 134
v “Multithreaded CLI applications” on page 133
v “DB2 Call Level Interface (CLI) versus embedded SQL” on page 4
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “SQLAllocEnv function (CLI) - Allocate environment handle” in Call Level
Interface Guide and Reference, Volume 2
v “sqleAttachToCtx API - Attach to context” in Administrative API Reference
With multisite updates, the two phase commit (2PC) protocol, and coordinated
distributed transactions, an application is able to update data in multiple remote
database servers with guaranteed integrity.
Related concepts:
v “Configuration parameter settings for multisite update applications” in
Developing SQL and External Routines
v “DB2 as transaction manager in CLI applications” on page 138
v “Multisite Updates” in DB2 Connect User’s Guide
v “Process-based XA-compliant Transaction Program Monitor (XA TP)
programming considerations for CLI applications” on page 141
Related tasks:
v “Enabling Multisite Updates using the Control Center” in DB2 Connect User’s
Guide
DB2 CLI/ODBC applications can use DB2 itself as the Transaction Manager (DB2
TM) to coordinate distributed transactions against all IBM database servers.
The DB2 Transaction Manager must be set up according to the information in the
DB2 transaction manager configuration documentation.
Figure 9 on page 139 shows the logical flow of an application executing statements
on two SQL_CONCURRENT_TRANS connections (’A’ and ’B’), and indicates the
scope of the transactions.
Restrictions:
Related concepts:
v “DB2 Database transaction manager configuration” in Administration Guide:
Planning
v “Considerations for mixing embedded SQL and DB2 CLI” on page 183
v “db2cli.ini initialization file” on page 277
v “Multisite updates (two phase commit) in CLI applications” on page 137
Related reference:
v “CONNECT (Type 1) statement” in SQL Reference, Volume 2
v “CONNECT (Type 2) statement” in SQL Reference, Volume 2
v “ConnectType CLI/ODBC configuration keyword” on page 301
Related samples:
v “dbmcon.c -- How to use multiple databases”
v “dbmconx.c -- How to use multiple databases with embedded SQL.”
Configuration:
Programming considerations:
DB2 CLI/ODBC applications written for this environment must complete the
following steps:
v The application must first call SQLConnect() or SQLDriverConnect() to associate
the TM-opened connections with the CLI/ODBC connection handle. The data
source name must be specified. User ID and Password are optional.
v The application must call the XA TM to do a commit or rollback. As a result,
since the CLI/ODBC driver does not know that the transaction has ended, the
application should do the following before exiting:
– Drop all CLI/ODBC statement handles.
– Free up the connection handle by calling SQLDisconnect() and
SQLFreeHandle(). The actual database connection will not be disconnected
until the XA TM performs an xa_close.
Restrictions:
Related reference:
v “SQLConnect function (CLI) - Connect to a data source” in Call Level Interface
Guide and Reference, Volume 2
v “SQLDisconnect function (CLI) - Disconnect from a data source” in Call Level
Interface Guide and Reference, Volume 2
v “SQLDriverConnect function (CLI) - (Expanded) Connect to a data source” in
Call Level Interface Guide and Reference, Volume 2
v “SQLFreeHandle function (CLI) - Free handle resources” in Call Level Interface
Guide and Reference, Volume 2
ODBC adds types to the set of C and SQL types that already exist to accommodate
Unicode, and CLI uses these additional types accordingly. The new C type,
SQL_C_WCHAR, indicates that the C buffer contains Unicode data. The DB2
CLI/ODBC driver considers all Unicode data exchanged with the application to be
UCS-2 in native-endian format. The new SQL types, SQL_WCHAR,
SQL_WVARCHAR, and SQL_WLONGVARCHAR, indicate that a particular
column or parameter marker contains Unicode data. For DB2 Unicode databases,
graphic columns are described using the new types. Conversion is allowed
between SQL_C_WCHAR and SQL_CHAR, SQL_VARCHAR,
SQL_LONGVARCHAR and SQL_CLOB, as well as with the graphic data types.
Related concepts:
v “Unicode function calls to ODBC driver managers” on page 145
v “Unicode functions (CLI)” on page 144
v “Applications connected to Unicode databases” in Developing SQL and External
Routines
Related reference:
v “C data types for CLI applications” on page 43
v “Patch2 CLI/ODBC configuration keyword” on page 352
v “SQL symbolic and default data types for CLI applications” on page 41
Unicode functions that have arguments which are always the length of strings
interpret these arguments as the number of SQLWCHAR elements needed to store
the string. For functions that return length information for server data, the display
size and precision are again described in terms of the number of SQLWCHAR
elements used to store them. When the length (transfer size of the data) could refer
to string or non-string data, it is interpreted as the number of bytes needed to store
the data.
For example, SQLGetInfoW() will still take the length as the number of bytes, but
SQLExecDirectW() will use the number of SQLWCHAR elements. Consider a single
character from the UTF-16 extended character set (UTF-16 is an extended character
set of UCS-2; Microsoft Windows 2000 and Microsoft Windows XP use UTF-16).
Microsoft Windows 2000 will use two SQL_C_WCHAR elements, which is
equivalent to 4 bytes, to store this single character. The character therefore has a
The syntax for a DB2 CLI Unicode function is the same as the syntax for its
corresponding ANSI function, except that SQLCHAR parameters are defined as
SQLWCHAR. Character buffers defined as SQLPOINTER in the ANSI syntax can
be defined as either SQLCHAR or SQLWCHAR in the Unicode function. Refer to
the ANSI version of the CLI Unicode functions for ANSI syntax details.
Related concepts:
v “Unicode function calls to ODBC driver managers” on page 145
v “Unicode CLI applications” on page 143
Related reference:
v “CLI and ODBC function summary” in Call Level Interface Guide and Reference,
Volume 2
v “C data types for CLI applications” on page 43
v “SQL symbolic and default data types for CLI applications” on page 41
When connecting to a data source, the ODBC driver manager checks to see if the
requested driver exports the SQLConnectW() function. If the function is supported,
the ODBC driver is considered a Unicode driver, and all subsequent calls in the
application to ODBC functions are routed to the functions’ Unicode equivalents
(identified by the ’W’ suffix; for example, SQLConnectW()) by the ODBC driver
manager. If the application calls Unicode functions, no string conversion is
necessary, and the ODBC driver manager calls the Unicode functions directly. If the
If an application calls Unicode functions, but the driver does not export
SQLConnectW(), then the ODBC driver manager routes any Unicode function calls
to their ANSI equivalents. All Unicode strings are converted by the ODBC driver
manager to ANSI strings in the application’s code page before calling the
equivalent ANSI function. This might result in data loss if the application uses
Unicode characters which cannot be converted to the application’s code page.
Various ODBC driver managers use different encoding schemes for Unicode
strings, depending on the operating system:
Table 11. Unicode string encoding schemes by operating system
Operating system
Driver manager Microsoft Windows Linux and UNIX
Microsoft ODBC Driver UTF-16* not applicable
Manager
unixODBC Driver Manager UCS-2 UCS-2
DataDirect Connect for UTF-16* UTF-8
ODBC Driver Manager
* UTF-16 is a superset of UCS-2 and therefore is compatible
Complications arise when using the DB2 CLI/ODBC driver with the DataDirect
Connect for ODBC Driver Manager in the UNIX environment because of the use of
UTF-8 character encoding by the driver manager. UTF-8 is a variable length
character encoding scheme using anywhere from 1 to 6 bytes to store characters.
UTF-8 and UCS-2 are not inherently compatible, and passing UTF-8 data to the
DB2 CLI/ODBC driver (which expects UCS-2) might result in application errors,
data corruption, or application exceptions.
To avoid this problem, the DataDirect Connect for ODBC Driver Manager 4.2
Service Pack 2 recognizes a DB2 CLI/ODBC driver and not use the Unicode
functions, effectively treating the DB2 CLI/ODBC driver as an ANSI-only driver.
Before release 4.2 Service Pack 2, the DataDirect Connect for ODBC Driver
Manager had to be linked with the "_36" version of the DB2 CLI/ODBC driver
which does not export the SQLConnectW() function.
Related concepts:
v “Comparison of DB2 CLI and Microsoft ODBC” on page 9
v “Unicode CLI applications” on page 143
v “Unicode functions (CLI)” on page 144
Related tasks:
v “Setting up the unixODBC Driver Manager” on page 212
v “Setting up the UNIX ODBC environment” on page 210
Distinct types help provide the strong typing control needed in object oriented
programming by ensuring that only those functions and operators explicitly
defined on a distinct type can be applied to its instances. Applications continue to
work with C data types for application variables, and only need to consider the
distinct types when constructing SQL statements.
This means:
v All SQL to C data type conversion rules that apply to the built-in type apply to
distinct types.
v Distinct types will have the same default C Type as the built-in type.
v SQLDescribeCol() will return the built-in type information. The user defined
type name can be obtained by calling SQLColAttribute() with the input
descriptor type set to SQL_DESC_DISTINCT_TYPE.
v SQL predicates that involve parameter markers must be explicitly cast to the
distinct type. This is required since the application can only deal with the
built-in types, so before any operation can be performed using the parameter, it
must be cast from the C built-in type to the distinct type; otherwise an error will
occur when the statement is prepared.
Related concepts:
v “User-defined type (UDT) usage in CLI applications” on page 148
Related reference:
v “C data types for CLI applications” on page 43
v “CREATE DISTINCT TYPE statement” in SQL Reference, Volume 2
v “SQL symbolic and default data types for CLI applications” on page 41
v “SQL to C data conversion in CLI” on page 399
v “SQLColAttribute function (CLI) - Return a column attribute” in Call Level
Interface Guide and Reference, Volume 2
v “SQLDescribeCol function (CLI) - Return a set of attributes for a column” in Call
Level Interface Guide and Reference, Volume 2
Related samples:
v “dtudt.c -- How to create, use, and drop user-defined distinct types.”
Additionally, the following descriptor fields may be used to obtain the type names:
v SQL_DESC_REFERENCE_TYPE contains the name of the reference type, or an
empty string if the column is not a reference type.
v SQL_DESC_STRUCTURED_TYPE contains the name of the structured type, or
an empty string if the column is not a structured type.
v SQL_DESC_USER_TYPE or SQL_DESC_DISTINCT_TYPE contains the name of
the distinct type, or an empty string if the column is not a distinct type.
The descriptor fields listed above return the schema as part of the name. If the
schema is less than 8 letters, it is padded with blanks.
A CLI application may not wish to repeatedly obtain the value of the
SQL_DESC_USER_DEFINED_TYPE_CODE descriptor field to determine if columns
contain UDTs. For this reason, there is an attribute called
SQL_ATTR_RETURN_USER_DEFINED_TYPES at both the connection and the
statement handle level. When set to SQL_TRUE using SQLSetConnectAttr(), CLI
returns SQL_DESC_USER_DEFINED_TYPE where you would normally find SQL
types in results from calls to SQLColAttribute(), SQLDescribeCol() and
SQLGetDescField(). This allows the application to check for this special type, and
then do special processing for UDTs. The default value for this attribute is
SQL_FALSE.
Note that SQLBindParameter() will not allow you to bind a parameter of the type
SQL_USER_DEFINED_TYPE. You must still bind parameters using the base SQL
Related concepts:
v “Distinct type usage in CLI applications” on page 147
Related reference:
v “CREATE DISTINCT TYPE statement” in SQL Reference, Volume 2
v “SQL symbolic and default data types for CLI applications” on page 41
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLColAttribute function (CLI) - Return a column attribute” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetDescField function (CLI) - Get single field settings of descriptor record”
in Call Level Interface Guide and Reference, Volume 2
v “SQLSetConnectAttr function (CLI) - Set connection attributes” in Call Level
Interface Guide and Reference, Volume 2
Related samples:
v “dtudt.c -- How to create, use, and drop user-defined distinct types.”
v “udfcli.c -- How to work with different types of user-defined functions (UDFs)”
Many CLI functions make use of descriptors, but the application itself does not
need to manipulate them directly.
For instance:
v When an application binds column data using SQLBindCol(), descriptor fields
are set that completely describe the binding.
v A number of statement attributes correspond to the header fields of a descriptor.
In this case you can achieve the same effect calling SQLSetStmtAttr() as calling
the corresponding function SQLSetDescField() that sets the values in the
descriptor directly.
The only difference between the four types of descriptors described above is how
they are used. One of the benefits of descriptors is that a single descriptor can be
used to serve multiple purposes. For instance, a row descriptor in one statement
can be used as a parameter descriptor in another statement.
Each descriptor contains both header fields and record fields. These fields together
completely describe the column or parameter.
Header fields:
Each header field occurs once in each descriptor. Changing one of these fields
affects all columns or parameters.
SQL_DESC_ALLOC_TYPE SQL_DESC_BIND_TYPEa
SQL_DESC_ARRAY_SIZEa SQL_DESC_COUNT
SQL_DESC_ARRAY_STATUS_PTRa SQL_DESC_ROWS_PROCESSED_PTRa
SQL_DESC_BIND_OFFSET_PTRa
Note:
a
This header field corresponds to a statement attribute.
Descriptor records:
The following is a list of the fields in a descriptor record. They describe a column
or parameter, and occur once in each descriptor record.
SQL_DESC_AUTO_UNIQUE_VALUE SQL_DESC_LOCAL_TYPE_NAME
SQL_DESC_BASE_COLUMN_NAME SQL_DESC_NAME
SQL_DESC_BASE_TABLE_NAME SQL_DESC_NULLABLE
SQL_DESC_CASE_SENSITIVE SQL_DESC_OCTET_LENGTH
SQL_DESC_CATALOG_NAME SQL_DESC_OCTET_LENGTH_PTR
SQL_DESC_CONCISE_TYPE SQL_DESC_PARAMETER_TYPE
SQL_DESC_DATA_PTR SQL_DESC_PRECISION
SQL_DESC_DATETIME_INTERVAL_CODE SQL_DESC_SCALE
SQL_DESC_DATETIME_INTERVAL_PRECISION SQL_DESC_SCHEMA_NAME
SQL_DESC_DISPLAY_SIZE SQL_DESC_SEARCHABLE
SQL_DESC_FIXED_PREC_SCALE SQL_DESC_TABLE_NAME
SQL_DESC_INDICATOR_PTR SQL_DESC_TYPE
SQL_DESC_LABEL SQL_DESC_TYPE_NAME
SQL_DESC_LENGTH SQL_DESC_UNNAMED
SQL_DESC_LITERAL_PREFIX SQL_DESC_UNSIGNED
SQL_DESC_LITERAL_SUFFIX SQL_DESC_UPDATABLE
Deferred fields:
Deferred fields are created when the descriptor header or a descriptor record is
created. The addresses of the defined variables are stored but not used until a later
point in the application. The application must not deallocate or discard these
variables between the time it associates them with the fields and the time CLI
reads or writes them.
The following table lists the deferred fields and the meaning or a null pointer
where applicable:
Table 12. Deferred fields
Field Meaning of Null value
SQL_DESC_DATA_PTR The record is unbound.
SQL_DESC_INDICATOR_PTR (none)
SQL_DESC_OCTET_LENGTH_PTR (ARD and v ARD: The length information for that column is
APD only) not returned.
v APD: If the parameter is a character string, the
driver assumes that string is null-terminated.
For output parameters, a null value in this field
prevents the driver from returning length
information. (If the SQL_DESC_TYPE field does
not indicate a character-string parameter, the
SQL_DESC_OCTET_LENGTH_PTR field is
ignored.)
SQL_DESC_ARRAY_STATUS_PTR (multirow fetch A multirow fetch failed to return this component
only) of the per-row diagnostic information.
SQL_DESC_ROWS_PROCESSED_PTR (multirow (none)
fetch only)
Related concepts:
v “Consistency checks for descriptors in CLI applications” on page 154
v “Descriptor allocation and freeing” on page 155
v “Descriptor manipulation with descriptor handles in CLI applications” on page
158
v “Descriptor manipulation without using descriptor handles in CLI applications”
on page 160
Related reference:
v “Descriptor FieldIdentifier argument values (CLI)” in Call Level Interface Guide
and Reference, Volume 2
v “Descriptor header and record field initialization values (CLI)” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetDescField function (CLI) - Get single field settings of descriptor record”
in Call Level Interface Guide and Reference, Volume 2
v “SQLSetDescField function (CLI) - Set a single field of a descriptor record” in
Call Level Interface Guide and Reference, Volume 2
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
To force a consistency check of IPD fields, the application can set the
SQL_DESC_DATA_PTR field of the IPD. This setting is only used to force the
consistency check. The value is not stored and cannot be retrieved by a call to
SQLGetDescField() or SQLGetDescRec().
Application descriptors:
Related concepts:
v “Descriptors in CLI applications” on page 151
Related reference:
v “Descriptor FieldIdentifier argument values (CLI)” in Call Level Interface Guide
and Reference, Volume 2
v “Descriptor header and record field initialization values (CLI)” in Call Level
Interface Guide and Reference, Volume 2
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLSetDescRec function (CLI) - Set multiple descriptor fields for a column or
parameter data” in Call Level Interface Guide and Reference, Volume 2
Note: The descriptors whose handles are obtained in this manner will still
be freed when the statement for which they were allocated is freed.
Explicitly allocated descriptors
An application can explicitly allocate application descriptors. It is not
possible, however, to allocate implementation descriptors.
An application descriptor can be explicitly allocated any time the
application is connected to the database. To explicitly allocate the
application descriptor, call SQLAllocHandle() with a HandleType of
SQL_HANDLE_DESC. For example, the following call explicitly allocates
an application row descriptor:
rc = SQLAllocHandle( SQL_HANDLE_DESC, hdbc, &hARD ) ;
Field initialization:
When an application row descriptor is allocated, its fields are initialized to the
values listed in the descriptor header and record field initialization values
documentation. The SQL_DESC_TYPE field is set to SQL_DEFAULT which
provides for a standard treatment of database data for presentation to the
application. The application may specify different treatment of the data by setting
fields of the descriptor record.
There are no default values for the fields of an IRD. The fields are set when there
is a prepared or executed statement.
Automatic population of the IPD involves some overhead. If it is not necessary for
this information to be automatically gathered by the CLI driver then the
SQL_ATTR_ENABLE_AUTO_IPD statement attribute should be set to SQL_FALSE.
When automatic population of the IPD is active, each call to SQLPrepare() causes
the fields of the IPD to be updated. The resulting descriptor information can be
retrieved by calling the following functions:
v SQLGetDescField()
v SQLGetDescRec()
v SQLDescribeParam()
Freeing of descriptors:
Explicitly allocated descriptors
When an explicitly allocated descriptor is freed, all statement handles to
which the freed descriptor applied automatically revert to the original
descriptors implicitly allocated for them.
Explicitly allocated descriptors can be freed in one of two ways:
v by calling SQLFreeHandle()with a HandleType of SQL_HANDLE_DESC
v by freeing the connection handle that the descriptor is associated with
Implicitly allocated descriptors
An implicitly allocated descriptor can be freed in one of the following
ways:
v by calling SQLDisconnect() which drops any statements or descriptors
open on the connection
v by calling SQLFreeHandle() with a HandleType of SQL_HANDLE_STMT
to free the statement handle and all of the implicitly allocated
descriptors associated with the statement
An implicitly allocated descriptor cannot be freed by calling
SQLFreeHandle() with a HandleType of SQL_HANDLE_DESC.
Related concepts:
v “Descriptors in CLI applications” on page 151
Related reference:
v “Descriptor FieldIdentifier argument values (CLI)” in Call Level Interface Guide
and Reference, Volume 2
v “Descriptor header and record field initialization values (CLI)” in Call Level
Interface Guide and Reference, Volume 2
v “SQLFreeHandle function (CLI) - Free handle resources” in Call Level Interface
Guide and Reference, Volume 2
v “SQLPrepare function (CLI) - Prepare a statement” in Call Level Interface Guide
and Reference, Volume 2
Related samples:
v “dbuse.c -- How to use a database”
The DB2 CLI function SQLGetDescField() can be used to obtain a single field of a
descriptor record. SQLGetDescRec() retrieves the settings of multiple descriptor
fields that affect the data type and storage of column or parameter data.
Two methods are available for setting descriptor fields: one field at a time or
multiple fields at once.
Some fields of a descriptor are read-only, but others can be set using the function
SQLSetDescField(). Refer to the list of header and record fields in the descriptor
FieldIdentifier values documentation.
Record and header fields are set differently using SQLSetDescField() as follows:
Header fields
The call to SQLSetDescField() passes the header field to be set and a
record number of 0. The record number is ignored since there is only one
header field per descriptor. In this case the record number of 0 does not
indicate the bookmark field.
Record fields
The call to SQLSetDescField() passes the record field to be set and a record
number of 1 or higher, or 0 to indicate the bookmark field.
The application must follow the sequence of setting descriptor fields described in
the SQLSetDescField() documentation when setting individual fields of a
descriptor. Setting some fields will cause DB2 CLI to automatically set other fields.
A consistency check will take place after the application follows the defined steps.
This will ensure that the values in the descriptor fields are consistent.
If a function call that would set a descriptor fails, the content of the descriptor
fields are undefined after the failed function call.
A predefined set of descriptor fields can be set with one call rather than setting
individual fields one at a time. SQLSetDescRec() sets the following fields for a
single column or parameter:
v SQL_DESC_TYPE
v SQL_DESC_OCTET_LENGTH
v SQL_DESC_PRECISION
v SQL_DESC_SCALE
v SQL_DESC_DATA_PTR
v SQL_DESC_OCTET_LENGTH_PTR
v SQL_DESC_INDICATOR_PTR
(SQL_DESC_DATETIME_INTERVAL_CODE is also defined by ODBC but is not
supported by DB2 CLI.)
For example, all of the descriptor fields listed above are set with the following call:
/* dbuse.c */
/* ... */
rc = SQLSetDescRec(hARD, 1, type, 0,
length, 0, 0, &id_no, &datalen, NULL);
Copying of descriptors:
One benefit of descriptors is the fact that a single descriptor can be used for
multiple purposes. For instance, an ARD on one statement handle can be used as
an APD on another statement handle.
There will be other instances, however, where the application will want to make a
copy of the original descriptor, then modify certain fields. In this case
SQLCopyDesc() is used to overwrite the fields of an existing descriptor with the
values from another descriptor. Only fields that are defined for both the source and
target descriptors are copied (with the exception of the SQL_DESC_ALLOC_TYPE
field which cannot be changed).
Fields can be copied from any type of descriptor, but can only be copied to an
application descriptor (APD or ARD) or an IPD. Fields cannot be copied to an IRD.
The descriptor’s allocation type will not be changed by the copy procedure (again,
the SQL_DESC_ALLOC_TYPE field cannot be changed).
Related concepts:
v “Consistency checks for descriptors in CLI applications” on page 154
v “Descriptors in CLI applications” on page 151
v “Handles in CLI” on page 15
Related reference:
v “Descriptor FieldIdentifier argument values (CLI)” in Call Level Interface Guide
and Reference, Volume 2
v “Descriptor header and record field initialization values (CLI)” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetDescField function (CLI) - Get single field settings of descriptor record”
in Call Level Interface Guide and Reference, Volume 2
v “SQLGetDescRec function (CLI) - Get multiple field settings of descriptor
record” in Call Level Interface Guide and Reference, Volume 2
Related samples:
v “dbuse.c -- How to use a database”
Related concepts:
v “Descriptors in CLI applications” on page 151
v “Handles in CLI” on page 15
An environment handle has attributes which affect the behavior of DB2 CLI
functions under that environment. The application can specify the value of an
attribute by calling SQLSetEnvAttr() and can obtain the current attribute value by
calling SQLGetEnvAttr(). SQLSetEnvAttr() can only be called before any connection
handles have been allocated for the environment handle. For details on each
environment attribute, refer to the list of CLI environment attributes.
A connection handle has attributes which affect the behavior of DB2 CLI functions
under that connection. Of the attributes that can be changed:
v Some can be set any time once the connection handle is allocated.
v Some can be set only before the actual connection has been established.
v Some can be set any time after the connection has been established.
v Some can be set after the connection has been established, but only while there
are no outstanding transactions or open cursors.
A statement handle has attributes which affect the behavior of CLI functions
executed using that statement handle. Of the statement attributes that can be
changed:
v Some attributes can be set, but currently are limited to only one specific value.
v Some attributes can be set any time after the statement handle has been
allocated.
v Some attributes can only be set if there is no open cursor on that statement
handle.
The application can specify the value of any statement attribute that can be set by
calling SQLSetStmtAttr() and can obtain the current value of an attribute by
calling SQLGetStmtAttr(). For details on each statement attribute, refer to the list of
CLI statement attributes.
Many applications just use the default attribute settings; however, there may be
situations where some of these defaults are not suitable for a particular user of the
application. Some default values can be changed by setting the CLI/ODBC
The DB2 CLI initialization file can be used to change default values for all DB2 CLI
applications on that workstation. This may be the end user’s only means of
changing the defaults if the application does not provide a means for the user to
provide default attribute values in the SQLDriverConnect() connection string.
Default attribute values that are specified on SQLDriverConnect() override the
values in the DB2 CLI initialization file for that particular connection.
The mechanisms for changing defaults are intended for end user tuning;
application developers must use the appropriate set-attribute function. If an
application does call a set-attribute or option function with a value different from
the initialization file or the connection string specification, then the initial default
value is overridden and the new value takes effect.
The diagram below shows the addition of the attribute functions to the basic
connect scenario.
SQLGetEnvAttr
(optional)
SQLSetEnvAttr
SQLSetConnectAttr
SQLSetConnectOption
Optionally set
SQLConnect SQLDriverConnect keyword values
SQLGetConnectAttr
(optional)
Some options can only
be changed after the connect
SQLSetConnectAttr
SQLAllocHandle
(Statement)
SQLGetStmtAttr
(optional)
SQLSetStmtAttr
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Handles in CLI” on page 15
v “Programming hints and tips for CLI applications” on page 55
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Environment attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “SQLGetConnectAttr function (CLI) - Get current attribute setting” in Call Level
Interface Guide and Reference, Volume 2
Related samples:
v “dbuse.c -- How to use a database”
v “spcall.c -- Call individual stored procedures”
v “tbread.c -- How to read data from tables”
The catalog functions operate by returning to the application a result set through a
statement handle. Calling these functions is conceptually equivalent to using
SQLExecDirect() to execute a select against the system catalog tables. After calling
these functions, the application can fetch individual rows of the result set as it
would process column data from an ordinary SQLFetch(). The DB2 CLI catalog
functions are:
v SQLColumnPrivileges()
v SQLColumns()
v SQLForeignKeys()
v SQLGetTypeInfo()
v SQLPrimaryKeys()
v SQLProcedureColumns()
v SQLProcedures()
v SQLSpecialColumns()
v SQLStatistics()
v SQLTablePrivileges()
v SQLTables()
The result sets returned by these functions are defined in the descriptions for each
catalog function. The columns are defined in a specified order. In future releases,
other columns may be added to the end of each defined result set, therefore
applications should be written in a way that would not be affected by such
changes.
Some of the catalog functions result in execution of fairly complex queries, and for
this reason should only be called when needed. It is recommended that the
application save the information returned rather than making repeated calls to get
the same information.
Related concepts:
v “Input arguments on catalog functions in CLI applications” on page 168
Related reference:
v “CLI and ODBC function summary” in Call Level Interface Guide and Reference,
Volume 2
Some catalog functions accept pattern values on some of their input arguments.
For example, SQLColumnPrivileges() treats SchemaName and TableName as ordinary
arguments and ColumnName as a pattern value. Refer to the ″Function Arguments″
section of the specific catalog function to see if a particular input argument accepts
pattern values.
Inputs treated as pattern values are used to constrain the size of the result set by
including only matching rows as though the underlying query’s WHERE clause
contained a LIKE predicate. If the application passes a null pointer for a pattern
value input, the argument is not used to restrict the result set (that is, there is no
corresponding LIKE in the WHERE clause). If a catalog function has more than one
pattern value input argument, they are treated as though the LIKE predicates of
the WHERE clauses in the underlying query were joined by AND; a row appears
in this result set only if it meets all the conditions of the LIKE predicates.
These argument values are used on conceptual LIKE predicate(s) in the WHERE
clause. To treat the metadata characters (_, %) as themselves, an escape character
must immediately precede the _ or %. The escape character itself can be specified
as part of the pattern by including it twice in succession. An application can
determine the escape character by calling SQLGetInfo() with
SQL_SEARCH_PATTERN_ESCAPE.
For example, the following calls would retrieve all the tables that start with ’ST’:
/* tbinfo.c */
/* ... */
struct
{ SQLINTEGER ind ;
SQLCHAR val[129] ;
} tbQualifier, tbSchema, tbName, tbType;
struct
{ SQLINTEGER ind ;
SQLCHAR val[255] ;
} tbRemarks;
/* ... */
sqlrc = SQLTables( hstmt, NULL, 0,
tbSchemaPattern, SQL_NTS,
tbNamePattern, SQL_NTS,
NULL, 0);
/* ... */
/* ... */
sqlrc = SQLFetch( hstmt );
/* ... */
while (sqlrc != SQL_NO_DATA_FOUND)
{ /* ... */
sqlrc = SQLFetch( hstmt );
/* ... */
}
Related concepts:
v “Catalog functions for querying system catalog information in CLI applications”
on page 167
Related samples:
v “tbinfo.c -- How to get information about tables from the system catalog tables”
Currently, escape clauses are used extensively by ODBC to define SQL extensions.
DB2 CLI translates the ODBC extensions into the correct DB2 syntax. The
SQLNativeSql() function can be used to display the resulting syntax.
If an application is only going to access DB2 data sources, then there is no reason
to use the escape clauses. If an application is going to access other data sources
that offer the same support through a different syntax, then the escape clauses
increase the portability of the application.
DB2 CLI used both the standard and shorthand syntax for escape clauses. The
standard syntax has been deprecated (although DB2 CLI still supports it). An
escape clause using the standard syntax took the form:
−−(*vendor(vendor-identifier),
product(product-identifier) extended SQL text*)−−
Applications should now only use the shorthand syntax, as described below, to
remain current with the latest ODBC standards.
The ODBC escape clauses for date, time, and timestamp data are:
{d ’value’}
{t ’value’}
{ts ’value’}
d indicates value is a date in the yyyy-mm-dd format,
t indicates value is a time in the hh:mm:ss format
ts indicates value is a timestamp in the yyyy-mm-dd hh:mm:ss[.f...] format.
DB2 CLI will translate the above statement to a DB2 format. SQLNativeSql() can be
used to return the translated statement.
The ODBC escape clauses for date, time, and timestamp literals can be used in
input parameters with a C data type of SQL_C_CHAR.
Note: Not all DB2 servers support outer join. To determine if the current server
supports outer joins, call SQLGetInfo() with the
SQL_SQL92_RELATIONAL_JOIN_OPERATORS and SQL_OJ_CAPABILITIES
options.
LIKE predicate:
where escape-character is any character supported by the DB2 rules governing the
use of the SQL ESCAPE clause.
As an example of how to use an ″escape″ ODBC escape clause, suppose you had a
table Customers with the columns Name and Growth. The Growth column
contains data having the metacharacter ’%’. The following statement would select
all of the values from Name that have values in Growth only between 10% and
19%, excluding 100% and above:
SELECT Name FROM Customers WHERE Growth LIKE ’1_\%’{escape ’\’}
Applications that are not concerned about portability across different vendor
DBMS products should pass an SQL ESCAPE clause directly to the data source. To
determine when LIKE predicate escape characters are supported by a particular
where:
v [?=] indicates the optional parameter marker for the return value
v procedure-name specifies the name of a procedure stored at the data source
v parameter specifies a procedure parameter.
Scalar functions such as string length, substring, or trim can be used on columns of
a result set and on columns that restrict rows of a result set. The ODBC escape
clause for scalar functions is:
{fn scalar-function}
Where, scalar-function can be any function listed in the list of extended scalar
functions.
to:
SELECT FIRSTNAME CONCAT LASTNAME FROM EMPLOYEE
To determine which scalar functions are supported by the current server referenced
by a specific connection handle, call SQLGetInfo() with the options:
Related reference:
v “SQLGetDiagField function (CLI) - Get a field of diagnostic data” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetDiagRec function (CLI) - Get multiple fields settings of diagnostic
record” in Call Level Interface Guide and Reference, Volume 2
v “SQLGetInfo function (CLI) - Get general information” in Call Level Interface
Guide and Reference, Volume 2
v “SQLNativeSql function (CLI) - Get native SQL text” in Call Level Interface Guide
and Reference, Volume 2
v “CALL statement” in SQL Reference, Volume 2
v “Extended scalar functions for CLI applications” on page 174
v “LIKE predicate” in SQL Reference, Volume 1
v “SELECT statement” in SQL Reference, Volume 2
Related samples:
v “dbnative.c -- How to translate a statement that contains an ODBC escape
clause”
The tables in the following sections indicates for which servers (and the earliest
versions) that the function can be accessed, when called from an application using
DB2 CLI.
All errors detected by the following functions, when connected to a DB2 Version 5
or later server, will return SQLSTATE 38552. The text portion of the message is of
the form SYSFUN:nn where nn is one of the following reason codes:
01 Numeric value out of range
02 Division by zero
03 Arithmetic overflow or underflow
04 Invalid date format
05 Invalid time format
06 Invalid timestamp format
07 Invalid character representation of a timestamp duration
08 Invalid interval type (must be one of 1, 2, 4, 8, 16, 32, 64, 128, 256)
09 String too long
10 Length or position in string function out of range
11 Invalid character representation of a floating point number
The string functions in this section are supported by DB2 CLI and defined by
ODBC using vendor escape clauses.
v Character string literals used as arguments to scalar functions must be bounded
by single quotes.
v Arguments denoted as string_exp can be the name of a column, a string literal,
or the result of another scalar function, where the underlying data type can be
represented as SQL_CHAR, SQL_VARCHAR, SQL_LONGVARCHAR, or
SQL_CLOB.
v Arguments denoted as start, length, code or count can be a numeric literal or the
result of another scalar function, where the underlying data type is integer based
(SQL_SMALLINT, SQL_INTEGER).
v The first character in the string is considered to be at position 1.
Table 13. String scalar functions
Servers that
support the
String scalar function Description function
ASCII( string_exp ) Returns the ASCII code value of the leftmost character DB2 for
of string_exp as an integer. workstation
CHAR( code ) Returns the character that has the ASCII code value DB2 for
specified by code. The value of code should be between 0 workstation
and 255; otherwise, the return value is null.
CONCAT( string_exp1, string_exp2 ) Returns a character string that is the result of DB2 for
concatenating string_exp2 to string_exp1. workstation,
MVS™, VM/VSE,
AS/400
DIFFERENCE( string_exp1, string_exp2 Returns an integer value indicating the difference DB2 for
) between the values returned by the SOUNDEX function workstation
for string_exp1 and string_exp2.
INSERT( string_exp1, start, length, Returns a character string where length number of DB2 for
string_exp2 ) characters beginning at start has been replaced by workstation, MVS,
string_exp2 which contains length characters. VM/VSE, AS/400
LCASE( string_exp ) Converts all uppercase characters in string_exp to DB2 for
lowercase. workstation,
VM/VSE
LEFT( string_exp,count ) Returns the leftmost count of characters of string_exp. DB2 for
workstation, MVS,
VM/VSE, AS/400
LENGTH( string_exp ) Returns the number of characters in string_exp, DB2 for
excluding trailing blanks and the string termination workstation, MVS,
character. VM/VSE, AS/400
Note: Trailing blanks are included for DB2 for
MVS/ESA™.
LOCATE( string_exp1, string_exp2 [ Returns the starting position of the first occurrence of DB2 for
,start ]) string_exp1 within string_exp2. The search for the first workstation
occurrence of string_exp1 begins with first character
position in string_exp2 unless the optional argument,
start, is specified. If start is specified, the search begins
with the character position indicated by the value of
start. The first character position in string_exp2 is
indicated by the value 1. If string_exp1 is not found
within string_exp2, the value 0 is returned.
Numeric functions:
The numeric functions in this section are supported by DB2 CLI and defined by
ODBC using vendor escape clauses.
v Arguments denoted as numeric_exp can be the name of a column, the result of
another scalar function, or a numeric literal, where the underlying data type can
be either floating point based ( SQL_NUMERIC, SQL_DECIMAL, SQL_FLOAT,
SQL_REAL, SQL_DOUBLE) or integer based (SQL_SMALLINT, SQL_INTEGER).
v Arguments denoted as double_exp can be the name of a column, the result of
another scalar functions, or a numeric literal where the underlying data type is
floating point based.
v Arguments denoted as integer_exp can be the name of a column, the result of
another scalar functions, or a numeric literal, where the underlying data type is
integer based.
Table 14. Numeric scalar functions
Servers that
support the
Numeric scalar function Description function
ABS( numeric_exp ) Returns the absolute value of numeric_exp DB2 for
workstation,
AS/400
The date and time functions in this section are supported by DB2 CLI and defined
by ODBC using vendor escape clauses.
v Arguments denoted as timestamp_exp can be the name of a column, the result of
another scalar function, or a time, date, or timestamp literal.
v Arguments denoted as date_exp can be the name of a column, the result of
another scalar function, or a date or timestamp literal, where the underlying
data type can be character based, or date or timestamp based.
v Arguments denoted as time_exp can be the name of a column, the result of
another scalar function, or a time or timestamp literal, where the underlying
data types can be character based, or time or timestamp based.
Table 15. Date and time scalar functions
Servers that
support the
Date and time scalar function Description function
CURDATE() Returns the current date as a date value. DB2 for
workstation, MVS,
VM/VSE, AS/400
CURTIME() Returns the current local time as a time value. DB2 for
workstation, MVS,
VM/VSE, AS/400
DAYNAME( date_exp ) Returns a character string containing the name of the DB2 for
day (Sunday, Monday, Tuesday, Wednesday, Thursday, workstation
Friday, Saturday ) for the day portion of date_exp.
For those functions that return a character string containing the name of the day of
week or the name of the month, these character strings will be National Language
Support enabled.
System functions:
The system functions in this section are supported by DB2 CLI and defined by
ODBC using vendor escape clauses.
v Arguments denoted as exp can be the name of a column, the result of another
scalar function, or a literal.
v Arguments denoted as value can be a literal constant.
Table 16. System scalar functions
Servers that
support the
System scalar function Description function
DATABASE() Returns the name of the database corresponding to the DB2 for
connection handle (hdbc). (The name of the database is workstation, MVS,
also available via SQLGetInfo() by specifying the VM/VSE, AS/400
information type SQL_DATABASE_NAME.)
IFNULL( exp, value ) If exp is null, value is returned. If exp is not null, exp is DB2 for
returned. The possible data type(s) of value must be workstation, MVS,
compatible with the data type of exp. VM/VSE, AS/400
USER() Returns the user’s authorization name. (The user’s DB2 for
authorization name is also available via SQLGetInfo() workstation, MVS,
by specifying the information type SQL_USER_NAME.) VM/VSE, AS/400
Conversion function:
Each driver and data source determines which conversions are valid between the
possible data types. As the driver translates the ODBC syntax into native syntax it
will reject the conversions that are not supported by the data source, even if the
ODBC syntax is valid.
Use the function SQLGetInfo() with the appropriate convert function masks to
determine which conversions are supported by the data source.
Table 17. Conversion Function
Servers that
support the
Conversion scalar function Description function
CONVERT( expr_value, data_type ) v data_type indicates the data type of the converted DB2 for
representation of expr_value, and can be either workstation
SQL_CHAR or SQL_DOUBLE.
v expr_value is the value to convert. It can be of various
types, depending on the conversions supported by the
driver and data source. Use the function
SQLGetInfo() with the appropriate convert function
masks to determine which conversions are supported
by the data source.
Related concepts:
v “Vendor escape clauses in CLI applications” on page 171
Related reference:
v “SQL symbolic and default data types for CLI applications” on page 41
If the DB2 CLI application is multithreaded and also makes embedded SQL calls or
DB2 API calls, then each thread must have a DB2 context.
Related concepts:
v “DB2 Call Level Interface (CLI) versus embedded SQL” on page 4
Related reference:
v “SQLSetConnection function (CLI) - Set connection handle” in Call Level Interface
Guide and Reference, Volume 2
Related samples:
v “dbmconx.c -- How to use multiple databases with embedded SQL.”
v “dbusemx.sqc -- How to execute embedded SQL statements in CLI”
Restrictions:
v When executing an application with pre-bound static SQL statements, dynamic
registers that control the dynamic statement behavior will have no effect on the
statements that are converted to static.
v If an application issues DDL (data definition language) statements for objects
that are referenced in subsequent DML (data manipulation language) statements,
you will find all of these statements in the capture file. The CLI/ODBC/JDBC
Static Profiling Bind Tool, db2cap, will attempt to bind them. The bind attempt
will be successful with DBMSs that support the VALIDATE(RUN) bind option,
but it will fail with ones that do not. In this case, the application should not use
Static Profiling.
v The database administrator (DBA) may edit the capture file to add, change, or
remove SQL statements, based on application-specific requirements.
Before running the application during the profiling session, ensure that the
following conditions have been noted:
v An SQL statement must have successfully executed (generated a positive
SQLCODE) for it to be captured in a profiling session. In a statement matching
session, unmatched dynamic statements will continue to execute as dynamic
CLI/ODBC/JDBC calls.
v An SQL statement must be identical character-by-character to the one that was
captured and bound to be a valid candidate for statement matching. Spaces are
significant: for example, ″COL = 1″ is considered different than ″COL=1″. Use
parameter markers in place of literals to improve match hits.
Be aware that there are times when not all dynamic CLI/ODBC calls can be
captured and grouped into a static package. Possible reasons are:
v The application does not regularly free environment handles. During a capture
session, statements captured under a particular environment handle are only
written to the capture file or files when that environment handle is freed.
v The application has complex control flows that make it difficult to cover all
runtime conditions in a single application run.
v The application executes SET statements to change register variables. These
statements are not recorded. Note that there is a limited capability in match
mode to detect dynamic SET SQLID and SET SCHEMA statements, and suspend
executing static statements accordingly. However, for other SET statements,
subsequent SQL statements which depend on the register variables being set
may not behave properly.
Since dynamic and static SQL are quite different, the DBA should always verify the
behaviour of the application in static match mode before making it available to end
users. Furthermore, while static SQL may offer improved runtime performance
over dynamic SQL, this is not necessarily true for all statements. If testing shows
that static execution decreases performance for a particular statement, the DBA can
force that statement to be dynamically executed by removing the statement from
the capture file. In addition, static SQL, unlike dynamic SQL, may require
occasional rebinding of packages to maintain performance, particularly if the
database objects referred to in the packages frequently change. If CLI/ODBC/JDBC
Static Profiling does not fit the type of application you are running, there are other
programming methods which allow you to obtain the benefits of static SQL, such
as embedded SQL and stored procedures.
Procedure:
To create static SQL statements from existing dynamic SQL statements, perform the
following steps:
1. Profile the application by capturing all the dynamic SQL statements issued by
the application. This process is known as running the application in static
capture mode. To turn on static capture mode, set the following CLI/ODBC
configuration keywords for the CLI/ODBC/JDBC data source in the
db2cli.ini configuration file, before running the application:
v StaticMode = CAPTURE
v StaticPackage = qualified package name
v StaticCapFile = capture file name
For example:
[DSN1]
StaticMode = CAPTURE
StaticPackage = MySchema.MyPkg
StaticCapFile = E:\Shared\MyApp.cpt
Attention: For the StaticPackage keyword, ensure that you specify a schema
name (MySchema in the sample above). If a schema is not specified, the name
you provide will be considered to be the container name instead of the package
name, and the package name will be blank.
The resulting static profile takes the form of a text-based capture file, containing
information about the SQL statements captured.
The above example file yields the following results: Data Source Name 1
(DSN1) is set to capture mode; the package will be named MySchema.MyPkg; and
the capture file, MyApp.cpt, will be saved in the E:\Shared\ directory. Until the
StaticMode keyword is changed to a value other than CAPTURE, such as
DISABLED which is used to turn off static capture mode, each subsequent run of
this application will capture SQL statements and append them to the capture
file MyApp.cpt. Only unique SQL statements will be captured however, as
duplicate executions are ignored.
2. Optional: Set the CLI/ODBC configuration keyword StaticLogFile to generate a
CLI/ODBC/JDBC Static Profiling log file. It contains useful information to
determine the state of the statement capturing process.
3. Run the application.
Related concepts:
v “Capture file for CLI/ODBC/JDBC Static Profiling” on page 187
v “Characteristics and reasons for using static SQL” in Developing SQL and External
Routines
Related reference:
v “db2cap - CLI/ODBC static package binding tool command” in Command
Reference
v “StaticCapFile CLI/ODBC configuration keyword” on page 368
v “StaticLogFile CLI/ODBC configuration keyword” on page 369
v “StaticMode CLI/ODBC configuration keyword” on page 370
v “StaticPackage CLI/ODBC configuration keyword” on page 370
To help you understand how to edit SQL statements, here is the description of the
fields in a statement:
Field Description
SQLID If present, indicates the SCHEMA or SQLID when the
statement was captured is different from the default
QUALIFIER of the package(s).
SECTNO Section number of the static package that the statement was
bound to.
ISOLATION Isolation level for the statement. It determines which one of
the five possible package the statement belongs to.
STMTTEXT Statement string
STMTTYPE There are 3 possible values:
v SELECT_CURSOR_WITHHOLD: SELECT statement
using a withhold cursor
v SELECT_CURSOR_NOHOLD: SELECT statement using a
nohold cursor
v OTHER: non-SELECT statements
CURSOR Cursor name declared for the SELECT statement
INVARnn Description of the n-th input variable
Related concepts:
v “Introduction to DB2 CLI and ODBC” on page 3
Related tasks:
v “Creating static SQL with CLI/ODBC/JDBC Static Profiling” on page 185
The DB2 CLI and the DB2 JDBC Type 2 Driver for Linux, UNIX, and Windows
offer comprehensive tracing facilities. By default, these facilities are disabled and
use no additional computing resources. When enabled, the trace facilities generate
one or more text log files whenever an application accesses the appropriate driver
(DB2 CLI or DB2 JDBC Type 2 Driver). These log files provide detailed information
about:
v the order in which CLI or JDBC functions were called by the application
v the contents of input and output parameters passed to and received from CLI or
JDBC functions
v the return codes and any error or warning messages generated by CLI or JDBC
functions
Note: This trace facility does not apply to the DB2 Universal JDBC Driver.
DB2 CLI and DB2 JDBC trace file analysis can benefit application developers in a
number of ways. First, subtle program logic and parameter initialization errors are
often evident in the traces. Second, DB2 CLI and DB2 JDBC traces might suggest
ways of better tuning an application or the databases it accesses. For example, if a
DB2 CLI trace shows a table being queried many times on a particular set of
attributes, an index corresponding to those attributes might be created on the table
to improve application performance. Finally, analysis of DB2 CLI and DB2 JDBC
trace files can help application developers understand how a third party
application or interface is behaving.
The configuration parameters for both DB2 CLI and DB2 JDBC traces facilities are
read from the DB2 CLI configuration file db2cli.ini. By default, this file is located
in the \sqllib path on the Windows platform and the /sqllib/cfg path on UNIX
platforms. You can override the default path by setting the DB2CLIINIPATH
environment variable. On the Windows platform, an additional db2cli.ini file can
be found in the user’s profile (or home) directory if there are any user-defined data
sources defined using the ODBC Driver Manager. This db2cli.ini file will
override the default file.
To view the current db2cli.ini trace configuration parameters from the command
line processor, issue the following command:
db2 GET CLI CFG FOR SECTION COMMON
Important: Disable the DB2 CLI and DB2 JDBC trace facilities when they are not
needed. Unnecessary tracing can reduce application performance and
generate unwanted trace log files. DB2 does not delete any generated
trace files and will append new trace information to any existing trace
files.
When an application using the DB2 CLI driver begins execution, the driver checks
for trace facility options in the [COMMON] section of the db2cli.ini file. These
trace options are specific trace keywords that are set to certain values in the
db2cli.ini file under the [COMMON] section.
Note: Because DB2 CLI trace keywords appear in the [COMMON] section of the
db2cli.ini file, their values apply to all database connections through the
DB2 CLI driver.
An example db2cli.ini file trace configuration using these DB2 CLI keywords and
values is:
[COMMON]
trace=1
TraceFileName=\temp\clitrace.txt
TraceFlush=1
Notes:
1. CLI trace keywords are NOT case sensitive. However, path and file name
keyword values might be case-sensitive on some operating systems (such as
UNIX).
2. If either a DB2 CLI trace keyword or its associated value in the db2cli.ini file
is invalid, the DB2 CLI trace facility will ignore it and use the default value for
that trace keyword instead.
When an application using the DB2 JDBC Type 2 Driver begins execution, the
driver also checks for trace facility options in the db2cli.ini file. As with the DB2
CLI trace options, DB2 JDBC trace options are specified as keyword/value pairs
located under the [COMMON] section of the db2cli.ini file.
Note: Because DB2 JDBC trace keywords appear in the [COMMON] section of the
db2cli.ini file, their values apply to all database connections through the
DB2 JDBC Type 2 Driver.
Note: Each DB2 JDBC log file close and reopen operation incurs significant
input/output overhead and can reduce application performance
considerably.
An example db2cli.ini file trace configuration using these DB2 JDBC keywords
and values is:
[COMMON]
jdbctrace=1
JdbcTracePathName=\temp\jdbctrace\
JDBCTraceFlush=1
Notes:
1. JDBC trace keywords are NOT case sensitive. However, path and file name
keyword values might be case-sensitive on some operating systems (such as
UNIX).
2. If either a DB2 JDBC trace keyword or its associated value in the db2cli.ini
file is invalid, the DB2 JDBC trace facility will ignore it and use the default
value for that trace keyword instead.
3. Enabling DB2 JDBC tracing does not enable DB2 CLI tracing. The DB2 JDBC
Type 2 Driver depends on the DB2 CLI driver to access the database.
Consequently, Java™ developers might also want to enable DB2 CLI tracing for
additional information on how their applications interact with the database
through the various software layers. DB2 JDBC and DB2 CLI trace options are
independent of each other and can be specified together in any order under the
[COMMON] section of the db2cli.ini file.
An ODBC driver manager might forward some function calls directly from the
application to the DB2 CLI driver. However, the ODBC driver manager might also
delay or avoid forwarding some function calls to the driver. The ODBC driver
manager might also modify application function arguments or map application
functions to other functions before forwarding the call on to the DB2 CLI driver.
Reasons for application function call intervention by the ODBC driver manager
include:
192 CLI Guide and Reference, Volume 1
v Applications written using ODBC 2.0 functions that have been deprecated in
ODBC 3.0 will have the old functions mapped to new functions.
v ODBC 2.0 function arguments deprecated in ODBC 3.0 will be mapped to
equivalent ODBC 3.0 arguments.
v The Microsoft cursor library will map calls such as SQLExtendedFetch() to
multiple calls to SQLFetch() and other supporting functions to achieve the same
end result.
v ODBC driver manager connection pooling will usually defer SQLDisconnect()
requests (or avoid them altogether if the connection gets reused).
For these and other reasons, application developers might find an ODBC driver
manager trace to be a useful complement to the DB2 CLI driver trace.
For more information on capturing and interpreting ODBC driver manager traces,
refer to the ODBC driver manager documentation. On the Windows platforms,
refer to the Microsoft ODBC 3.0 Software Development Kit and Programmer’s
Reference, also available online at: http://www.msdn.microsoft.com/.
DB2 CLI Driver, DB2 JDBC Type 2 Driver, and DB2 traces:
Internally, the DB2 JDBC Type 2 Driver makes use of the DB2 CLI driver for
database access. For example, the Java getConnection() method is internally
mapped by the DB2 JDBC Type 2 Driver to the DB2 CLI SQLConnect() function. As
a result, Java developers might find a DB2 CLI trace to be a useful complement to
the DB2 JDBC trace.
The DB2 CLI driver makes use of many internal and DB2 specific functions to do
its work. These internal and DB2 specific function calls are logged in the DB2 trace.
Application developers will not find DB2 traces useful, as they are only meant to
assist IBM Service in problem determination and resolution.
DB2 CLI and DB2 JDBC traces and CLI or Java stored procedures:
On all workstation platforms, the DB2 CLI and DB2 JDBC trace facilities can be
used to trace DB2 CLI and DB2 JDBC stored procedures.
Most of the DB2 CLI and DB2 JDBC trace information and instructions given in
earlier sections is generic and applies to both applications and stored procedures
equally. However, unlike applications which are clients of a database server (and
typically execute on a machine separate from the database server), stored
procedures execute at the database server. Therefore, the following additional steps
must be taken when tracing DB2 CLI or DB2 JDBC stored procedures:
v Ensure the trace keyword options are specified in the db2cli.ini file located at
the DB2 server.
v If the TraceRefreshInterval keyword is not set to a positive, non-zero value,
ensure all keywords are configured correctly prior to database startup time (that
is, when the db2start command is issued). Changing trace settings while the
database server is running can cause unpredictable results. For example, if the
TracePathName is changed while the server is running, then the next time a
stored procedure is executed, some trace files might be written to the new path,
while others are written to the original path. To ensure consistency, restart the
server any time a trace keyword other than Trace or TracePIDList is modified.
Related concepts:
v “CLI and JDBC trace files” on page 194
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “db2trc - Trace command” in Command Reference
v “GET CLI CONFIGURATION command” in Command Reference
v “Miscellaneous variables” in Performance Guide
v “SQLSetEnvAttr function (CLI) - Set environment attribute” in Call Level Interface
Guide and Reference, Volume 2
v “UPDATE CLI CONFIGURATION command” in Command Reference
If the TraceFileName keyword was used in the db2cli.ini file to specify a fully
qualified file name, then the DB2 CLI trace log file will be in the location specified.
If a relative file name was specified for the DB2 CLI trace log file name, the
location of that file will depend on what the operating system considers to be the
current path of the application.
Note: If the user executing the application does not have sufficient authority to
write to the trace log file in the specified path, no file will be generated and
no warning or error is given.
Note: If the user executing the application does not have sufficient authority to
write trace files in the specified path, no file will be generated and no
warning or error is given. If the specified trace path does not exist, it will
not be created.
The DB2 CLI and DB2 JDBC trace facilities automatically use the application’s
process ID and thread sequence number to name the trace log files when the
TracePathName and JDBCTracePathName keywords have been set. For example, a
DB2 CLI trace of an application with three threads might generate the following
DB2 CLI trace log files: 100390.0, 100390.1, 100390.2.
Note: If the trace directory contains both old and new trace log files, file date and
time stamp information can be used to locate the most recent trace files.
If no DB2 CLI or DB2 JDBC trace output files appear to have been created:
v Verify that the trace configuration keywords are set correctly in the db2cli.ini
file. Issuing the db2 GET CLI CFG FOR SECTION COMMON command from the
command line processor is a quick way to do this.
v Ensure the application is restarted after updating the db2cli.ini file. Specifically,
the DB2 CLI and DB2 JDBC trace facilities are initialized during application
startup. Once initialized, the DB2 JDBC trace facility cannot be reconfigured. The
DB2 CLI trace facility can be reconfigured at run time but only if the
TraceRefreshInterval keyword was appropriately specified prior to application
startup.
Note: Only the Trace and TracePIDList DB2 CLI keywords can be reconfigured
at run time. Changes made to other DB2 CLI keywords, including
TraceRefreshInterval, have no effect without an application restart.
v If the TraceRefreshInterval keyword was specified prior to application startup,
and if the Trace keyword was initially set to 0, ensure that enough time has
elapsed for the DB2 CLI trace facility to reread the Trace keyword value.
v If either or both the TracePathName and JDBCTracePathName keywords are
used to specify trace directories, ensure those directories exist prior to starting
the application.
v Ensure the application has write access to the specified trace log file or trace
directory.
v Check the DB2CLIINIPATH environment variable. If set, the DB2 CLI and DB2
JDBC trace facilities expect the db2cli.ini file to be at the location specified by
this variable.
v If the application uses ODBC to interface with the DB2 CLI driver, verify that
one of the SQLConnect(), SQLDriverConnect() or SQLBrowseConnect() functions
have been successfully called. No entries will be written to the DB2 CLI trace
log files until a database connection has successfully been made.
DB2 CLI traces always begin with a header that identifies the process ID and
thread ID of the application that generated the trace, the time the trace began, and
product specific information such as the local DB2 build level and DB2 CLI driver
version. For example:
1 [ Process: 1227, Thread: 1024 ]
2 [ Date, Time: 01-27-2002 13:46:07.535211 ]
3 [ Product: QDB2/LINUX 7.1.0 ]
4 [ Level Identifier: 02010105 ]
5 [ CLI Driver Version: 07.01.0000 ]
6 [ Informational Tokens: "DB2 v7.1.0","n000510","" ]
Note: Trace examples used in this section have line numbers added to the left
hand side of the trace. These line numbers have been added to aid the
discussion and will not appear in an actual DB2 CLI trace.
9 SQLAllocEnv( phEnv=0:1 )
10 <––– SQL_SUCCESS Time elapsed - +7.500000E-004 seconds
13 SQLAllocConnect( phDbc=0:1 )
14 <––– SQL_SUCCESS Time elapsed - +5.280000E-004 seconds
17 SQLSetConnectOption( )
18 <––– SQL_SUCCESS Time elapsed - +3.150000E-004 seconds
22 SQLConnect( )
23 <––– SQL_SUCCESS Time elapsed - +5.209880E-001 seconds
24 ( DSN=""SAMPLE"" )
25 ( UID=" " )
26 ( PWD="*" )
In the above trace example, notice that there are two entries for each DB2 CLI
function call (for example, lines 19-21 and 22-26 for the SQLConnect() function call).
This is always the case in DB2 CLI traces. The first entry shows the input
parameter values passed to the function call while the second entry shows the
function output parameter values and return code returned to the application.
The above trace example shows that the SQLAllocEnv() function successfully
allocated an environment handle ( phEnv=0:1 ) at line 9. That handle was then
passed to the SQLAllocConnect() function which successfully allocated a database
connection handle ( phDbc=0:1 ) as of line 13. Next, the SQLSetConnectOption()
function was used to set the phDbc=0:1 connection’s SQL_ATTR_AUTOCOMMIT
attribute to SQL_AUTOCOMMIT_OFF ( vParam=0 ) at line 15. Finally,
SQLConnect() was called to connect to the target database ( SAMPLE ) at line 19.
Included in the input trace entry of the SQLConnect() function on line 21 is the
build and FixPak level of the target database server. Other information that might
also appear in this trace entry includes input connection string keywords and the
code pages of the client and server. For example, suppose the following
information also appeared in the SQLConnect() trace entry:
( Application Codepage=819, Database Codepage=819,
Char Send/Recv Codepage=819, Graphic Send/Recv Codepage=819,
Application Char Codepage=819, Application Graphic Codepage=819 )
This would mean the application and the database server were using the same
code page ( 819 ).
Following the environment and connection related trace entries are the statement
related trace entries. For example:
27 SQLAllocStmt( hDbc=0:1, phStmt=&bffff684 )
28 –––> Time elapsed - +1.868000E-003 seconds
29 SQLAllocStmt( phStmt=1:1 )
30 <––– SQL_SUCCESS Time elapsed - +6.890000E-004 seconds
34 SQLExecDirect( )
35 <––– SQL_SUCCESS Time elapsed - +2.387800E-002 seconds
In the above trace example, the database connection handle ( phDbc=0:1 ) was
used to allocate a statement handle ( phStmt=1:1 ) at line 29. An unprepared SQL
statement was then executed on that statement handle at line 31. If the
TraceComm=1 keyword had been set in the db2cli.ini file, the SQLExecDirect()
function call trace entries would have shown additional client-server
communication information as follows:
SQLExecDirect( hStmt=1:1, pszSqlStr="CREATE TABLE GREETING (MSG
VARCHAR(10))", cbSqlStr=-3 )
–––> Time elapsed - +2.876000E-003 seconds
( StmtOut="CREATE TABLE GREETING (MSG VARCHAR(10))" )
SQLExecDirect( )
<––– SQL_SUCCESS Time elapsed - +2.384900E-002 seconds
Notice the additional sqlccsend() and sqlccrecv() function call information in this
trace entry. The sqlccsend() call information reveals how much data was sent from
the client to the server, how long the transmission took, and the success of that
transmission ( 0 = SQL_SUCCESS ). The sqlccrecv() call information then reveals
how long the client waited for a response from the server and the amount of data
included in the response.
Often, multiple statement handles will appear in the DB2 CLI trace. By paying
close attention to the statement handle identifier, one can easily follow the
execution path of a statement handle independent of all other statement handles
appearing in the trace.
Statement execution paths appearing in the DB2 CLI trace are usually more
complicated than the example shown above. For example:
38 SQLAllocStmt( phStmt=1:2 )
39 <––– SQL_SUCCESS Time elapsed - +6.820000E-004 seconds
43 SQLPrepare( )
44 <––– SQL_SUCCESS Time elapsed - +9.150000E-004 seconds
47 SQLBindParameter( )
48 <––– SQL_SUCCESS Time elapsed - +6.780000E-004 seconds
49 SQLExecute( hStmt=1:2 )
50 –––> Time elapsed - +1.337000E-003 seconds
51 ( iPar=1, fCType=SQL_C_CHAR, rgbValue="Hello World!!!", pcbValue=14,
piIndicatorPtr=14 )
52 SQLExecute( )
53 <––– SQL_ERROR Time elapsed - +5.951000E-003 seconds
In the above trace example, the database connection handle ( phDbc=0:1 ) was
used to allocate a second statement handle ( phStmt=1:2 ) at line 38. An SQL
statement with one parameter marker was then prepared on that statement handle
at line 40. Next, an input parameter ( iPar=1 ) of the appropriate SQL type (
SQL_CHAR ) was bound to the parameter marker at line 45. Finally, the statement
was executed at line 49. Notice that both the contents and length of the input
parameter ( rgbValue=″Hello World!!!″, pcbValue=14 ) are displayed in the trace on
line 51.
The SQLExecute() function fails at line 52. If the application calls a diagnostic DB2
CLI function like SQLError() to diagnose the cause of the failure, then that cause
will appear in the trace. For example:
54 SQLError( hEnv=0:1, hDbc=0:1, hStmt=1:2, pszSqlState=&bffff680,
pfNativeError=&bfffee78, pszErrorMsg=&bffff280,
cbErrorMsgMax=1024, pcbErrorMsg=&bfffee76 )
55 –––> Time elapsed - +1.512000E-003 seconds
The error message returned at line 56 contains the DB2 native error code that was
generated ( SQL0302N ), the sqlstate that corresponds to that code (
SQLSTATE=22001 ) and a brief description of the error. In this example, the source
of the error is evident: on line 49, the application is trying to insert a string with 14
characters into a column defined as VARCHAR(10) on line 31.
If the application does not respond to a DB2 CLI function warning or error return
code by calling a diagnostic function like SQLError(), the warning or error message
SQLDisconnect( )
<––– SQL_SUCCESS Time elapsed - +1.734130E-001 seconds
The final part of a DB2 CLI trace should show the application releasing the
database connection and environment handles that it allocated earlier in the trace.
For example:
58 SQLTransact( hEnv=0:1, hDbc=0:1, fType=SQL_ROLLBACK )
59 –––> Time elapsed - +6.085000E-003 seconds
60 ( ROLLBACK=0 )
61 SQLTransact( )
<––– SQL_SUCCESS Time elapsed - +2.220750E-001 seconds
62 SQLDisconnect( hDbc=0:1 )
63 –––> Time elapsed - +1.511000E-003 seconds
64 SQLDisconnect( )
65 <––– SQL_SUCCESS Time elapsed - +1.531340E-001 seconds
66 SQLFreeConnect( hDbc=0:1 )
67 –––> Time elapsed - +2.389000E-003 seconds
68 SQLFreeConnect( )
69 <––– SQL_SUCCESS Time elapsed - +3.140000E-004 seconds
70 SQLFreeEnv( hEnv=0:1 )
71 –––> Time elapsed - +1.129000E-003 seconds
72 SQLFreeEnv( )
73 <––– SQL_SUCCESS Time elapsed - +2.870000E-004 seconds
DB2 JDBC traces always begin with a header that lists important system
information such as key environment variable settings, the SDK for Java or JRE
level, the DB2 JDBC driver level, and the DB2 build level. For example:
1 ========================================================
2 | Trace beginning on 2002-1-28 7:21:0.19
3 ========================================================
4 System Properties:
5 ------------------
6 user.language = en
7 java.home = c:\Program Files\SQLLIB\java\jdk\bin\..
8 java.vendor.url.bug =
9 awt.toolkit = sun.awt.windows.WToolkit
Note: Trace examples used in this section have line numbers added to the left
hand side of the trace. These line numbers have been added to aid the
discussion and will not appear in an actual DB2 JDBC trace.
Immediately following the trace header, one usually finds a number of trace entries
related to initialization of the JDBC environment and database connection
establishment. For example:
31 jdbc.app.DB2Driver –> DB2Driver() (2002-1-28 7:21:0.29)
32 | Loaded db2jdbc from java.library.path
33 jdbc.app.DB2Driver <– DB2Driver() [Time Elapsed = 0.01]
34 DB2Driver - connect(jdbc:db2:sample)
In the above trace example, a request to load the DB2 JDBC driver was made on
line 31. This request returned successfully as reported on line 33.
The DB2 JDBC trace facility uses specific Java classes to capture the trace
information. In the above trace example, one of those trace classes,
DB2ConnectionTrace, has generated two trace entries numbered 35-37 and 38-41.
Line 35 shows the connect() method being invoked and the input parameters to
that method call. Line 37 shows that the connect() method call has returned
successfully while line 36 shows the output parameter of that call ( Connection
handle = 1 ).
Following the connection related entries, one usually finds statement related entries
in the JDBC trace. For example:
On line 42 and 43, the DB2ConnectionTrace class reported that the JDBC
createStatement() method had been called with connection handle 1. Within that
method, the internal method DB2Statement() was called as reported by another
DB2 JDBC trace facility class, DB2StatementTrace. Notice that this internal method
call appears ’nested’ in the trace entry. Lines 47-49 show that the methods returned
successfully and that statement handle 1:1 was allocated.
On line 50, an SQL query method call is made on statement 1:1, but the call
generates an exception at line 52. The error message is reported on line 53 and
contains the DB2 native error code that was generated ( SQL0401N ), the sqlstate
that corresponds to that code ( SQLSTATE=42818 ) and a brief description of the
error. In this example, the error results because the EMPLOYEE.EMPNO column is
defined as CHAR(6) and not an integer value as assumed in the query.
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
Related reference:
v “Miscellaneous variables” in Performance Guide
v “Trace CLI/ODBC configuration keyword” on page 375
v “TraceComm CLI/ODBC configuration keyword” on page 376
v “TraceFileName CLI/ODBC configuration keyword” on page 378
v “TracePathName CLI/ODBC configuration keyword” on page 381
v “TracePIDList CLI/ODBC configuration keyword” on page 382
v “TraceRefreshInterval CLI/ODBC configuration keyword” on page 383
The db2cli.lst file contains the names of the required bind files for DB2 CLI to
connect to DB2 servers on Linux, UNIX, and Windows (db2clipk.bnd and
db2clist.bnd).
For host and iSeries servers use one of ddcsvm.lst, ddcsmvs.lst, ddcsvse.lst, or
ddcs400.lst bind list files.
Warnings that are generated when binding DB2 CLI packages (such as
db2clist.bnd or db2cli.lst) to workstation or host servers are expected. This is
because DB2 uses generic bind files, but the bind file packages for DB2 CLI
packages contain sections that apply to specific platforms. Therefore, DB2 might
generate warnings during the binding against a server, when it encounters a
platform-specific section that does not apply to the server.
The following is an example of a warning that can be ignored which might occur
when binding a DB2 CLI package (such as db2clist.bnd or db2cli.lst) to a
workstation server:
LINE MESSAGES FOR db2clist.bnd
------ --------------------------------------------------------------------
235 SQL0440N No authorized routine named "POSSTR" of type
"FUNCTION" having compatible arguments was found.
SQLSTATE=42884
Previous versions of DB2 servers do not need all of the bind files and will therefore return
errors at bind time. Use the bind option SQLERROR(CONTINUE) so that the same
package can be bound on all platforms and errors will be ignored for any statements not
supported there.
The db2schema.bnd bind file is automatically bound when the database is created
or migrated on DB2 servers on Linux, UNIX, and Windows, and exists only on
these types of servers. This bind file is located at the server and should be bound
manually (from the server) if a fix pack was applied on the server, if the package
If the package is missing, it must be rebound locally on the server. Do not bind
this package against remote servers (for example, against a host database). The
bind file is found in the sqllib/bnd directory of the instance home directory, and is
rebound with the following command:
bind db2schema.bnd blocking all grant public
Related concepts:
v “Packages” in SQL Reference, Volume 1
Related tasks:
v “Setting up the CLI environment” on page 209
Related reference:
v “BIND command” in Command Reference
To create DB2 CLI packages with bind options that are not supported by default,
specify the COLLECTION bind option with a collection ID that is different from
the default collection ID, NULLID. Any bind options specified are then accepted.
For example, to create DB2 CLI packages with the KEEPDYNAMIC YES bind
option, which is not supported by default, issue the following command:
db2 bind @db2cli.lst collection newcolid keepdynamic yes
In order for CLI/ODBC applications to access the DB2 CLI packages created in the
new collection, set the CurrentPackageSet CLI/ODBC keyword in the db2cli.ini
initialization file to the new collection ID.
To overwrite DB2 CLI packages that already exist under a particular collection ID,
perform either of the following actions:
v Drop the existing CLI package before issuing the bind command for this
collection ID.
v Specify the ACTION REPLACE bind option when issuing the bind command.
Related reference:
Before you can run a CLI application, you must set up the CLI environment. This
chapter describes how to set up the CLI or ODBC environment on the UNIX and
Windows platforms.
Prerequisites:
Before you set up your CLI environment, ensure you have set up the application
development environment.
Procedure:
Related concepts:
v “Initialization and termination in CLI overview” on page 17
Related tasks:
Related reference:
v “BIND command” in Command Reference
v “CATALOG DATABASE command” in Command Reference
Prerequisites:
Before setting up the UNIX ODBC environment, ensure you have set up the CLI
environment.
Procedure:
For ODBC applications on UNIX that need to access a DB2 database, follow the
steps described below.
1. Ensure that an ODBC driver manager is installed and that each user that will
use ODBC has access to it. DB2 does not install an ODBC driver manager, so
you must use the ODBC driver manager that was supplied with your ODBC
client application or ODBC SDK in order to access DB2 data using that
application.
2. Set up .odbc.ini, the end-user’s data source configuration. Each user ID has a
separate copy of this file in their home directory. Note that the file starts with a
dot. Although necessary files are usually updated automatically by the tools on
most platforms, users of ODBC on UNIX platforms will have to edit them
manually.
Using an ASCII editor, update the file to reflect the appropriate data source
configuration information. To register a DB2 database as an ODBC data source
there must be one stanza (section) for each DB2 database.
The .odbc.ini file must contain the following lines (examples refer to
configuration of the SAMPLE database data source):
v in the [ODBC Data Source] stanza:
SAMPLE=IBM DB2 ODBC DRIVER
which indicates that there is a data source called SAMPLE that uses the IBM
DB2 ODBC DRIVER;
v in the [SAMPLE] stanza:
on AIX, for example,
[SAMPLE]
Driver=/u/thisuser/sqllib/lib/libdb2.a
Description=Sample DB2 ODBC Database
on the Solaris operating system, for example,
[SAMPLE]
Driver=/u/thisuser/sqllib/lib/libdb2.so
Description=Sample DB2 ODBC Database
Note: The file extension of the DB2 driver to specify depends on the
operating system. The extensions are as follows:
– .a - AIX
– .so - Linux, Solaris, HP-IPF
– .sl - HP-PA
3. Ensure that the application execution environment has reference to the ODBC
driver manager by including libodbc.a (for AIX) or libodbc.so (for UNIX) in
the LIBPATH (for AIX) or LD_LIBRARY_PATH (for UNIX) environment
variables.
4. Enable a system-wide .odbc.ini file to be used by setting the ODBCINI
environment variable to the fully qualified pathname of the .ini file. Some
ODBC driver managers support this feature which allows for centralized
control. The following examples show how to set ODBCINI:
in the C shell,
setenv ODBCINI /opt/odbc/system_odbc.ini
in the Bourne or Korn shell,
ODBCINI=/opt/odbc/system_odbc.ini;export ODBCINI
5. Once the .odbc.ini file is set up, you can run your ODBC application and
access DB2 databases. Refer to the documentation that comes with your ODBC
application for additional help and information.
Related concepts:
v “Comparison of DB2 CLI and Microsoft ODBC” on page 9
v “Initialization and termination in CLI overview” on page 17
Related tasks:
v “Building CLI applications on UNIX” on page 219
v “Building CLI routines on UNIX” on page 222
v “Initializing CLI applications” on page 18
v “Setting up the CLI environment” on page 209
Support statement:
Procedure:
To set up the unixODBC Driver Manager for use with DB2 CLI and ODBC
applications:
1. Download the latest unixODBC source code from: http://www.unixodbc.com.
2. Untar the source files:
gzip -d unixODBC-2.2.11.tar.gz
tar xf unixODBC-2.2.11.tar
3. For AIX only: configure the C compiler to be thread-enabled:
export CC=xlc_r
export CCC=xlC_r
4. To compile a 64-bit version of the driver manager using the xlc_r compilers, set
the environment variables OBJECT_MODE and CFLAGS:
export OBJECT_MODE=64
export CFLAGS=-q64 -DBUILD_REAL_64_BIT_MODE
5. Install the driver manager in either your home directory or the default
/usr/local prefix:
v (Home directory) Issue the following command in the directory where you
untarred the source files:
./configure --prefix=$HOME -DBUILD_REAL_64_BIT_MODE --enable-gui=no
--enable-drivers=no
v (/usr/local as root) Issue the following command:
./configure --enable-gui=no --enable-drivers=no
6. Optional: Examine all configuration options by issuing the following command:
./configure --help
7. Build and install the driver manager:
make
make install
Important: Provide absolute paths when specifying the paths of the user and
system INI files. Do not use relative paths or environment
variables.
Related tasks:
v “Setting up the UNIX ODBC environment” on page 210
Related reference:
v “Sample build scripts and configurations for the unixODBC Driver Manager” on
page 213
Support statement:
The following are sample build scripts for setting up your environment to use the
unixODBC Driver Manager.
AIX:
#! /bin/sh
cd unixODBC-2.2.11
UNIX (non-AIX):
#! /bin/sh
cd unixODBC-2.2.11
The following are sample user and system INI files for using the unixODBC Driver
Manager.
[SAMPLE]
DESCRIPTION = Connection to DB2
DRIVER = DB2
[DB2]
Description = DB2 Driver
Driver = /u/db2inst1/sqllib/lib/db2.o
[ODBC]
Trace = yes
Tracefile = /u/user/trc.log
This system INI file has the ODBC trace enabled, with the trace log file set to
trc.log.
Note: If you encounter problems when closing the driver manager (such as during
SQLDisconnect()), set the value dontdlclose=1 in the odbcinst.ini file, as
shown in the example above.
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
Related tasks:
v “Setting up the unixODBC Driver Manager” on page 212
v “Setting up the UNIX ODBC environment” on page 210
Prerequisites:
Before setting up the Windows CLI environment, ensure that the CLI environment
has been set up.
Restrictions:
When using the Configuration Assistant on Windows 64-bit platforms, ODBC Data
Sources can be configured only for 64-bit applications. ODBC Data Sources for
32-bit applications need to be configured using the Microsoft 32-bit ODBC Data
Source Administrator (32-bit odbcad32.exe) that is included with the Windows
64-bit operating system.
Procedure:
Before DB2 CLI and ODBC applications can successfully access a DB2 database
from a Windows client, perform the following steps on the client system:
1. Verify that the Microsoft ODBC Driver Manager and the DB2 CLI/ODBC
driver are installed. On Windows operating systems they are both installed
with DB2 unless the ODBC component is manually unselected during the
install. DB2 will not overwrite a newer version of the Microsoft ODBC Driver
Manager if one is found. To verify that they both exist on the machine:
a. Start the Microsoft ODBC Data Sources icon in the Control Panel, or run the
odbcad32.exe command from the command line.
b. Click on the ″Drivers″ tab.
Note: The latest version of the Microsoft ODBC Driver Manager is included as
part of the Microsoft Data Access Components (MDAC) and is available
for download from http://www.microsoft.com/data/.
2. Register the DB2 database with the ODBC driver manager as a data source. On
Windows operating systems you can make the data source available to all users
of the system (a system data source), or only the current user (a user data
source). Use either of these methods to add the data source:
v Using the Configuration Assistant:
a. Select the DB2 database alias that you want to add as a data source.
b. Click on the ″Properties″ push button. The Database Properties window
opens.
c. Select the ″Register this database for ODBC″ check box.
d. Use the radio buttons to add the data source as either a user, system, or
file data source.
v Using the Microsoft ODBC Administration tool, which you can access from
the icon in the Control Panel or by running odbcad32.exe from the command
line:
a. The list of user data sources appears by default. If you want to add a
system data source click on the ″System DSN″ button, or the ″System
DSN″ tab (depending on the platform).
b. Click on the ″Add″ push button.
c. Double-click on the IBM DB2 ODBC DRIVER - <DB2 Copy name> in the
list. <DB2 Copy name> is the DB2 copy name that you want to use.
d. Select the DB2 database to add and click on OK.
v Use the CATALOG command to register the DB2 database with the ODBC
driver manager as a data source:
CATALOG [ user | system ] ODBC DATA SOURCE
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Initialization and termination in CLI overview” on page 17
v “Multiple DB2 copies on the same computer (Windows)” in Administration Guide:
Implementation
Related tasks:
v “Building CLI applications on Windows” on page 228
v “Building CLI routines on Windows” on page 231
v “Initializing CLI applications” on page 18
v “Setting up the CLI environment” on page 209
Prerequisites:
Restrictions:
See Multiple DB2 copies on the same computer (Windows) and Client connectivity
using multiple DB2 copies (Windows)
Procedure:
The following are different methods that allow DB2 CLI applications to
successfully access a different DB2 copy on the Windows platform.
v Using the DB2 command window from the Start → Programs → IBM DB2 → <DB2
Copy Name> → Command Line Tools → DB2 Command Window: the command
window is already set up with the correct environment variables for the
particular DB2 copy chosen.
v Using db2envar.bat from a command window:
1. Open a command window.
2. Run the db2envar.bat file using the fully qualified path for the DB2 copy
that you want the application to use:
<DB2 Copy install dir>\bin\db2envar.bat
3. Run the DB2 CLI application from the same command window.
This will set up all the environment variables for the selected DB2 copy in the
command window where the db2envar.bat was run. Once the command
window has been closed and a new one opened, the DB2 CLI application will
run against the default DB2 Copy unless the db2envar.bat for another DB2 copy
is run again.
v Using the db2SelectDB2Copy API: For applications that are dynamically linked,
you can call this API prior to loading any DB2 DLLs within your application
process. This API sets up the required environment for your application to use
Related concepts:
v “Multiple DB2 copies on the same computer (Windows)” in Administration Guide:
Implementation
Related tasks:
v “Setting up the Windows CLI environment” on page 215
v “Client connectivity using multiple DB2 copies (Windows)” in Administration
Guide: Implementation
v “Setting environment variables on Windows” in Administration Guide:
Implementation
v “Setting the current instance environment variables” in Administration Guide:
Implementation
Related reference:
v “db2SelectDB2Copy API - Select the DB2 copy to be used by your application”
in Administrative API Reference
v “Multiple DB2 copies roadmap” in Administration Guide: Implementation
UNIX
The following sections describe how to build CLI applications and routines on
supported UNIX operating systems. They also show sample build scripts for each
operating system and descriptions of the compile and link options used within the
build scripts.
The script file bldapp contains the commands to build a DB2 CLI application. It
takes up to four parameters, represented inside the script file by the variables $1,
$2, $3, and $4.
The parameter, $1, specifies the name of your source file. This is the only required
parameter, and the only one needed for CLI applications that do not contain
embedded SQL. Building embedded SQL programs requires a connection to the
database so three optional parameters are also provided: the second parameter, $2,
specifies the name of the database to which you want to connect; the third
parameter, $3, specifies the user ID for the database, and $4 specifies the password.
If the program contains embedded SQL, indicated by the .sqc extension, then the
embprep script is called to precompile the program, producing a program file with
a .c extension.
Procedure:
The following examples show you how to build and run CLI applications.
To build the sample program tbinfo from the source file tbinfo.c, enter:
bldapp tbinfo
There are three ways to build the embedded SQL application, dbusemx, from the
source file dbusemx.sqc:
1. If connecting to the sample database on the same instance, enter:
bldapp dbusemx
2. If connecting to another database on the same instance, also enter the database
name:
bldapp dbusemx database
3. If connecting to a database on another instance, also enter the user ID and
password of the database instance:
bldapp dbusemx database userid password
Related tasks:
v “Building CLI routines on UNIX” on page 222
v “Configuring the database application development environment” in Getting
Started with Database Application Development
v “Setting up the UNIX application development environment” in Getting Started
with Database Application Development
Related samples:
v “bldapp -- Builds AIX CLI applications”
v “dbusemx.sqc -- How to execute embedded SQL statements in CLI”
v “tbinfo.c -- How to get information about tables from the system catalog tables”
The build file, bldmc, contains the commands to build a DB2 multi-connection
program, requiring two databases. The compile and link options are the same as
those used in bldapp.
Note: The makefile hardcodes default values of ″sample″ and ″sample2″ for the
database names ($2 and $3, respectively) so if you are using the makefile,
and accept these defaults, you only have to specify the program name (the
$1 parameter). If you are using the bldmc script, you must specify all three
parameters.
Optional parameters are not required for a local connection, but are required for
connecting to a server from a remote client. These are: $4 and $5 to specify the
user ID and password, respectively, for the first database; and $6 and $7 to specify
the user ID and password, respectively, for the second database.
Procedure:
For the multi-connection sample program, dbmconx, you require two databases. If
the sample database is not yet created, you can create it by entering db2sampl on
the command line. The second database, here called sample2, can be created with
one of the following commands:
Multi-connection also requires that the TCP/IP listener is running. To ensure it is,
do the following:
1. Set the environment variable DB2COMM to TCP/IP as follows:
db2set DB2COMM=TCPIP
2. Update the database manager configuration file with the TCP/IP service name
as specified in the services file:
db2 update dbm cfg using SVCENAME <TCP/IP service name>
Each instance has a TCP/IP service name listed in the services file. Ask your
system administrator if you cannot locate it or do not have the file permission
to read the services file. On UNIX and Linux systems, the services file is
located in: /etc/services
3. Stop and restart the database manager in order for these changes to take effect:
db2stop
db2start
Related concepts:
v “Multisite updates (two phase commit) in CLI applications” on page 137
Related reference:
v “svcename - TCP/IP service name configuration parameter” in Performance Guide
Related samples:
v “bldmc -- Builds AIX CLI multi-connection applications”
v “bldmc -- Builds HP-UX CLI multi-connection applications”
v “bldmc -- Builds Linux CLI multi-connection applications”
v “bldmc -- Builds Solaris CLI multi-connection applications”
v “dbmconx.c -- How to use multiple databases with embedded SQL.”
v “dbmconx1.h -- Functions used in dbmconx.c”
v “dbmconx1.sqc -- This file contains functions used in dbmconx.c”
v “dbmconx2.h -- Functions used in dbmconx.c”
v “dbmconx2.sqc -- This file contains functions used in dbmconx.c”
The script file bldrtn contains the commands to build DB2 CLI routines (stored
procedures and user-defined functions). bldrtn creates a shared library on the
server. It takes a parameter for the source file name, represented inside the script
file by the variable $1.
To build the sample program spserver from the source file spserver.c:
1. Enter the build script name and program name:
bldrtn spserver
The script file copies the shared library to the sqllib/function directory.
2. Next, catalog the routines by running the spcat script on the server:
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 call the
spdrop.db2 and spcreate.db2 scripts individually.
3. Then, unless this is the first time the shared library was built, stop and restart
the database to allow the new version of the shared library to be recognized. If
necessary, set the file mode for the shared library so the DB2 instance can
access it.
Once you build the shared library, spserver, you can build the CLI client
application, spclient, that calls the routines within the shared library.
The client application can be built like any other CLI client application by using
the script file, bldapp.
To access the shared library, run the sample client application by entering:
where
database
Is the name of the database to which you want to connect. The name could
be sample, or its alias, or another database name.
userid Is a valid user ID.
password
Is a valid password.
The client application accesses the shared library, spserver, and executes the
routines on the server database. The output is returned to the client application.
Related tasks:
v “Setting up the UNIX application development environment” in Getting Started
with Database Application Development
v “Building CLI applications on UNIX” on page 219
Related samples:
v “bldrtn -- Builds AIX CLI routines (stored procedures and UDFs)”
v “spclient.c -- Call various stored procedures”
v “spserver.c -- Definition of various types of stored procedures”
v “spcat -- To catalog stored procedures on UNIX (C)”
v “spcreate.db2 -- How to catalog the stored procedures contained in spserver.sqc
(C)”
AIX
Build script for AIX applications
The script for building CLI applications on AIX is called bldapp and is located in
the sqllib/samples/cli directory. The compile and link options recommended by
DB2 for building CLI applications with the AIX IBM C compiler, are demonstrated
in the sqllib/samples/cli/bldapp build script also.
Procedure:
To use the configuration file to build the DB2 CLI sample program tbinfo from the
source file tbinfo.c, do the following:
1. Set the CLI environment variable:
export CLI=tbinfo
2. If you have a cli.ics file in your working directory, produced by building a
different program with the cli.icc file, delete the cli.ics file with this
command:
rm cli.ics
An existing cli.ics file produced for the same program you are going to build
again does not have to be deleted.
3. Compile the sample program by entering:
vacbld cli.icc
The result is an executable file, tbinfo. You can run the program by entering the
executable name:
tbinfo
You use the configuration file after the program is precompiled with the embprep
file. The embprep file precompiles the source file and binds the program to the
database. You use the cli.icc configuration file to compile the precompiled file.
There are three ways to precompile the embedded SQL application, dbusemx, from
the source file dbusemx.sqc:
1. If connecting to the sample database on the same instance, enter:
embprep dbusemx
2. If connecting to another database on the same instance, also enter the database
name:
embprep dbusemx database
After it is precompiled, the C file can be compiled with the cli.icc file as follows:
1. Set the CLI environment variable to the program name by entering:
export CLI=dbusemx
2. If you have a cli.ics file in your working directory, produced by building a
different program with the cli.icc or cliapi.icc file, delete the cli.ics file
with this command:
rm cli.ics
An existing cli.ics file produced for the same program you are going to build
again does not have to be deleted.
3. Compile the sample program by entering:
vacbld cli.icc
Related tasks:
v “Building embedded SQL and DB2 API applications in C or C++ with
configuration files (AIX)” in Developing Embedded SQL Applications
v “Building embedded SQL stored procedures in C or C++ with configuration
files” in Developing Embedded SQL Applications
v “Building user-defined functions in C or C++ with configuration files (AIX)” in
Developing Embedded SQL Applications
v “Building CLI stored procedures with configuration files” on page 226
v “Building embedded SQL applications written in VisualAge C++ with
configuration files” in Developing Embedded SQL Applications
Related samples:
v “dbusemx.sqc -- How to execute embedded SQL statements in CLI”
v “tbinfo.c -- How to get information about tables from the system catalog tables”
Building CLI stored procedures with configuration files: The configuration file,
clis.icc, in sqllib/samples/cli, allows you to build DB2 CLI stored procedures.
Procedure:
To use the configuration file to build the DB2 CLI stored procedure spserver from
the source file spserver.c, do the following:
1. Set the CLIS environment variable to the program name by entering:
export CLIS=spserver
2. If you have a clis.ics file in your working directory, produced by building a
different program with the clis.icc file, delete the clis.ics file with this
command:
rm clis.ics
An existing clis.ics file produced for the same program you are going to
build again does not have to be deleted.
3. Compile the sample program by entering:
vacbld clis.icc
Next, catalog the stored procedures by running the spcreate.db2 script on the
server. First, connect to the database with the user ID and password of the instance
where the database is located:
db2 connect to sample userid password
If the stored procedures were previously cataloged, you can drop them with this
command:
db2 -td@ -vf spdrop.db2
Then, stop and restart the database to allow the new shared library to be
recognized. If necessary, set the file mode for the shared library so the DB2
instance can access it.
Once you build the stored procedure spserver, you can build the CLI client
application spclient that calls the stored procedure. You can build spclient by
using the configuration file, cli.icc.
To call the stored procedure, run the sample client application by entering:
where
The client application accesses the shared library, spserver, and executes a number
of stored procedure functions on the server database. The output is returned to the
client application.
Related tasks:
v “Building CLI routines on UNIX” on page 222
Related samples:
v “spclient.c -- Call various stored procedures”
v “spcreate.db2 -- How to catalog the stored procedures contained in spserver.sqc
(C)”
v “spdrop.db2 -- How to uncatalog the stored procedures contained in spserver.sqc
(C)”
HP-UX
Build script for HP-UX applications
The script for building CLI applications on HP-UX is called bldapp and is located
in the sqllib/samples/cli directory. The compile and link options recommended
by DB2 for building CLI applications with the HP-UX C compiler, are
demonstrated in the sqllib/samples/cli/bldapp build script also.
Linux
Build script for Linux applications
The script for building CLI applications on Linux is called bldapp and is located in
the sqllib/samples/cli directory. The compile and link options recommended by
DB2 for building CLI applications with the GNU/Linux gcc compiler, are
demonstrated in the sqllib/samples/cli/bldapp build script also.
Windows
The following sections describe how to build CLI applications and routines on
supported Windows operating systems. They also provide sample batch files for
building DB2 programs as well as descriptions of the compile and link options
used in the batch files.
The batch file bldapp.bat contains the commands to build a DB2 CLI program. It
takes up to four parameters, represented inside the batch file by the variables %1,
%2, %3, and %4.
The parameter, %1, specifies the name of your source file. This is the only required
parameter, and the only one needed for CLI programs that do not contain
embedded SQL. Building embedded SQL programs requires a connection to the
database so three optional parameters are also provided: the second parameter, %2,
specifies the name of the database to which you want to connect; the third
parameter, %3, specifies the user ID for the database, and %4 specifies the password.
If the program contains embedded SQL, indicated by the .sqc or .sqx extension,
then the embprep.bat batch file is called to precompile the program, producing a
program file with either a .c or a .cxx extension, respectively.
Procedure:
The following examples show you how to build and run CLI applications.
To build the sample program tbinfo from the source file tbinfo.c, enter:
bldapp tbinfo
The result is an executable file tbinfo. You can run the executable file by entering
the executable name:
tbinfo
There are three ways to build the embedded SQL application, dbusemx, from the
source file dbusemx.sqc:
1. If connecting to the sample database on the same instance, enter:
bldapp dbusemx
2. If connecting to another database on the same instance, also enter the database
name:
bldapp dbusemx database
3. If connecting to a database on another instance, also enter the user ID and
password of the database instance:
bldapp dbusemx database userid password
Related tasks:
v “Building CLI routines on Windows” on page 231
v “Setting up the CLI environment” on page 209
v “Setting up the Windows CLI environment” on page 215
Related samples:
v “bldapp.bat -- Builds C applications on Windows”
v “embprep.bat -- Prep and binds a C/C++ or Micro Focus COBOL embedded
SQL program on Windows”
v “dbusemx.sqc -- How to execute embedded SQL statements in CLI”
v “tbinfo.c -- How to get information about tables from the system catalog tables”
The batch file, bldmc.bat, contains the commands to build a DB2 multi-connection
program requiring two databases. The compile and link options are the same as
those used in bldapp.bat.
The first parameter, %1, specifies the name of your source file. The second
parameter, %2, specifies the name of the first database to which you want to
Note: The makefile hardcodes default values of ″sample″ and ″sample2″ for the
database names (%2 and %3, respectively) so if you are using the makefile,
and accept these defaults, you only have to specify the program name (the
%1 parameter). If you are using the bldmc.bat file, you must specify all three
parameters.
Optional parameters are not required for a local connection, but are required for
connecting to a server from a remote client. These are: %4 and %5 to specify the
user ID and password, respectively, for the first database; and %6 and %7 to specify
the user ID and password, respectively, for the second database.
Procedure:
For the multi-connection sample program, dbmconx, you require two databases. If
the sample database is not yet created, you can create it by entering db2sampl on
the command line. The second database, here called sample2, can be created with
one of the following commands:
Multi-connection also requires that the TCP/IP listener is running. To ensure it is,
do the following:
1. Set the environment variable DB2COMM to TCP/IP as follows:
db2set DB2COMM=TCPIP
2. Update the database manager configuration file with the TCP/IP service name
as specified in the services file:
db2 update dbm cfg using SVCENAME <TCP/IP service name>
Each instance has a TCP/IP service name listed in the services file. Ask your
system administrator if you cannot locate it or do not have the file permission
to read the services file.
3. Stop and restart the database manager in order for these changes to take effect:
db2stop
db2start
Related concepts:
v “Multisite updates (two phase commit) in CLI applications” on page 137
Related reference:
v “svcename - TCP/IP service name configuration parameter” in Performance Guide
Related samples:
v “bldmc.bat -- Builds Windows CLI multi-connection applications”
v “dbmconx.c -- How to use multiple databases with embedded SQL.”
v “dbmconx1.h -- Functions used in dbmconx.c”
v “dbmconx1.sqc -- This file contains functions used in dbmconx.c”
v “dbmconx2.h -- Functions used in dbmconx.c”
v “dbmconx2.sqc -- This file contains functions used in dbmconx.c”
The batch file bldrtn.bat contains the commands to build CLI routines (stored
procedures and user-defined functions). bldrtn.bat creates a DLL on the server. It
takes one parameter, represented inside the batch file by the variable %1, which
specifies the name of your source file. The batch file uses the source file name for
the DLL name.
Procedure:
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 call the
spdrop.db2 and spcreate.db2 scripts individually.
3. Then, unless this is the first time the shared library was built, stop and restart
the database to allow the new version of the shared library to be recognized. If
necessary, set the file mode for the shared library so the DB2 instance can
access it.
Once you build the DLL spserver, you can build the CLI client application
spclient that calls the routines within it.
where
database
Is the name of the database to which you want to connect. The name could
be sample, or its alias, or another database name.
userid Is a valid user ID.
password
Is a valid password.
The client application accesses the DLL, spserver, which executes the routines on
the server database. The output is returned to the client application.
Related tasks:
v “Building CLI applications on Windows” on page 228
v “Setting up the CLI environment” on page 209
v “Setting up the Windows CLI environment” on page 215
Related samples:
v “bldapp.bat -- Builds C applications on Windows”
v “bldrtn.bat -- Builds C routines (stored procedures and UDFs) on Windows”
v “spcat -- To catalog stored procedures on UNIX (C)”
v “spcreate.db2 -- How to catalog the stored procedures contained in spserver.sqc
(C)”
v “spdrop.db2 -- How to uncatalog the stored procedures contained in spserver.sqc
(C)”
v “spclient.c -- Call various stored procedures”
v “spserver.c -- Definition of various types of stored procedures”
Related tasks:
v “Building CLI applications on UNIX” on page 219
v “Building CLI applications on Windows” on page 228
v “Building CLI routines on UNIX” on page 222
v “Building CLI routines on Windows” on page 231
v “Setting up the CLI environment” on page 209
Related reference:
v “CLI samples” on page 235
CLI samples
UNIX directory: sqllib/samples/cli. Windows directory: sqllib\samples\cli.
Table 20. Sample CLI program files
Type of sample Sample program name Program description
ADMIN_CMD admincmd_autoconfigure.c How to autoconfigure a database using
samples - ADMIN_CMD routine
Programs that
admincmd_contacts.c How to add, update and drop contacts and
demonstrate the
contactgroups using AMDIN_CMD routine
use of
ADMIN_CMD admincmd_export.c How to export data using ADMIN_CMD
stored routine.
procedure for admincmd_import.c How to import data using ADMIN_CMD
performing routine.
administration
tasks admincmd_describe.c How to describe table and indices using
ADMIN_CMD routine.
admincmd_quiesce.c How to quiesce tablespaces and database
using ADMIN_CMD routine.
admincmd_onlinebackup.c How to perform online backup using
ADMIN_CMD routine.
admincmd_updateconfig.c How to update and reset the Database
configuration and Database Manager
Configuration Parameters using
ADMIN_CMD routine.
Related concepts:
v “Building embedded SQL applications using the sample build script” in
Developing Embedded SQL Applications
v “Error-checking utilities” in Developing Embedded SQL Applications
v “Sample files” in Samples Topics
Related concepts:
v “Introduction to DB2 CLI and ODBC” on page 3
Related tasks:
v “Obtaining the IBM DB2 Driver for ODBC and CLI” on page 243
v “Configuring the IBM DB2 Driver for ODBC and CLI” on page 249
v “Connecting to databases with the IBM DB2 Driver for ODBC and CLI” on page
257
v “Deploying the IBM DB2 Driver for ODBC and CLI with database applications”
on page 269
v “Installing the IBM DB2 Driver for ODBC and CLI” on page 245
v “Running DB2 CLI and ODBC applications using the IBM DB2 Driver for ODBC
and CLI” on page 263
v “Uninstalling the IBM DB2 Driver for ODBC and CLI” on page 273
Prerequisites:
To obtain the IBM DB2 Driver for ODBC and CLI, you need:
v internet access, so you can download the driver; or
v a DB2 Version 9 installation CD.
Procedure:
You can obtain the IBM DB2 Driver for ODBC and CLI by doing either of the
following:
v Download the driver from: http://www-306.ibm.com/software/data/db2/ad.
or
v Copy the driver from the DB2 Version 9 install CD.
The driver is in a compressed file called “db2_driver_for_odbc_cli.zip” on
Windows operating systems, and “db2_driver_for_odbc_cli.tar.Z” on other
operating systems.
Related concepts:
v Chapter 27, “IBM DB2 Driver for ODBC and CLI overview,” on page 241
Prerequisites:
To install the IBM DB2 Driver for ODBC and CLI, you need:
v to obtain the compressed file that contains the driver.
See: Obtaining the IBM DB2 Driver for ODBC and CLI.
Procedure:
There is no installation program for the IBM DB2 Driver for ODBC and CLI. You
must install the driver manually:
1. Copy the compressed file that contains the driver onto the target machine from
the internet or a DB2 Version 9 installation CD.
2. Uncompress that file into your chosen install directory on the target machine.
3. Optional: remove the compressed file.
Example:
If you are installing the IBM DB2 Driver for ODBC and CLI under the
following conditions:
– the operating systems on the target machine is AIX; and
– the DB2 Version 9 CD is mounted on the target machine.
the steps you would follow are:
1. Create the directory $HOME/db2_cli_odbc_driver, where you will install the
driver.
2. Locate the compressed file that contains the driver on the install CD. In this
scenario, the file would be called db2_driver_for_odbc_cli.tar.Z.
3. Copy db2_driver_for_odbc_cli.tar.Z to the install directory,
$HOME/db2_cli_odbc_driver.
4. Uncompress db2_driver_for_odbc_cli.tar.Z:
cd $HOME/db2_cli_odbc_driver
uncompress db2_driver_for_odbc_cli.tar.Z
tar −xvf db2_driver_for_odbc_cli.tar
5. Delete db2_driver_for_odbc_cli.tar.Z.
Related concepts:
v Chapter 27, “IBM DB2 Driver for ODBC and CLI overview,” on page 241
Related tasks:
v “Obtaining the IBM DB2 Driver for ODBC and CLI” on page 243
v “Installing multiple copies of the IBM DB2 Driver for ODBC and CLI on the
same machine” on page 246
Installing multiple copies of the IBM DB2 Driver for ODBC and CLI on
the same machine
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed separately.
You can install multiple copies of the IBM DB2 Driver for ODBC and CLI on the
same machine. You might want to do this if you have two database applications on
the same machine that require different versions of the driver.
Prerequisites:
To install multiple copies of the IBM DB2 Driver for ODBC and CLI on the same
machine, you need:
v to obtain the compressed file that contains the driver.
See: Obtaining the IBM DB2 Driver for ODBC and CLI.
Procedure:
For each copy of the IBM DB2 Driver for ODBC and CLI that you are installing:
1. create a unique target installation directory; and
2. follow the installation steps outlined in Installing the IBM DB2 Driver for
ODBC and CLI.
Example:
If you are installing two copies of the IBM DB2 Driver for ODBC and CLI
under the following conditions:
– the operating systems on the target machine is AIX; and
– the DB2 Version 9 CD is mounted on the target machine.
the steps you would follow are:
1. Create the two directories, $HOME/db2_cli_odbc_driver1 and
$HOME/db2_cli_odbc_driver2, where you will install the driver.
2. Locate the compressed file that contains the driver on the install CD. In this
scenario, the file would be called db2_driver_for_odbc_cli.tar.Z.
3. Copy db2_driver_for_odbc_cli.tar.Z to the install directories,
$HOME/db2_cli_odbc_driver1 and $HOME/db2_cli_odbc_driver2.
4. Uncompress db2_driver_for_odbc_cli.tar.Z in each directory:
cd $HOME/db2_cli_odbc_driver1
uncompress db2_driver_for_odbc_cli.tar.Z
tar −xvf db2_driver_for_odbc_cli.tar
cd $HOME/db2_cli_odbc_driver2
uncompress db2_driver_for_odbc_cli.tar.Z
tar −xvf db2_driver_for_odbc_cli.tar
5. Delete db2_driver_for_odbc_cli.tar.Z.
Related concepts:
v Chapter 27, “IBM DB2 Driver for ODBC and CLI overview,” on page 241
Intalling the IBM DB2 Driver for ODBC and CLI on a machine with an
existing DB2 client
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed separately.
You can install one or more copies of the IBM DB2 Driver for ODBC and CLI on a
machine where a DB2 Client or DB2 Runtime Client is already installed. You might
want to do this if you have developed some ODBC or CLI database applications
with the DB2 Client that you plan to deploy with the IBM DB2 Driver for ODBC
and CLI, because it enables you to test the database applications with the driver on
the same machine as your development environment.
Prerequisites:
To install the IBM DB2 Driver for ODBC and CLI on the same machine as a DB2
Client or DB2 Runtime Client, you need:
v to obtain the compressed file that contains the driver.
See: Obtaining the IBM DB2 Driver for ODBC and CLI.
Procedure:
The procedure for installing one or more copies of the IBM DB2 Driver for ODBC
and CLI on a machine that already has a DB2 Client or DB2 Runtime Client
installed is the same as the procedure for installing the driver on a machine that
has no DB2 Client installed.
See: Installing the IBM DB2 Driver for ODBC and CLI and Installing multiple
copies of the IBM DB2 Driver for ODBC and CLI on the same machine.
Related concepts:
v Chapter 27, “IBM DB2 Driver for ODBC and CLI overview,” on page 241
Related tasks:
v “Obtaining the IBM DB2 Driver for ODBC and CLI” on page 243
v “Installing multiple copies of the IBM DB2 Driver for ODBC and CLI on the
same machine” on page 246
v “Installing the IBM DB2 Driver for ODBC and CLI” on page 245
Chapter 29. Installing the IBM DB2 Driver for ODBC and CLI 247
248 CLI Guide and Reference, Volume 1
Chapter 30. Configuring the IBM DB2 Driver for ODBC and CLI
Configuring the IBM DB2 Driver for ODBC and CLI
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately.
You must configure the IBM DB2 Driver for ODBC and CLI, and the software
components of your database application runtime environment in order for your
applications to use the driver successfully.
Prerequisites:
To configure the IBM DB2 Driver for ODBC and CLI and your application
environment for the driver, you need:
v one or more copies of the driver installed.
See: Installing the IBM DB2 Driver for ODBC and CLI.
Procedure:
To configure the IBM DB2 Driver for ODBC and CLI, and the runtime environment
of your DB2 CLI and ODBC applications to use the driver:
1. Configure aspects of the driver’s behaviour such as data source name, user
name, performance options, and connection options by updating the
db2cli.ini initialization file.
See: db2cli.ini initialization file
There is no support for the Command Line Processor (CLP) with the IBM DB2
Driver for ODBC and CLI. For this reason, you can not update CLI
configuration using the CLP command “db2 update CLI cfg”; you must update
the db2cli.ini initialization file manually.
The db2cli.ini file is located in the install directory on Windows operating
systems, and in the cfg subdirectory of the install directory on other operating
systems.
If you have multiple copies of the IBM DB2 Driver for ODBC and CLI installed,
each copy of the driver will have its own db2cli.ini file. Ensure you make the
additions to the db2cli.ini for the correct copy of the driver.
2. Configure application environment variables.
See: Configuring environment variables for the IBM DB2 Driver for ODBC
and CLI
3. For applications participating in transactions managed by the Microsoft
Distributed Transaction Coordinator (DTC) only: you must register the driver
with the DTC.
See: Registering the IBM DB2 Driver for ODBC and CLI with the Microsoft
DTC.
4. For ODBC applications using the Microsoft ODBC driver manager only: you
must register the driver with the Microsoft driver manager.
See: Registering the IBM DB2 Driver for ODBC and CLI with the Microsoft
ODBC driver manager.
Related tasks:
v “Installing the IBM DB2 Driver for ODBC and CLI” on page 245
v “Configuring environment variables for the IBM DB2 Driver for ODBC and CLI”
on page 250
v “Registering the IBM DB2 Driver for ODBC and CLI with the Microsoft DTC”
on page 253
v “Registering the IBM DB2 Driver for ODBC and CLI with the Microsoft ODBC
driver manager” on page 254
Configuring environment variables for the IBM DB2 Driver for ODBC
and CLI
To use the IBM DB2 Driver for ODBC and CLI, there are two types of environment
variables that you might have to set: environment variables that have replaced
some DB2 registry variables; and an environment variable that tells your
applications where to find the driver libraries.
Prerequisites:
To configure environment variables for the IBM DB2 Driver for ODBC and CLI,
you need:
v one or more copies of the driver installed.
See: Installing the IBM DB2 Driver for ODBC and CLI.
Procedure:
To configure environment variables for the IBM DB2 Driver for ODBC and CLI:
1. Optional: set any applicable DB2 environment variables which have DB2
registry variables.
There is no support for the Command Line Processor (CLP) with the IBM DB2
Driver for ODBC and CLI. For this reason, you can not configure DB2 registry
variables using the “db2set” CLP command. Required DB2 registry variables
have been replaced with environment variables.
For more information about DB2 registry variables, see: DB2 registry and
environment variables.
For a list of the environment variables that can be used instead of DB2 registry
variables, see: Environment variables supported by the IBM DB2 Driver for
ODBC and CLI.
2. Required for AIX 5.2 operating systems only: Set the local environment
variable DB2_CLI_DRIVER_INSTALL_PATH to the directory in which the driver is
Restrictions:
If there are multiple versions of the IBM DB2 Driver for ODBC and CLI installed
on the same machine, or if there are other DB2 Version 9 products installed on the
same machine, setting environment variables (for example, setting LIBPATH or
LD_LIBRARY_PATH to point to the IBM DB2 Driver for ODBC and CLI library) might
break existing applications. When setting an environment variable, ensure that it is
appropriate for all applications running in the scope of that environment.
Related concepts:
v “DB2 registry and environment variables” in Performance Guide
Related tasks:
v “Installing the IBM DB2 Driver for ODBC and CLI” on page 245
Related reference:
v “Environment variables supported by the IBM DB2 Driver for ODBC and CLI”
on page 251
The IBM DB2 Driver for ODBC and CLI does not support the command line
processor (CLP.) This means that the usual mechanism to set DB2 registry
variables, using the “db2set” CLP command, is not possible. Relevant DB2 registry
variables will be supported with the IBM DB2 Driver for ODBC and CLI as
environment variables instead.
The DB2 registry variables that will be supported by the IBM DB2 Driver for
ODBC and CLI as environment variables are:
Chapter 30. Configuring the IBM DB2 Driver for ODBC and CLI 251
Table 21. DB2 registry variables supported as environment variables
Type of variable Variable name(s)
General variables DB2ACCOUNT
See: General registry DB2BIDI
variables. DB2CODEPAGE
DB2COUNTRY
DB2GRAPHICUNICODESERVER
DB2LOCALE
DB2TERRITORY
System environment variables DB2DOMAINLIST
See: System environment
variables.
Communications variables DB2_FORCE_NLS_CACHE
See: Communications DB2SORCVBUF
variables. DB2SOSNDBUF
DB2TCP_CLIENT_RCVTIMEOUT
Performance variables DB2_NO_FORK_CHECK
See: Performance
variables.
Miscellaneous variables DB2CLIINIPATH
See: Miscellaneous DB2_ENABLE_LDAP
variables. DB2LDAP_BASEDN
DB2LDAP_CLIENT_PROVIDER
DB2LDAPHOST
DB2LDAP_KEEP_CONNECTION
DB2LDAP_SEARCH_SCOPE
DB2NOEXITLIST
Diagnostic variables DB2_DIAGPATH
See: DiagPath CLI/ODBC
configuration keyword.
Related concepts:
v “DB2 registry and environment variables” in Performance Guide
Related tasks:
v “Configuring environment variables for the IBM DB2 Driver for ODBC and CLI”
on page 250
db2oreg1.exe overview
The utility db2oreg1.exe is used on Windows operating systems only. This utility
does two things: it registers the XA library of the IBM DB2 Driver for ODBC and
CLI with the Microsoft Distributed Transaction Coordinator (DTC); and it registers
the driver with the Microsoft ODBC driver manager.
Related concepts:
v “Supported transaction managers” in Getting Started with Database Application
Development
Related tasks:
v “Registering the IBM DB2 Driver for ODBC and CLI with the Microsoft DTC”
on page 253
Registering the IBM DB2 Driver for ODBC and CLI with the Microsoft
DTC
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately.
To use the IBM DB2 Driver for ODBC and CLI with database applications that
participate in transactions managed by the Microsoft Distributed Transaction
Coordinator (DTC), you must register the driver with the DTC.
Here is a link to the Microsoft article outlining the details of this security
requirement:
Registry Entries Are Required for XA Transaction Support
Prerequisites:
To register the IBM DB2 Driver for ODBC and CLI with the DTC, you need:
v one or more copies of the driver installed.
See: Installing the IBM DB2 Driver for ODBC and CLI.
Restrictions:
You only need to register the IBM DB2 Driver for ODBC and CLI with the DTC if
your applications that use the driver are participating in transactions managed by
the DTC.
Procedure:
Chapter 30. Configuring the IBM DB2 Driver for ODBC and CLI 253
To register the IBM DB2 Driver for ODBC and CLI with the DTC, do the following
for each copy of the driver that is installed:
v run the db2oreg1.exe utility.
See: db2oreg1.exe overview.
The db2oreg1.exe utility makes changes to the Windows registry when you run
it after installing the driver. If you uninstall the driver, you should run the utility
again to undo those changes.
Related concepts:
v “db2oreg1.exe overview” on page 252
v Chapter 27, “IBM DB2 Driver for ODBC and CLI overview,” on page 241
Related tasks:
v “Installing the IBM DB2 Driver for ODBC and CLI” on page 245
v “Configuring the IBM DB2 Driver for ODBC and CLI” on page 249
Registering the IBM DB2 Driver for ODBC and CLI with the Microsoft
ODBC driver manager
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately.
For ODBC applications to use the IBM DB2 Driver for ODBC and CLI with the
Microsoft ODBC driver manager, you must register the driver with the driver
manager.
Prerequisites:
To register the IBM DB2 Driver for ODBC and CLI with the Microsoft ODBC
driver manager, you need:
v one or more copies of the driver installed.
See: Installing the IBM DB2 Driver for ODBC and CLI.
Restrictions:
The Microsoft ODBC driver manager is the only ODBC driver manager with which
you must register the IBM DB2 Driver for ODBC and CLI. The other ODBC driver
managers do not require this.
Procedure:
To register the IBM DB2 Driver for ODBC and CLI with the Microsoft driver
manager, do the following for each copy of the driver that is installed:
v run the db2iodbc.exe utility.
See: db2oreg1.exe overview.
The db2oreg1.exe utility makes changes to the Windows registry when you run
it after installing the driver. If you uninstall the driver, you should run the utility
again to undo those changes.
Related concepts:
v “db2oreg1.exe overview” on page 252
Chapter 30. Configuring the IBM DB2 Driver for ODBC and CLI 255
256 CLI Guide and Reference, Volume 1
Chapter 31. Connecting to databases with the IBM DB2 Driver
for ODBC and CLI
Connecting to databases with the IBM DB2 Driver for ODBC and CLI
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately.
The IBM DB2 Driver for ODBC and CLI does not create a local database directory.
This means that when you use this driver, you must make connectivity information
available to your applications in other ways.
Prerequisites:
To connect to databases with the IBM DB2 Driver for ODBC and CLI, you need:
v database(s) to which to connect; and
v one or more copies of the driver installed.
See: Installing the IBM DB2 Driver for ODBC and CLI.
Procedure:
There are five ways to specify connectivity information so that your CLI and
ODBC database applications can use the IBM DB2 Driver for ODBC and CLI to
connect to a database.
To configure connectivity for a database when using the IBM DB2 Driver for
ODBC and CLI, do one of:
1. Specify the database connectivity information in the connection string
parameter to SQLDriverConnect.
See: SQLDriverConnect function (CLI) - (Expanded) Connect to a data
source.
or
2. For CLI applications only: put the database connectivity information in the DB2
CLI configuration file.
See: db2cli.ini initialization file.
There is no support for the Command Line Processor (CLP) with the IBM DB2
Driver for ODBC and CLI. For this reason, you can not update CLI
configuration using the CLP command “db2 update CLI cfg”; you must update
the db2cli.ini initialization file manually.
The db2cli.ini file is located in the install directory on Windows operating
systems, and in the cfg subdirectory of the install directory on other operating
systems.
If you have multiple copies of the IBM DB2 Driver for ODBC and CLI installed,
each copy of the driver will have its own db2cli.ini file. Ensure you make the
additions to the db2cli.ini for the correct copy of the driver.
or
or
4. Use the FileDSN CLI/ODBC keyword to identify a file DSN that contains the
database connectivity information.
See: FileDSN CLI/ODBC configuration keyword.
A file DSN is a file that contains database connectivity information. You can
create a file DSN by using the SaveFile CLI/ODBC keyword. On Microsoft
Windows you can use the Microsoft ODBC driver manager to create a file DSN.
or
5. For local database servers only: use the PROTOCOL and DB2INSTANCE CLI/ODBC
keywords to identify the local database:
v Set the PROTOCOL CLI/ODBC keyword to the value “Local”; and
v Set the DB2INSTANCE CLI/ODBC keyword to the instance name of the local
database server on which the database is located.
See: Protocol CLI/ODBC configuration keyword.
Here is a list of CLI/ODBC keywords that work with file DSN or DSN-less
connections:
v AltHostName CLI/ODBC configuration keyword;
v AltPort CLI/ODBC configuration keyword;
v Authentication CLI/ODBC configuration keyword;
v BIDI CLI/ODBC configuration keyword;
v FileDSN CLI/ODBC configuration keyword;
v Instance CLI/ODBC configuration keyword;
v Interrupt CLI/ODBC configuration keyword;
v KRBPlugin CLI/ODBC configuration keyword;
v Protocol CLI/ODBC configuration keyword;
v PWDPlugin CLI/ODBC configuration keyword;
v SaveFile CLI/ODBC configuration keyword;
Examples:
For the following examples, consider a database with the following properties:
v the database or subsystem is called db1 on the server;
v the server is located at 11.22.33.444;
v the access port is 56789; and
v the transfer protocol is TCPIP.
To make a connection to the database in a CLI application, you could do one of the
following:
1. Call SQLConnect with a connection string that contains:
“Database=db1; Protocol=tcpip;
Hostname=11.22.33.444;
Servicename=56789;”
Related concepts:
v “db2cli.ini initialization file” on page 277
v Chapter 27, “IBM DB2 Driver for ODBC and CLI overview,” on page 241
Related tasks:
v “Installing the IBM DB2 Driver for ODBC and CLI” on page 245
v “Registering ODBC data sources for applications using the IBM DB2 Driver for
ODBC and CLI” on page 259
v “Using security plugins with the IBM DB2 Driver for ODBC and CLI” on page
261
Related reference:
v “FileDSN CLI/ODBC configuration keyword” on page 323
v “Protocol CLI/ODBC configuration keyword” on page 356
v “AltHostName CLI/ODBC configuration keyword” on page 284
v “AltPort CLI/ODBC configuration keyword” on page 285
v “Authentication CLI/ODBC configuration keyword” on page 290
v “BIDI CLI/ODBC configuration keyword” on page 291
v “Instance CLI/ODBC configuration keyword” on page 328
v “Interrupt CLI/ODBC configuration keyword” on page 329
v “KRBPlugin CLI/ODBC configuration keyword” on page 330
v “PWDPlugin CLI/ODBC configuration keyword” on page 358
v “SaveFile CLI/ODBC configuration keyword” on page 365
v “SQLDriverConnect function (CLI) - (Expanded) Connect to a data source” in
Call Level Interface Guide and Reference, Volume 2
Registering ODBC data sources for applications using the IBM DB2
Driver for ODBC and CLI
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately.
Before an ODBC database application can use the IBM DB2 Driver for ODBC and
CLI to connect to a database, you must: 1) register the database as an ODBC data
source with the ODBC driver manager; and 2) identify the IBM DB2 Driver for
ODBC and CLI as the ODBC driver for the data source.
Chapter 31. Connecting to databases with the IBM DB2 Driver for ODBC and CLI 259
Prerequisites:
To register a database as an ODBC data source and associate the IBM DB2 Driver
for ODBC and CLI with it, you need:
v databases to which your ODBC applications are going to connect;
v an ODBC driver manager installed; and
v one or more copies of the driver installed.
See: Installing the IBM DB2 Driver for ODBC and CLI.
Procedure:
The procedure for registering a database as an ODBC data source and associating
the IBM DB2 Driver for ODBC and CLI with it depends on which driver manager
you are using.
v For the Microsoft ODBC driver manager:
1. Register the IBM DB2 Driver for ODBC and CLI with the Microsoft ODBC
driver manager using the db2oreg1.exe utility.
See: Registering the IBM DB2 Driver for ODBC and CLI with the
Microsoft ODBC driver manager.
2. Register the database as an ODBC data source.
See: Setting up the Windows CLI environment.
v For open source ODBC driver managers:
1. Identify the database as an ODBC data source by adding database
information to the odbc.ini file.
See: Setting up the UNIX ODBC environment.
2. Associate the IBM DB2 Driver for ODBC and CLI with the data source by
adding the fully qualified driver library file in the section of the odbc.ini file
for the database.
The name of the IBM DB2 Driver for ODBC and CLI library file is db2app.dll on
Windows platorms, and db2app.lib on other platforms. The driver library file is
located in the “lib” subdirectory of the directory in which you installed the driver.
If you have multiple copies of the IBM DB2 Driver for ODBC and CLI installed,
ensure the intended copy is identified in the odbc.ini file.
Example:
If you are registering ODBC data sources with an open source driver manager
under the following conditions:
– the operating system on the target machine is a AIX;
– there are two copies of the IBM DB2 Driver for ODBC and CLI installed at
$HOME/db2_cli_odbc_driver1 and
$HOME/db2_cli_odbc_driver2
– there are two ODBC database applications:
1. ODBCapp_A
- connects to two data sources, db1 and db2; and
- is intended to use the copy of the driver installed at
$HOME/db2_cli_odbc_driver1.
2. ODBCapp_B
- connects to the data source db3; and
[db2]
Driver=$HOME/db2_cli_odbc_driver1/lib/libdb.a
Description=Second ODBC data source for ODBCapp1,
using the first copy of the IBM DB2 Driver for ODBC and CLI
[db3]
Driver=$HOME/db2_cli_odbc_driver2/lib/libdb2.a
Description=First ODBC data source for ODBCapp2,
using the second copy of the IBM DB2 Driver for ODBC and CLI
Related tasks:
v “Installing the IBM DB2 Driver for ODBC and CLI” on page 245
v “Registering the IBM DB2 Driver for ODBC and CLI with the Microsoft ODBC
driver manager” on page 254
v “Setting up the Windows CLI environment” on page 215
v “Setting up the UNIX ODBC environment” on page 210
v “Configuring the IBM DB2 Driver for ODBC and CLI” on page 249
v “Connecting to databases with the IBM DB2 Driver for ODBC and CLI” on page
257
Using security plugins with the IBM DB2 Driver for ODBC and CLI
A security plug-in is a dynamicaly-loadable library that provides authentication
security services.
Procedure:
Using security plug-ins with the IBM DB2 Driver for ODBC and CLI is no different
from using security plug-ins with a DB2 Client or DB2 Runtime Client.
For more information about using security plugins with DB2, see:
Security plug-ins.
When you read about using security plug-ins throughout the DB2 Information
Center and DB2 books, consider the IBM DB2 Driver for ODBC and CLI like a DB2
client. Details about using security plug-ins with DB2 clients apply to using
security plug-ins with the IBM DB2 Driver for ODBC and CLI too.
Related concepts:
v “Authentication” in Administration Guide: Planning
v “Security plug-ins” in Administrative API Reference
Chapter 31. Connecting to databases with the IBM DB2 Driver for ODBC and CLI 261
262 CLI Guide and Reference, Volume 1
Chapter 32. Running DB2 CLI and ODBC applications using
the IBM DB2 Driver for ODBC and CLI
Running DB2 CLI and ODBC applications using the IBM DB2 Driver for
ODBC and CLI
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately; and it provides a
subset of the functionality of either DB2 client.
The IBM DB2 Driver for ODBC and CLI provides runtime support for:
v the DB2 CLI application programming interface (API);
v the ODBC API;
v the XA API; and
v connecting to databases.
Prerequisites:
To run database applications with the IBM DB2 Driver for ODBC and CLI, you
need:
v one or more copies of the driver installed.
See: Installing the IBM DB2 Driver for ODBC and CLI.
v to have configured the application environment for the driver.
See: Configuring the IBM DB2 Driver for ODBC and CLI.
Procedure:
When writing applications for, or migrating applications to using the IBM DB2
Driver for ODBC and CLI:
v Ensure your applications use only the DB2 CLI, ODBC and XA API functions
that are supported by the driver.
See:
- DB2 CLI and ODBC API support in the IBM DB2 Driver for ODBC and
CLI
- XA API support in the IBM DB2 Driver for ODBC and CLI
v Ensure your applications are not attempting to make use of DB2 Client or DB2
Runtime Client functionality that is restricted in the driver.
See: Restrictions of the IBM DB2 Driver for ODBC and CLI
v Use the 32-bit version of the driver with 32-bit database applications, and use
the 64-bit version of the driver with 64-bit database applications.
v Understand the available tracing, logging, and diagnostic support provided by
the driver for investigating problems.
See: Diagnostic support in the IBM DB2 Driver for ODBC and CLI
Related concepts:
v Chapter 27, “IBM DB2 Driver for ODBC and CLI overview,” on page 241
Related reference:
v “DB2 CLI and ODBC API support in the IBM DB2 Driver for ODBC and CLI”
on page 264
v “Diagnostic support in the IBM DB2 Driver for ODBC and CLI” on page 266
v “LDAP support in the IBM DB2 Driver for ODBC and CLI” on page 265
v “Restrictions of the IBM DB2 Driver for ODBC and CLI” on page 266
v “XA API support in the IBM DB2 Driver for ODBC and CLI” on page 265
DB2 CLI and ODBC API support in the IBM DB2 Driver for ODBC and
CLI
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately; and it provides a
subset of the functionality of either DB2 client.
The IBM DB2 Driver for ODBC and CLI supports the ANSI and (where they exist)
the Unicode versions of the following ODBC and DB2 CLI functions:
SQLAllocConnect SQLExtendedPrepare SQLNumParams
SQLAllocEnv SQLFetch SQLNumResultCols
SQLAllocHandle SQLFetchScroll SQLParamData
SQLAllocStmt SQLForeignKeys SQLParamOptions
SQLBindCol SQLFreeConnect SQLPrepare
SQLBindFileToCol SQLFreeEnv SQLPrimaryKeys
SQLBindFileToParam SQLFreeHandle SQLProcedureColumns
SQLBindParameter SQLFreeStmt SQLProcedures
SQLBrowseConnect SQLGetConnectAttr SQLPutData
SQLBuildDataLink SQLGetConnectOption SQLRowCount
SQLBulkOperations SQLGetCursorName SQLSetColAttributes
SQLCancel SQLGetData SQLSetConnectAttr
SQLCloseCursor SQLGetDataLinkAttr SQLSetConnectOption
SQLColAttribute SQLGetDescField SQLSetConnection
SQLColAttributes SQLGetDescRec SQLSetCursorName
SQLColumnPrivileges SQLGetDiagField SQLSetDescField
SQLColumns SQLGetDiagRec SQLSetDescRec
SQLConnect SQLGetEnvAttr SQLSetEnvAttr
SQLCopyDesc SQLGetFunctions SQLSetParam
SQLDataSources SQLGetInfo SQLSetPos
SQLDescribeCol SQLGetLength SQLSetScrollOptions
SQLDescribeParam SQLGetPosition SQLSetStmtAttr
SQLDisconnect SQLGetSQLCA SQLSetStmtOption
SQLDriverConnect SQLGetStmtAttr SQLSpecialColumns
SQLEndTran SQLGetStmtOption SQLStatistics
SQLError SQLGetSubString SQLTablePrivileges
SQLExecDirect SQLGetTypeInfo SQLTables
SQLExecute SQLMoreResults SQLTransact
SQLExtendedBind SQLNativeSql
SQLExtendedFetch SQLNextResult
Related tasks:
v “Running DB2 CLI and ODBC applications using the IBM DB2 Driver for ODBC
and CLI” on page 263
The IBM DB2 Driver for ODBC and CLI supports the following XA API functions:
xa_open
xa_close
xa_start
xa_end
xa_prepare
xa_commit
xa_rollback
xa_forget
xa_recover
Related tasks:
v “Running DB2 CLI and ODBC applications using the IBM DB2 Driver for ODBC
and CLI” on page 263
LDAP support in the IBM DB2 Driver for ODBC and CLI
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately; and it provides a
subset of the functionality of either DB2 client.
The IBM DB2 Driver for ODBC and CLI supports the LDAP Database Directory
support with one restriction:
v the LDAP cache can not be saved to disk; it is an in-memory cache only. The
DB2LDAPCACHE registry variable is ignored.
The steps for configuring the database application environment to enable LDAP
when using the IBM DB2 Driver for ODBC and CLI are the same as for other
scenarios, except that the DB2LDAPCACHE registry variable is ignored.
Related concepts:
v “Lightweight Directory Access Protocol (LDAP) overview” in Administration
Guide: Implementation
Related tasks:
v “Running DB2 CLI and ODBC applications using the IBM DB2 Driver for ODBC
and CLI” on page 263
Chapter 32. Running DB2 CLI and ODBC applications using the IBM DB2 Driver for ODBC and CLI 265
Restrictions of the IBM DB2 Driver for ODBC and CLI
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately; and it provides a
subset of the functionality of either DB2 client.
The IBM DB2 Driver for ODBC and CLI provides runtime support for:
v the DB2 CLI application programming interface (API);
v the ODBC API;
v the XA API; and
v connecting to databases.
Functionality not supported by the IBM DB2 Driver for ODBC and CLI:
v CLI and ODBC application development;
v the Command Line Processor (CLP);
v administrative APIs;
v installation program.
– You must install the driver manually.
See: Installing the IBM DB2 Driver for ODBC and CLI.
– You must configure the driver manually.
See: Configuring the IBM DB2 Driver for ODBC and CLI.
Functionality supported with restrictions by the IBM DB2 Driver for ODBC and
CLI:
v Messages will be reported only in English.
v There is no local database directory.
– LDAP is supported, but the LDAP cache is not saved to disk.
See: LDAP support in the IBM DB2 Driver for ODBC and CLI.
– Configuring for connectivity requires some additional steps.
See: Connecting to databases with the IBM DB2 Driver for ODBC and CLI.
v Not all diagnostic utilities are available.
See: Diagnostic support in the IBM DB2 Driver for ODBC and CLI.
Related tasks:
v “Running DB2 CLI and ODBC applications using the IBM DB2 Driver for ODBC
and CLI” on page 263
Diagnostic support in the IBM DB2 Driver for ODBC and CLI
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately; and it provides a
subset of the functionality of either DB2 client.
The following tracing, logging, and diagnostic utilities are provided with the IBM
DB2 Driver for ODBC and CLI:
CLI trace
The method for using CLI trace with the IBM DB2 Driver for ODBC and
CLI is the same as the method for using CLI trace with a DB2 client.
The IBM DB2 Driver for ODBC and CLI does not support the command line
processor (CLP.) This means that the usual mechanism to set DB2 registry
variables, using the db2set command, is not possible. However, the functionality of
registry variables related to diagnostics is supported through CLI/ODBC
keywords:
v DiagLevel CLI/ODBC configuration keyword
v NotifyLevel CLI/ODBC configuration keyword
v DiagPath CLI/ODBC configuration keyword
Chapter 32. Running DB2 CLI and ODBC applications using the IBM DB2 Driver for ODBC and CLI 267
and environment variables:
v DB2_DIAGPATH
See: Environment variables supported by the IBM DB2 Driver for ODBC and
CLI.
The IBM DB2 Driver for ODBC and CLI can be installed on a Network File
System (NFS). If the driver is installed on a read-only NFS, the environment
variable DB2_DIAGPATH must be set to allow DB2 trace to work.
Related concepts:
v “CLI trace files” in Troubleshooting Guide
v “Interpreting diagnostic log file entries” in Troubleshooting Guide
v “Obtaining a DB2 trace using db2trc” in Troubleshooting Guide
Related tasks:
v “Running DB2 CLI and ODBC applications using the IBM DB2 Driver for ODBC
and CLI” on page 263
You can simplify the deployment of your DB2 CLI and ODBC database
applications by creating an install program. You can deploy the IBM DB2 Driver
for ODBC and CLI with your DB2 CLI and ODBC database applications by
incorporating the files and installation and configuration steps required for the
driver into your install program.
Prerequisites:
To deploy the IBM DB2 Driver for ODBC and CLI with your applications you will
need:
v a mechanism for deploying the applications, such as an install program;
v to obtain the compressed file that contains the driver;
See: Obtaining the IBM DB2 Driver for ODBC and CLI
v a redistribution license.
See: License requirements for the IBM DB2 Driver for ODBC and CLI.
Restrictions:
Under the terms of the redistribution licence, only some of the IBM DB2 Driver for
ODBC and CLI files can be redistributed. Which files may be redistributed is listed
in the file redist.txt. This file can be found in the compressed file that contains
the driver, called db2_driver_for_odbc_cli.zip on the Windows platforms and
db2_driver_for_odbc_cli.tar.Z on all other platforms.
Procedure:
To incorporate the IBM DB2 Driver for ODBC and CLI into your install program,
you must do the following:
1. Copy the driver files into your install program. See the restrictions above
about which driver files can be redistributed.
2. Set the install program to install the driver on the target machine.
See: Installing the IBM DB2 Driver for ODBC and CLI.
3. Set the install program to configure the environment on the target machine.
See: Configuring the IBM DB2 Driver for ODBC and CLI.
Related concepts:
v Chapter 27, “IBM DB2 Driver for ODBC and CLI overview,” on page 241
Related tasks:
v “Obtaining the IBM DB2 Driver for ODBC and CLI” on page 243
Related reference:
v “License requirements for the IBM DB2 Driver for ODBC and CLI” on page 270
License requirements for the IBM DB2 Driver for ODBC and CLI
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately.
You can download and install the IBM DB2 Driver for ODBC and CLI and use it
with your ODBC and CLI applications without a special license. However, you
need a redistribution license to redistribute the driver with your applications.
Under the terms of the redistribution licence, only some of the IBM DB2 Driver for
ODBC and CLI files can be redistributed. Which files may be redistributed is listed
in the file redist.txt. This file can be found in the compressed file that contains
the driver, called db2_driver_for_odbc_cli.zip on the Windows platform and
db2_driver_for_odbc_cli.tar.Z on all other platforms. For more information
about where to find this file, see: Obtaining the IBM DB2 Driver for ODBC and
CLI
The IBM DB2 ODBC and CLI Driver can be used to connect only to a properly
licensed:
v DB2 for Linux, UNIX and Windows server;
v DB2 Connect server;
v WebSphere® Federation server;
v Cloudscape™ Server;
v Informix® Database Server;
v DB2 for OS/390 and z/OS server (see below);
v DB2 for iSeries server (see below); and
v DB2 for VM/VSE server (see below).
The IBM DB2 ODBC and CLI Driver can be used to connect to DB2 for OS/390
and z/OS, DB2 for iSeries and DB2 for VM/VSE servers only if:
v a connection is established through a properly licensed DB2 Connect server; or
v directly to the server if and only if a properly formatted authentic license key
file db2con.lkf is present. The file db2con.lkf is distributed as part of the DB2
Connect products, so the only way to obtain this license key file is to purchase
one of the following DB2 Connect products:
– DB2 Connect Personal Edition;
– DB2 Connect Enterprise Edition;
– DB2 Connect Application Server Edition;
– DB2 Connect Unlimited Edition for zSeries;
– DB2 Connect Unlimited Edition for iSeries;
No other product will provide this file or the license rights afforded by the
presence of this file. Tampering with or unauthorized distribution of this file will
constitute a breach of the license agreement.
Related concepts:
Chapter 33. Deploying the IBM DB2 Driver for ODBC and CLI with database applications 271
272 CLI Guide and Reference, Volume 1
Chapter 34. Uninstalling the IBM DB2 Driver for ODBC and
CLI
Uninstalling the IBM DB2 Driver for ODBC and CLI
The IBM DB2 Driver for ODBC and CLI is not part of the DB2 Client or the DB2
Runtime Client. It must be installed and configured separately.
Prerequisites:
To uninstall the IBM DB2 Driver for ODBC and CLI, you need:
v to ensure no applications are linked to the libraries of the copy of the driver that
you will be uninstalling.
Procedure:
There is no unstall utility for the IBM DB2 Driver for ODBC and CLI. It must be
uninstalled manually:
v On Windows operating systems only:
If you ran the utility db2iodbc.exe to register the driver with the Microsoft
Distributed Transaction Coordinator (DTC), you need to run the utility again
before uninstalling the driver. This will clean up theWindows registry entries the
utility created when you ran it to register the driver with the DTC.
see: db2oreg1.exe overview
v Remove the driver files by deleting the directory in which you installed the
driver.
For example, if you installed the driver in $HOME/db2_cli_odbc_driver, then
delete $HOME/db2_cli_odbc_driver.
Related concepts:
v “db2oreg1.exe overview” on page 252
v Chapter 27, “IBM DB2 Driver for ODBC and CLI overview,” on page 241
Related tasks:
v “Installing the IBM DB2 Driver for ODBC and CLI” on page 245
By default, the location of the DB2 CLI/ODBC configuration keyword file is in the
sqllib directory on Window platforms, and in the sqllib/cfg directory of the
database instance running the CLI/ODBC applications on UNIX platforms. If the
ODBC Driver Manager is used to configure a User Data Source on the Windows
platform, a db2cli.ini might be created in the user’s home (profile) directory.
The environment variable DB2CLIINIPATH can also be used to override the default
and specify a different location for the file.
The db2cli.ini initialization file is an ASCII file which stores values for the DB2
CLI configuration options. A sample file is shipped to help you get started. While
most CLI/ODBC configuration keywords are set in the db2cli.ini initialization
file, some keywords are set by providing the keyword information in the
connection string to SQLDriverConnect() instead.
There is one section within the file for each database (data source) the user wishes
to configure. If needed, there is also a common section that affects all database
connections.
Note: Configuration keywords are valid in the COMMON section, however, they
will apply to all database connections.
Before setting a common keyword it is important to evaluate its impact on all DB2
CLI/ODBC connections from that client. A keyword such as TRACE, for instance,
will generate information on all DB2 CLI/ODBC applications connecting to DB2 on
that client, even if you are intending to troubleshoot only one of those applications.
Each database specific section always begins with the name of the data source
name (DSN) between square brackets:
[data source name]
The parameters are set by specifying a keyword with its associated keyword value
in the form:
KeywordName =keywordValue
v All the keywords and their associated values for each database must be located
below the database section header.
Although you can edit the db2cli.ini file manually on all platforms, it is
recommended that you use the Configuration Assistant if it is available on your
platform or the UPDATE CLI CONFIGURATION command. You must add a blank
line after the last entry if you manually edit the db2cli.ini file.
Related reference:
v “UPDATE CLI CONFIGURATION command” in Command Reference
v “CLI/ODBC configuration keywords listing by category” on page 279
v “DBAlias CLI/ODBC configuration keyword” on page 313
v “Trace CLI/ODBC configuration keyword” on page 375
v “Miscellaneous variables” in Performance Guide
v “SQLDriverConnect function (CLI) - (Expanded) Connect to a data source” in
Call Level Interface Guide and Reference, Volume 2
The Compatibility set of options is used to define DB2 behavior. They can be set
to ensure that other applications are compatible with DB2.
v “CheckForFork CLI/ODBC configuration keyword” on page 294
v “CursorTypes CLI/ODBC configuration keyword” on page 308
v “DeferredPrepare CLI/ODBC configuration keyword” on page 316
v “DescribeCall CLI/ODBC configuration keyword” on page 317
v “DescribeParam CLI/ODBC configuration keyword” on page 320
v “DisableKeysetCursor CLI/ODBC configuration keyword” on page 321
v “DisableMultiThread CLI/ODBC configuration keyword” on page 322
v “DisableUnicode CLI/ODBC configuration keyword” on page 322
v “OleDbReportIsLongForLongTypes CLI/ODBC configuration keyword” on page
347
v “OleDbSQLColumnsSortByOrdinal CLI/ODBC configuration keyword” on page
348
v “RetCatalogAsCurrServer CLI/ODBC configuration keyword” on page 362
v “RetOleDbConnStr CLI/ODBC configuration keyword” on page 363
v “Trusted_Connection CLI/ODBC configuration keyword” on page 386 (use
SQLDriverConnect() to set this keyword)
General keywords.
v “DBAlias CLI/ODBC configuration keyword” on page 313
v “PWD CLI/ODBC configuration keyword” on page 357
v “UID CLI/ODBC configuration keyword” on page 388
The Data Type set of options is used to define how DB2 reports and handles
various data types.
v “BitData CLI/ODBC configuration keyword” on page 292
v “CurrentImplicitXMLParseOption CLI/ODBC configuration keyword” on page
302
v “DateTimeStringFormat CLI/ODBC configuration keyword” on page 310
v “DecimalFloatRoundingMode CLI/ODBC configuration keyword” on page 315
v “FloatPrecRadix CLI/ODBC configuration keyword” on page 324
v “Graphic CLI/ODBC configuration keyword” on page 326
v “LOBMaxColumnSize CLI/ODBC configuration keyword” on page 332
v “LongDataCompat CLI/ODBC configuration keyword” on page 333
v “MapBigintCDefault CLI/ODBC configuration keyword” on page 334
The Optimization set of options is used to speed up and reduce the amount of
network flow between the CLI/ODBC Driver and the server.
v “AllowGetDataLOBReaccess CLI/ODBC configuration keyword” on page 284
v “AppendForFetchOnly CLI/ODBC configuration keyword” on page 287
v “AppUsesLOBLocator CLI/ODBC configuration keyword” on page 287
v “BlockForNRows CLI/ODBC configuration keyword” on page 292
v “BlockLobs CLI/ODBC configuration keyword” on page 293
v “ClientBuffersUnboundLOBS CLI/ODBC configuration keyword” on page 296
v “CurrentMaintainedTableTypesForOpt CLI/ODBC configuration keyword” on
page 303
v “DB2Degree CLI/ODBC configuration keyword” on page 311
v “DB2Explain CLI/ODBC configuration keyword” on page 311
v “DB2NETNamedParam CLI/ODBC configuration keyword” on page 312
v “DB2Optimization CLI/ODBC configuration keyword” on page 313
v “DescribeInputOnPrepare CLI/ODBC configuration keyword” on page 318
v “DescribeOutputLevel CLI/ODBC configuration keyword” on page 318
v “KeepDynamic CLI/ODBC configuration keyword” on page 329
v “LOBCacheSize CLI/ODBC configuration keyword” on page 331
v “LOBFileThreshold CLI/ODBC configuration keyword” on page 332
v “LockTimeout CLI/ODBC configuration keyword” on page 333
v “MaxLOBBlockSize CLI/ODBC configuration keyword” on page 345
v “OptimizeForNRows CLI/ODBC configuration keyword” on page 349
v “Reopt CLI/ODBC configuration keyword” on page 360
v “SkipTrace CLI/ODBC configuration keyword” on page 367
v “StreamGetData CLI/ODBC configuration keyword” on page 371
v “StreamPutData CLI/ODBC configuration keyword” on page 372
v “Underscore CLI/ODBC configuration keyword” on page 389
The Static SQL set of options is used when running static SQL statements in
CLI/ODBC applications.
v “StaticCapFile CLI/ODBC configuration keyword” on page 368
v “StaticLogFile CLI/ODBC configuration keyword” on page 369
v “StaticMode CLI/ODBC configuration keyword” on page 370
v “StaticPackage CLI/ODBC configuration keyword” on page 370
The Transaction set of options is used to control and speed up SQL statements
used in the application.
v “ArrayInputChain CLI/ODBC configuration keyword” on page 288
v “AsyncEnable CLI/ODBC configuration keyword” on page 289
v “AutoCommit CLI/ODBC configuration keyword” on page 290
v “ClientAcctStr CLI/ODBC configuration keyword” on page 294
v “ClientApplName CLI/ODBC configuration keyword” on page 295
v “ClientUserID CLI/ODBC configuration keyword” on page 297
v “ClientWrkStnName CLI/ODBC configuration keyword” on page 298
v “ConnectType CLI/ODBC configuration keyword” on page 301
v “CursorHold CLI/ODBC configuration keyword” on page 307
v “Mode CLI/ODBC configuration keyword” on page 346
v “SQLOverrideFileName CLI/ODBC configuration keyword” on page 368
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Introduction to DB2 CLI and ODBC” on page 3
Related reference:
v “SQLDriverConnect function (CLI) - (Expanded) Connect to a data source” in
Call Level Interface Guide and Reference, Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLGetData function (CLI) - Get data from a column” in Call Level Interface
Guide and Reference, Volume 2
The DB2 CLI function (API) name that generated an error is appended to the error
message retrieved using SQLGetDiagRec() or SQLError(). The function name is
enclosed in curly braces { }.
For example,
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLError function (CLI) - Retrieve error information” in Call Level Interface
Guide and Reference, Volume 2
v “SQLGetDiagRec function (CLI) - Get multiple fields settings of diagnostic
record” in Call Level Interface Guide and Reference, Volume 2
Specifying 1 to append the row and column number will return the
following text for error CLI0111E:
[IBM][CLI Driver] CLI0111E Numeric value out of range.
SQLSTATE=22003 {Row=2,Col=1}
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “Header and record fields for the DiagIdentifier argument (CLI)” in Call Level
Interface Guide and Reference, Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
v “LOB locators in CLI applications” on page 98
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
To enable chaining:
288 CLI Guide and Reference, Volume 1
1. Set the keyword ArrayInputChain = -1.
2. Prepare and bind input parameters to the SQL statement.
3. Set the SQL_ATTR_CHAINING_BEGIN statement attribute with
SQLSetStmtAttr().
4. Update the bound parameters with input data and call SQLExecute().
5. Repeat Step 4 for as many rows as there are in the input array.
6. Set the SQL_ATTR_CHAINING_END statement attribute with
SQLSetStmtAttr() after the last row in the array has been processed according
to Step 4.
The effect of completing these steps will be the same as if normal array input had
been used.
Setting ArrayInputChain=0 (the default value) turns this array input feature off.
ArrayInputChain can also be set to any positive integer which sets the array size to
use for the input array.
Related concepts:
v “Reduction of network flows with CLI array input chaining” on page 62
v “db2cli.ini initialization file” on page 277
Related reference:
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
v “CLI/ODBC configuration keywords listing by category” on page 279
Related concepts:
v “Asynchronous execution of CLI functions” on page 127
v “db2cli.ini initialization file” on page 277
Related tasks:
v “Executing functions asynchronously in CLI applications” on page 129
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
To be consistent with ODBC, DB2 CLI defaults with AutoCommit on, which means
each statement is treated as a single, complete transaction. This keyword can
provide an alternative default, but will only be used if the application does not
specify a value for SQL_ATTR_AUTOCOMMIT.
1 = SQL_ATTR_AUTOCOMMIT_ON (default)
0 = SQL_ATTR_AUTOCOMMIT_OFF
This keyword also allows you to specify whether autocommit should be enabled in
a Distributed Unit of Work (DUOW) environment. If a connection is part of a
coordinated Distributed Unit of Work, and AutoCommit is not set, the default does
not apply; implicit commits arising from autocommit processing are suppressed. If
AutoCommit is set to 1, and the connection is part of a coordinated Distributed
Unit of Work, the implicit commits are processed. This may result in severe
performance degradation, and possibly other unexpected results elsewhere in the
DUOW system. However, some applications may not work at all unless this is
enabled.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Multisite updates (two phase commit) in CLI applications” on page 137
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
This option allows you to specify whether ODBC binary data types (SQL_BINARY,
SQL_VARBINARY, SQL_LONGVARBINARY, and SQL_BLOB), are reported as
binary type data. IBM DBMSs support columns with binary data types by defining
CHAR, VARCHAR, and LONG VARCHAR columns with the FOR BIT DATA
attribute. DB2 Database for Linux, UNIX, and Windows will also support binary
data via the BLOB data type (in this case it is mapped to a CLOB data type).
Only set BitData = 0 if you are sure that all columns defined as FOR BIT DATA or
BLOB contain only character data, and the application is incapable of displaying
binary data columns.
1 = report FOR BIT DATA and BLOB data types as binary data types (default).
0 = report FOR BIT DATA and BLOB data types as character data types.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQL symbolic and default data types for CLI applications” on page 41
The BlockForNRows keyword controls the number of rows of data that are
returned to the client in a single fetch request. If BlockForNRows is not specified
(the default setting), then as many rows of non-LOB data as can fit in a query
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Large object usage” in Developing SQL and External Routines
v “Large object usage in CLI applications” on page 96
Related reference:
v “BlockLobs CLI/ODBC configuration keyword” on page 293
v “CLI/ODBC configuration keywords listing by category” on page 279
Setting BlockLobs to 1 enables all of the LOB data associated with rows that fit
completely within a single query block to be returned in a single fetch request, if
the server supports LOB blocking. LOB data is described here as being associated
with a row, because the LOB data of a result set is itself not contained in the row.
Instead, the row contains a reference to the actual LOB data. Therefore, with LOB
blocking fetch, any rows of the result set that fit completely within the query block
(where each row consists of non-LOB data, since LOB data is not stored directly in
the row), will have their associated LOB data returned from the server, if the
server supports LOB blocking.
If the server does not support LOB blocking and the result set contains LOB data,
then only one row of data, including the LOB, will be returned in a single fetch
request, irrespective of the value BlockLobs is set to.
Chapter 35. CLI/ODBC configuration keywords 293
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Large object usage in CLI applications” on page 96
v “Large object usage” in Developing SQL and External Routines
Related reference:
v “BlockForNRows CLI/ODBC configuration keyword” on page 292
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “Environment attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
This option allows the CLI application to set the client accounting string that is
sent to the host database through DB2 Connect. Applications that do not offer the
accounting string by default can take advantage of this keyword to provide this
information.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Environment attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “ClientApplName CLI/ODBC configuration keyword” on page 295
v “ClientUserID CLI/ODBC configuration keyword” on page 297
v “ClientWrkStnName CLI/ODBC configuration keyword” on page 298
This option allows the CLI application to set the client application name that is
sent to the host database through DB2 Connect. Applications that do not offer the
application name by default can take advantage of this keyword to provide this
information.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Environment attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “ClientAcctStr CLI/ODBC configuration keyword” on page 294
v “ClientUserID CLI/ODBC configuration keyword” on page 297
v “ClientWrkStnName CLI/ODBC configuration keyword” on page 298
Related concepts:
v “db2cli.ini initialization file” on page 277
v “LOB locators in CLI applications” on page 98
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “LOBCacheSize CLI/ODBC configuration keyword” on page 331
v “SQLGetLength function (CLI) - Retrieve length of a string value” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetPosition function (CLI) - Return starting position of string” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetSubString function (CLI) - Retrieve portion of a string value” in Call
Level Interface Guide and Reference, Volume 2
This option allows the CLI application to set the client user ID (accounting user
ID) that is sent to the host database through DB2 Connect. Applications that do not
offer the user ID by default can take advantage of this keyword to provide this
information.
Related concepts:
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Environment attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “ClientAcctStr CLI/ODBC configuration keyword” on page 294
v “ClientApplName CLI/ODBC configuration keyword” on page 295
v “ClientWrkStnName CLI/ODBC configuration keyword” on page 298
This option allows the CLI application to set the client workstation name that is
sent to the host database through DB2 Connect. Applications that do not offer the
client workstation name by default can take advantage of this keyword to provide
this information.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Environment attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “ClientAcctStr CLI/ODBC configuration keyword” on page 294
v “ClientApplName CLI/ODBC configuration keyword” on page 295
298 CLI Guide and Reference, Volume 1
v “ClientUserID CLI/ODBC configuration keyword” on page 297
This keyword is used to increase the number of sections for SQL statements in
CLI/ODBC applications. If it is used, the administrator should explicitly bind the
required bind files with the CLIPkg bind option. For client applications, the
db2cli.ini file on the client must be updated with this value of CLIPkg. For
CLI/JDBC stored procedures, the db2cli.ini file on the server (DB2 UDB Version
6.1 or later on UNIX or Intel™ platforms) must be updated with the same value of
CLIPkg.
If the value is NOT an integer between 3 and 30, the default will be used without
error or warning.
This setting only applies to large packages (containing 384 sections). The number
of small packages (containing 64 sections) is 3 and cannot be changed.
It is recommended that you only increase the number of sections enough to run
your application as the packages take up space in the database.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Handles in CLI” on page 15
Related reference:
v “BIND command” in Command Reference
v “CLI/ODBC configuration keywords listing by category” on page 279
Note: This keyword does not affect the Control Center. The Control Center
always connects to the catalog partition referred to by the
SQL_CONN_CATALOG_NODE setting.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related tasks:
v “Setting environment variables on Windows” in Administration Guide:
Implementation
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Automatic client reroute and high availability disaster recovery (HADR)” in
Data Recovery and High Availability Guide and Reference
v “DB2 Sysplex exploitation” in DB2 Connect User’s Guide
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “CATALOG TCPIP/TCPIP4/TCPIP6 NODE command” in Command Reference
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Environment attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
This keyword defines the path used to resolve function references and data type
references that are used in dynamic SQL statements. It contains a list of one or
more schema-names, where schema-names are enclosed in double quotes and
separated by commas.
This keyword is used as part of the process for resolving unqualified function and
stored procedure references that may have been defined in a schema name other
than the current user’s schema. The order of the schema names determines the
order in which the function and procedure names will be resolved.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Schemas” in SQL Reference, Volume 1
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “USER special register” in SQL Reference, Volume 1
Setting this keyword issues the SET CURRENT IMPLICIT XMLPARSE OPTION
statement after every connection to a database. By default, this statement is not
issued.
The SET CURRENT IMPLICIT XMLPARSE OPTION statement sets the CURRENT
IMPLICIT XMLPARSE OPTION special register, which controls whether white
space is stripped or preserved during implicit non-validating parsing.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “CURRENT IMPLICIT XMLPARSE OPTION special register” in SQL Reference,
Volume 1
v “SET CURRENT IMPLICIT XMLPARSE OPTION statement” in SQL Reference,
Volume 2
v “XMLPARSE scalar function” in SQL Reference, Volume 1
v “CLI/ODBC configuration keywords listing by category” on page 279
This keyword defines the default value for the CURRENT MAINTAINED TABLE
TYPES FOR OPTIMIZATION special register. The value of the special register
affects the types of tables which are considered in the optimization of a query.
Refer to the SET CURRENT MAINTAINED TABLE TYPES FOR OPTIMIZATION
SQL statement for details on the supported settings of ALL, FEDERATED_TOOL,
NONE, SYSTEM, or USER. The <list> option represents a combination of the
supported settings, however, ALL and NONE cannot be specified with any other
value, and the same value cannot be specified more than once. Separate each value
in the list with a comma, for example:
CurrentMaintainedTableTypesForOpt = SYSTEM,USER
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “dft_mttb_types - Default maintained table types for optimization configuration
parameter” in Performance Guide
v “SET CURRENT MAINTAINED TABLE TYPES FOR OPTIMIZATION
statement” in SQL Reference, Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
When set, this option issues the command ″SET CURRENT PACKAGE PATH =
schema1, schema2, ...″ after every connection to the database. This setting specifies
the list of schema names (collection identifiers) that will be searched when there is
a package from a different schema.
This keyword is best suited for use with ODBC static processing applications,
rather than CLI applications.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
This option issues the SET CURRENT PACKAGESET SQL statement with
the CurrentPackageSet value after every connection to a database. By
default this clause is not appended.
The SET CURRENT PACKAGESET SQL statement sets the schema name
(collection identifier) that is used to select the package to use for
subsequent SQL statements.
CLI/ODBC applications issue dynamic SQL statements. Using this option
you can control the privileges used to run these statements:
v Choose a schema to use when running SQL statements from CLI/ODBC
applications.
v Ensure the objects in the schema have the desired privileges and then
rebind accordingly.
v Set the CurrentPackageSet option to this schema.
The SQL statements from the CLI/ODBC applications will now run under
the specified schema and use the privileges defined there.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “SET CURRENT PACKAGESET statement” in SQL Reference, Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Reopt CLI/ODBC configuration keyword” on page 360
Setting this keyword sets the value of the CURRENT REFRESH AGE special
register.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CURRENT REFRESH AGE special register” in SQL Reference, Volume 1
v “SET CURRENT REFRESH AGE statement” in SQL Reference, Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SET SCHEMA statement” in SQL Reference, Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SET SCHEMA statement” in SQL Reference, Volume 2
Note: Cursors are always closed when transactions are rolled back.
This option affects the result returned by SQLGetInfo() when called with
SQL_CURSOR_COMMIT_BEHAVIOR or SQL_CURSOR_ROLLBACK_BEHAVIOR.
The value of CursorHold is ignored if connecting to DB2 Server for VSE & VM
where cursor with hold is not supported.
The DBMS will operate more efficiently with CursorHold disabled, as resources no
longer need to be maintained after the end of a transaction.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLGetInfo function (CLI) - Get general information” in Call Level Interface
Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
This keyword only affects calls made to the following DB2 CLI functions:
v SQLBulkOperations()
v SQLExecDirect()
v SQLExecute()
v SQLFetchScroll()
v SQLPrepare()
v SQLSetPos()
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLBulkOperations function (CLI) - Add, update, delete or fetch a set of rows”
in Call Level Interface Guide and Reference, Volume 2
v “SQLExecDirect function (CLI) - Execute a statement directly” in Call Level
Interface Guide and Reference, Volume 2
v “SQLExecute function (CLI) - Execute a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLFetchScroll function (CLI) - Fetch rowset and return data for all bound
columns” in Call Level Interface Guide and Reference, Volume 2
v “SQLPrepare function (CLI) - Prepare a statement” in Call Level Interface Guide
and Reference, Volume 2
v “SQLSetPos function (CLI) - Set the cursor position in a rowset” in Call Level
Interface Guide and Reference, Volume 2
When using a File DSN you must use this option to specify the database on the
server to connect to. This value has nothing to do with any database alias name
specified on the client, it must be set to the database name on the server itself.
This setting is only considered when the Protocol option is set to TCPIP.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Hostname CLI/ODBC configuration keyword” on page 327
v “Protocol CLI/ODBC configuration keyword” on page 356
v “ServiceName CLI/ODBC configuration keyword” on page 366
The DateTimeStringFormat keyword controls the format in which date or time data
is inserted into character columns. This setting affects the insertion of
SQL_C_DATE, SQL_C_TIME, or SQL_C_TIMESTAMP data into the following
column types:
v SQL_CHAR
v SQL_VARCHAR
v SQL_LONGVARCHAR
v SQL_CLOB
This keyword also affects the format of date or time columns that are retrieved
into character strings. For example, retrieving data from an SQL_TIMESTAMP
column into an SQL_C_CHAR string will be affected by the setting of this
keyword.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Data types and data conversion in CLI applications” on page 39
Related reference:
v “Datetime values” in SQL Reference, Volume 1
v “CLI/ODBC configuration keywords listing by category” on page 279
If the value specified is anything other than 0 (the default) then DB2 CLI will issue
the following SQL statement after a successful connection:
This specifies the degree of parallelism for the execution of the SQL statements.
The database manager will determine the degree of parallelism if you specify ANY.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SET CURRENT DEGREE statement” in SQL Reference, Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI and ODBC function summary” in Call Level Interface Guide and Reference,
Volume 2
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “EXPLAIN statement” in SQL Reference, Volume 2
Related concepts:
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
If this option is set then DB2 CLI will issue the following SQL statement after a
successful connection:
This specifies the query optimization level at which the optimizer should operate
the SQL queries.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SET CURRENT QUERY OPTIMIZATION statement” in SQL Reference, Volume 2
This keyword allows for Data Source Names of greater than 8 single byte
characters. The Data Source Name (DSN) is the name, enclosed in square brackets,
that denotes the section header in the db2cli.ini. Typically, this section header is
the database alias name which has a maximum length of 8 bytes. A user who
wishes to refer to the data source with a longer, more meaningful name, can place
the longer name in the section header, and set this keyword value to the database
alias used on the CATALOG command. Here is an example:
The end user can specify [MyMeaningfulName] as the name of the data source on
connect while the actual database alias is DB2DBT10.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CATALOG DATABASE command” in Command Reference
v “CLI/ODBC configuration keywords listing by category” on page 279
This option is only used when connecting to DB2 for z/OS and OS/390, and only
if (base) table catalog information is requested by the application. If a large number
of tables exist in the z/OS or OS/390 subsystem, a dbname can be specified to
reduce the time it takes for the application to query table information, and reduce
the number of tables listed by the application.
If this option is set then the statement IN DATABASE dbname will be appended to
various statements such as CREATE TABLE.
This value maps to the DBNAME column in the z/OS or OS/390 system catalog
tables. If no value is specified, or if views, synonyms, system tables, or aliases are
also specified via TableType, only table information will be restricted; views,
aliases, and synonyms are not restricted with DBName. It can be used in
conjunction with SchemaList, and TableType to further limit the number of tables
for which information will be returned.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SchemaList CLI/ODBC configuration keyword” on page 365
v “TableType CLI/ODBC configuration keyword” on page 374
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
Defers sending the PREPARE request until the corresponding execute request is
issued. The two requests are then combined into one command/reply flow (instead
of two) to minimize network flow and to improve performance.
v 0 = SQL_DEFERRED_PREPARE_OFF. The PREPARE request will be executed
the moment it is issued.
v 1 = SQL_DEFERRED_PREPARE_ON (default). Defer the execution of the
PREPARE request until the corresponding execute request is issued.
If the target DBMS does not support deferred prepare, the client disables
deferred prepare for that connection.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Deferred prepare in CLI applications” on page 26
Related tasks:
v “Preparing and executing SQL statements in CLI applications” on page 24
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “PREPARE statement” in SQL Reference, Volume 2
v “SQLCA (SQL communications area)” in SQL Reference, Volume 1
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Related concepts:
v “db2cli.ini initialization file” on page 277
By default, DB2 CLI does not request input parameter describe information when
it prepares an SQL statement. If an application has correctly bound parameters to a
statement, then this describe information is unnecessary and not requesting it
improves performance. If, however, parameters have not been correctly bound,
then statement execution will fail and cause the CLI error recovery retry logic to
request input parameter describe information. The result is an additional server
request and reduced performance, compared to if the describe information had
been requested with the prepare. Setting DescribeInputOnPrepare to 1 causes the
input describe information to be requested with the prepare. This setting may
improve performance for applications which rely heavily on the CLI retry logic to
recover from application binding errors.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related tasks:
v “Binding parameter markers in CLI applications” on page 29
v “Preparing and executing SQL statements in CLI applications” on page 24
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
The following table lists the fields that form the describe information that
the server returns when it receives a prepare or describe request. These
fields are grouped into levels, and the DescribeOutputLevel CLI/ODBC
configuration keyword controls which levels of describe information the
CLI driver requests.
Notes:
1. Not all levels of describe information are supported by all DB2 servers.
All levels of describe information are supported on the following DB2
servers: DB2 for Linux, UNIX, and Windows Version 8 and later, DB2
for z/OS Version 8 and later, and DB2 for iSeries Version 5 Release 3
and later. All other DB2 servers support only the 2 or 0 setting for
DescribeOutputLevel.
2. The default behavior allows CLI to promote the level to 3 if the
application asks for describe information that was not initially retrieved
using the default level 2. This might result in two network flows to the
server. If an application uses this keyword to explicitly set a describe
level, then no promotion will occur. Therefore, if the keyword is used
to set the describe level to 2, CLI will not promote to level 3 even if the
application asks for extended information.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
When set to 1, this keyword forces the CLI driver to return a static cursor to the
application, even if the application has requested a keyset-driven scrollable cursor.
Related concepts:
v “Cursors in CLI applications” on page 65
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
If multithreading is disabled then all calls for all threads will be serialized at the
process level. Use this setting for multithreaded applications that require serialized
behavior.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Multithreaded CLI applications” on page 133
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
With Unicode support enabled, and when called by a Unicode application, CLI
will attempt to connect to the database using the best client code page possible to
ensure there is no unnecessary data loss due to code page conversion. This may
increase the connection time as code pages are exchanged, or may cause code page
conversions on the client that did not occur before this support was added.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Unicode CLI applications” on page 143
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Descriptor FieldIdentifier argument values (CLI)” in Call Level Interface Guide
and Reference, Volume 2
v “SQLColumns function (CLI) - Get column information for a table” in Call Level
Interface Guide and Reference, Volume 2
v “SQLGetDescField function (CLI) - Get single field settings of descriptor record”
in Call Level Interface Guide and Reference, Volume 2
v “SQLGetTypeInfo function (CLI) - Get data type information” in Call Level
Interface Guide and Reference, Volume 2
v “SQLProcedureColumns function (CLI) - Get input/output parameter
information for a procedure” in Call Level Interface Guide and Reference, Volume 2
v “SQLSpecialColumns function (CLI) - Get special (row identifier) columns” in
Call Level Interface Guide and Reference, Volume 2
This option can be used to reduce the amount of information returned when the
application gets a list of privileges for tables in a database, or columns in a table.
The list of authorization IDs specified is used as a filter; the only tables or columns
that are returned are those with privileges that have been granted TO those IDs.
Set this option to a list of one or more authorization IDs that have been granted
privileges, delimited with single quotes, and separated by commas. The entire
string must also be enclosed in double quotes. For example:
In the above example, if the application gets a list of privileges for a specific table,
only those columns that have a privilege granted TO USER1, USER2, or USER8
would be returned.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “GrantorList CLI/ODBC configuration keyword” on page 325
This option can be used to reduce the amount of information returned when the
application gets a list of privileges for tables in a database, or columns in a table.
The list of authorization IDs specified is used as a filter; the only tables or columns
that are returned are those with privileges that have been granted BY those IDs.
Set this option to a list of one or more authorization IDs that have granted
privileges, delimited with single quotes, and separated by commas. The entire
string must also be enclosed in double quotes. For example:
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “GranteeList CLI/ODBC configuration keyword” on page 324
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Data types and data conversion in CLI applications” on page 39
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
Use this option in conjunction with the ServiceName option to specify the required
attributes for a TCP/IP connection from this client machine to a server running
DB2. These two values are only considered when the Protocol option is set to
TCPIP.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Protocol CLI/ODBC configuration keyword” on page 356
v “ServiceName CLI/ODBC configuration keyword” on page 366
On rare occasions, an application will not correctly handle warning messages. This
keyword can be used to indicate that warnings from the database manager are not
to be passed to the application. The possible settings are:
v 0 - Warnings are reported as usual (default)
v 1 - Database manager warnings are ignored and SQL_SUCCESS is returned.
Warnings from the DB2 CLI/ODBC driver are still returned; many are required
for normal operation.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “IgnoreWarnList CLI/ODBC configuration keyword” on page 328
v “WarningList CLI/ODBC configuration keyword” on page 391
Each sqlstate must be in uppercase, delimited with single quotes and separated by
commas. The entire string must also be enclosed in double quotes. For example:
IgnoreWarnList="’01000’, ’01004’,’01504’"
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “IgnoreWarnings CLI/ODBC configuration keyword” on page 327
v “WarningList CLI/ODBC configuration keyword” on page 391
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Programming hints and tips for CLI applications” on page 55
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “CurrentPackageSet CLI/ODBC configuration keyword” on page 305
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
Related concepts:
Chapter 35. CLI/ODBC configuration keywords 331
v “db2cli.ini initialization file” on page 277
v “Large object usage in CLI applications” on page 96
v “LOB locators in CLI applications” on page 98
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
v “ClientBuffersUnboundLOBS CLI/ODBC configuration keyword” on page 296
v “CLI/ODBC configuration keywords listing by category” on page 279
This option specifies the maximum number of bytes of LOB data that DB2 CLI will
buffer in memory on calls to SQLPutData(). If the specified cache size is exceeded,
a temporary file will be created on disk to hold the LOB data before it is sent to
the server.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Large object usage in CLI applications” on page 96
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLPutData function (CLI) - Passing data value for a parameter” in Call Level
Interface Guide and Reference, Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “LongDataCompat CLI/ODBC configuration keyword” on page 333
v “MapXMLDescribe CLI/ODBC configuration keyword” on page 344
v “SQL symbolic and default data types for CLI applications” on page 41
The LockTimeout keyword specifies the number of seconds a DB2 CLI application
will wait to obtain locks. If the keyword is set to 0, locks will not be waited for.
The -1 setting causes the application to wait indefinitely until either the lock is
granted or deadlock occurs.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “locktimeout - Lock timeout configuration parameter” in Performance Guide
v “CLI/ODBC configuration keywords listing by category” on page 279
This option indicates to DB2 CLI what data type the application expects when
working with a database with large object (LOB) columns.
This option is useful when running ODBC applications that cannot handle the
large object data types.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Large object usage in CLI applications” on page 96
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “LOBMaxColumnSize CLI/ODBC configuration keyword” on page 332
v “MapGraphicDescribe CLI/ODBC configuration keyword” on page 339
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Data types and data conversion in CLI applications” on page 39
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “CLI and ODBC function summary” in Call Level Interface Guide and Reference,
Volume 2
Related reference:
v “SQLColumns function (CLI) - Get column information for a table” in Call Level
Interface Guide and Reference, Volume 2
v “SQLDescribeCol function (CLI) - Return a set of attributes for a column” in Call
Level Interface Guide and Reference, Volume 2
v “SQLDescribeParam function (CLI) - Return description of a parameter marker”
in Call Level Interface Guide and Reference, Volume 2
v “SQLGetDescField function (CLI) - Get single field settings of descriptor record”
in Call Level Interface Guide and Reference, Volume 2
v “SQLGetDescRec function (CLI) - Get multiple field settings of descriptor
record” in Call Level Interface Guide and Reference, Volume 2
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “SQLColAttribute function (CLI) - Return a column attribute” in Call Level
Interface Guide and Reference, Volume 2
v “SQLProcedureColumns function (CLI) - Get input/output parameter
information for a procedure” in Call Level Interface Guide and Reference, Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Data types and data conversion in CLI applications” on page 39
To control the SQL data type that is returned when DATE columns and parameter
markers are described, set MapDateDescribe as follows:
v 0 - to return the default SQL data type: SQL_DATE for ODBC 2.0 or
SQL_TYPE_DATE for ODBC 3.0
v 1 - to return the SQL_CHAR SQL data type
v 2 - to return the SQL_WCHAR SQL data type
Only the following DB2 CLI functions are affected by setting MapDateDescribe:
v SQLColumns()
v SQLDescribeCol()
v SQLDescribeParam()
v SQLGetDescField()
v SQLGetDescRec()
v SQLProcedureColumns()
v SQLSpecialColumns()
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Data types and data conversion in CLI applications” on page 39
Related reference:
v “SQLColumns function (CLI) - Get column information for a table” in Call Level
Interface Guide and Reference, Volume 2
v “SQLDescribeCol function (CLI) - Return a set of attributes for a column” in Call
Level Interface Guide and Reference, Volume 2
v “SQLDescribeParam function (CLI) - Return description of a parameter marker”
in Call Level Interface Guide and Reference, Volume 2
v “SQLGetDescField function (CLI) - Get single field settings of descriptor record”
in Call Level Interface Guide and Reference, Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
338 CLI Guide and Reference, Volume 1
v “CLI/ODBC configuration keywords listing by category” on page 279
To control the SQL data type that is returned when GRAPHIC-based columns and
parameter markers are described, set MapGraphicDescribe as follows:
v 0 - to return the default SQL data types
v 1 - to return the CHAR-based SQL data types: SQL_CHAR for GRAPHIC
columns, SQL_VARCHAR for VARGRAPHIC columns, and
SQL_LONGVARCHAR for LONG VARGRAPHIC columns
v 2 - to return the WCHAR-based SQL data types: SQL_WCHAR for GRAPHIC
columns, SQL_WVARCHAR for VARGRAPHIC columns, and
SQL_WLONGVARCHAR for LONG VARGRAPHIC columns
Only the following DB2 CLI functions are affected by setting MapGraphicDescribe:
v SQLDescribeCol()
v SQLDescribeParam()
v SQLGetDescField()
v SQLGetDescRec()
v SQLProcedureColumns()
v SQLSpecialColumns()
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Data types and data conversion in CLI applications” on page 39
Related reference:
v “MapDateDescribe CLI/ODBC configuration keyword” on page 337
v “MapTimeDescribe CLI/ODBC configuration keyword” on page 340
v “MapTimestampDescribe CLI/ODBC configuration keyword” on page 342
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLDescribeCol function (CLI) - Return a set of attributes for a column” in Call
Level Interface Guide and Reference, Volume 2
v “SQLDescribeParam function (CLI) - Return description of a parameter marker”
in Call Level Interface Guide and Reference, Volume 2
v “SQLGetDescField function (CLI) - Get single field settings of descriptor record”
in Call Level Interface Guide and Reference, Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Data types and data conversion in CLI applications” on page 39
Related reference:
v “CLI and ODBC function summary” in Call Level Interface Guide and Reference,
Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “MapDateCDefault CLI/ODBC configuration keyword” on page 336
v “MapTimestampCDefault CLI/ODBC configuration keyword” on page 342
v “Patch2 CLI/ODBC configuration keyword” on page 352
To control the SQL data type that is returned when TIME columns and parameter
markers are described, set MapTimeDescribe as follows:
v 0 - to return the default SQL data type: SQL_TIME for ODBC 2.0 or
SQL_TYPE_TIME for ODBC 3.0
v 1 - to return the SQL_CHAR SQL data type
v 2 - to return the SQL_WCHAR SQL data type
Only the following DB2 CLI functions are affected by setting MapTimeDescribe:
v SQLColumns()
v SQLDescribeCol()
v SQLDescribeParam()
v SQLGetDescField()
v SQLGetDescRec()
v SQLProcedureColumns()
v SQLSpecialColumns()
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Data types and data conversion in CLI applications” on page 39
Related reference:
v “SQLColumns function (CLI) - Get column information for a table” in Call Level
Interface Guide and Reference, Volume 2
v “SQLDescribeCol function (CLI) - Return a set of attributes for a column” in Call
Level Interface Guide and Reference, Volume 2
v “SQLDescribeParam function (CLI) - Return description of a parameter marker”
in Call Level Interface Guide and Reference, Volume 2
v “SQLGetDescField function (CLI) - Get single field settings of descriptor record”
in Call Level Interface Guide and Reference, Volume 2
v “SQLGetDescRec function (CLI) - Get multiple field settings of descriptor
record” in Call Level Interface Guide and Reference, Volume 2
v “SQLProcedureColumns function (CLI) - Get input/output parameter
information for a procedure” in Call Level Interface Guide and Reference, Volume 2
v “SQLSpecialColumns function (CLI) - Get special (row identifier) columns” in
Call Level Interface Guide and Reference, Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “MapDateDescribe CLI/ODBC configuration keyword” on page 337
v “MapGraphicDescribe CLI/ODBC configuration keyword” on page 339
v “MapTimestampDescribe CLI/ODBC configuration keyword” on page 342
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Data types and data conversion in CLI applications” on page 39
Related reference:
v “CLI and ODBC function summary” in Call Level Interface Guide and Reference,
Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “MapDateCDefault CLI/ODBC configuration keyword” on page 336
v “MapTimeCDefault CLI/ODBC configuration keyword” on page 340
To control the SQL data type that is returned when TIMESTAMP columns and
parameter markers are described, set MapTimestampDescribe as follows:
v 0 - to return the default SQL data type: SQL_TIMESTAMP for ODBC 2.0 or
SQL_TYPE_TIMESTAMP for ODBC 3.0
v 1 - to return the SQL_CHAR SQL data type
v 2 - to return the SQL_WCHAR SQL data type
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Data types and data conversion in CLI applications” on page 39
Related reference:
v “SQLColumns function (CLI) - Get column information for a table” in Call Level
Interface Guide and Reference, Volume 2
v “SQLDescribeCol function (CLI) - Return a set of attributes for a column” in Call
Level Interface Guide and Reference, Volume 2
v “SQLDescribeParam function (CLI) - Return description of a parameter marker”
in Call Level Interface Guide and Reference, Volume 2
v “SQLGetDescField function (CLI) - Get single field settings of descriptor record”
in Call Level Interface Guide and Reference, Volume 2
v “SQLGetDescRec function (CLI) - Get multiple field settings of descriptor
record” in Call Level Interface Guide and Reference, Volume 2
v “SQLProcedureColumns function (CLI) - Get input/output parameter
information for a procedure” in Call Level Interface Guide and Reference, Volume 2
v “SQLSpecialColumns function (CLI) - Get special (row identifier) columns” in
Call Level Interface Guide and Reference, Volume 2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “MapDateDescribe CLI/ODBC configuration keyword” on page 337
v “MapGraphicDescribe CLI/ODBC configuration keyword” on page 339
v “MapTimeDescribe CLI/ODBC configuration keyword” on page 340
Related concepts:
v “db2cli.ini initialization file” on page 277
v “XML data handling in CLI applications - Overview” on page 117
v “XML data type” in XML Guide
Related reference:
v “C data types for CLI applications” on page 43
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLBindCol function (CLI) - Bind a column to an application variable or LOB
locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
v “SQLGetData function (CLI) - Get data from a column” in Call Level Interface
Guide and Reference, Volume 2
To control the SQL data type that is returned when XML columns and parameter
markers are described, set MapXMLDescribe to one of the following integer values:
v -370 to return the default SQL_XML SQL data type
The data length for XML values mapped to LOB types is the maximum length for
the mapped data type.
When used in conjunction with the LongDataCompat keyword set to the value 1,
XML values mapped to LOB data types will be mapped to the corresponding
LONG data type as well.
Character types specified for MapXMLDescribe may result in data loss during data
conversion if the application code page does not support all of the characters in
the source data. Mapping XML values to character types, therefore, is only
recommended with caution.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “XML data encoding” in XML Guide
v “XML data handling in CLI applications - Overview” on page 117
v “XML data type” in XML Guide
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “LongDataCompat CLI/ODBC configuration keyword” on page 333
v “SQL symbolic and default data types for CLI applications” on page 41
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
v “Miscellaneous variables” in Performance Guide
Sets the CONNECT mode to either SHARE or EXCLUSIVE. If a mode is set by the
application at connect time, this value is ignored. The default is SHARE.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “CONNECT (Type 1) statement” in SQL Reference, Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Data type mappings between DB2 and OLE DB” in Developing ADO.NET and
OLE DB Applications
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
The IBM DB2 OLE DB Provider describes CHAR, VARCHAR, LONG VARCHAR,
and CLOB data as DBTYPE_WSTR by default as of DB2 UDB Version 8.1.2. The
CLI/ODBC configuration keyword OleDbReturnCharAsWChar allows you to
change this default to have the previously stated character data types reported as
DBTYPE_STR.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Purpose of the IBM OLE DB Provider for DB2” in Developing ADO.NET and
OLE DB Applications
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Data type mappings between DB2 and OLE DB” in Developing ADO.NET and
OLE DB Applications
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Schema rowsets supported by the IBM OLE DB Provider” in Developing
ADO.NET and OLE DB Applications
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
This option will append the ″OPTIMIZE FOR n ROWS″ clause to every select
statement, where n is an integer larger than 0. If set to 0 (the default) this clause
will not be appended.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Patch2 CLI/ODBC configuration keyword” on page 352
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Patch1 CLI/ODBC configuration keyword” on page 350
Use this option in conjunction with the Hostname option to specify the required
attributes for a TCP/IP connection from this client machine to a server running
DB2. These two values are only considered when the Protocol option is set to
TCPIP.
Specify either the server system’s service name or its port number. The service
name must be available for lookup at the client machine if it is used.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
If ProgramName is set to ″PID″ for a CLI application, the application’s name will
consist of the prefix ″CLI″ along with the application’s process ID and the current
active connection handle, as follows: CLI<pid>:<connectionHandle#>. The ″PID″
setting is useful when monitoring application servers that run multiple
applications with numerous connections to the same database.
(When the ProgramName keyword is set to ″PID″ for other types of applications,
the ″CLI″ prefix is replaced with the following values corresponding to the type of
application: ″JDBC″ for JDBC applications, ″OLEDB″ for OLE DB applications, and
″ADONET″ for .NET applications.)
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Database CLI/ODBC configuration keyword” on page 309
v “Hostname CLI/ODBC configuration keyword” on page 327
v “ServiceName CLI/ODBC configuration keyword” on page 366
It is stored as plain text in the db2cli.ini file and is therefore not secure.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “UID CLI/ODBC configuration keyword” on page 388
Note: DB2 CLI implements query timeout by starting a thread that periodically
queries the status of each executing query. The QueryTimeoutInterval value
specifies how long the query timeout thread waits between checks for
expired queries. Because this is an asynchronous operation to the queries
being executed, it is possible that a given query may not be timed out until
SQL_ATTR_QUERY_TIMEOUT + QueryTimeoutInterval seconds. In the
example above, the best-case timeout would be at 26 seconds, and the
worst-case timeout would be at 35 seconds.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLSetStmtAttr function (CLI) - Set options related to a statement” in Call Level
Interface Guide and Reference, Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
Related concepts:
v “Routines: Procedures” in Developing SQL and External Routines
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
v “CLI/ODBC configuration keywords listing by category” on page 279
v “CurrentPackageSet CLI/ODBC configuration keyword” on page 305
v “BIND command” in Command Reference
By default, when the DB2 CLI retry logic is able to recover successfully from a
non-fatal error, it masks that error from the application by returning
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI function return codes” on page 50
v “CLI/ODBC configuration keywords listing by category” on page 279
v “RetryOnError CLI/ODBC configuration keyword” on page 364
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLColumnPrivileges function (CLI) - Get privileges associated with the
columns of a table” in Call Level Interface Guide and Reference, Volume 2
v “SQLTablePrivileges function (CLI) - Get privileges associated with a table” in
Call Level Interface Guide and Reference, Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLTables function (CLI) - Get table information” in Call Level Interface Guide
and Reference, Volume 2
then the output connection string will have the following format:
DSN=SAMPLE;UID=;PWD=;MODE=3
then the output connection string will have the following format:
DSN=SAMPLE;UID=NEWTON;PWD=SECRET;MODE=12
OLE DB applications that use the string representation for the value of the
Mode keyword returned by SQLDriverConnect()and SQLBrowseConnect()
will receive an error from OLE DB Component Services. OLE DB
Component Services returns an error because it expects the keyword Mode
to have numeric values. Setting RetOleDbConnStr to 1 avoids this
behavior, as the value for Mode will then be numeric.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Mode CLI/ODBC configuration keyword” on page 346
By default, DB2 CLI will attempt to recover from non-fatal errors, such as incorrect
binding of application parameters, by retrieving additional information on the
failing SQL statement and then executing the statement again. The additional
information retrieved includes input parameter information from the database
catalog tables. If DB2 CLI is able to recover successfully from the error, by default,
it does not report the error to the application. The CLI/ODBC configuration
keyword ReportRetryErrorsAsWarnings allows you to set whether error recovery
warnings are returned to the application or not.
Important: Once DB2 CLI has successfully completed the error recovery, the
application may behave differently, because DB2 CLI will use the
catalog information gathered during the recovery for subsequent
executions of that particular SQL statement, rather than the information
provided in the original SQLBindParameter() function calls. If you do
not want this behavior, set RetryOnError to 0, forcing DB2 CLI not to
attempt recovery. You should, however, modify the application to
correctly bind statement parameters.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “ReportRetryErrorsAsWarnings CLI/ODBC configuration keyword” on page 361
v “SQLBindParameter function (CLI) - Bind a parameter marker to a buffer or
LOB locator” in Call Level Interface Guide and Reference, Volume 2
If there are a large number of tables defined in the database, a schema list can be
specified to reduce the time it takes for the application to query table information,
and reduce the number of tables listed by the application. Each schema name is
case-sensitive, must be delimited with single quotes, and separated by commas.
The entire string must also be enclosed in double quotes. For example:
SchemaList="’USER1’,’USER2’,’USER3’"
For DB2 for z/OS, CURRENT SQLID can also be included in this list, but without
the single quotes, for example:
SchemaList="’USER1’,CURRENT SQLID,’USER3’"
This option can be used in conjunction with DBName and TableType to further
limit the number of tables for which information will be returned.
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “DBName CLI/ODBC configuration keyword” on page 314
v “TableType CLI/ODBC configuration keyword” on page 374
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “UseServerMsgSP CLI/ODBC configuration keyword” on page 391
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
Use this option in conjunction with the Hostname option to specify the required
attributes for a TCP/IP connection from this client machine to a server running
DB2. These two values are only considered when the PROTOCOL option is set to
TCPIP.
Specify either the server system’s service name or its port number. The service
name must be available for lookup at the client machine if it is used.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Hostname CLI/ODBC configuration keyword” on page 327
v “Protocol CLI/ODBC configuration keyword” on page 356
This keyword can improve performance by allowing the DB2 trace function to
bypass CLI applications. Therefore, if the DB2 trace facility db2trc is turned on and
this keyword is set to 1, the trace will not contain information from the execution
of the CLI application.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “db2cli.ini initialization file” on page 277
[1]
StmtIn=SELECT * FROM Employee
StmtAttr=SQL_ATTR_BLOCK_FOR_NROWS=50;SQL_ATTR_OPTIMIZE_FOR_NROWS=1;
[2]
StmtIn=SELECT * FROM Sales
StmtAttr=SQL_ATTR_MAX_ROWS=25;
The number specified by ″Stmts″ in the ″[Common]″ section of the override file
equals the number of SQL statements contained in the override file.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
This keyword is used to specify the Capture File name and optionally the directory
where it will be saved.
Related concepts:
v “Capture file for CLI/ODBC/JDBC Static Profiling” on page 187
v “db2cli.ini initialization file” on page 277
Related tasks:
v “Creating static SQL with CLI/ODBC/JDBC Static Profiling” on page 185
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “StaticLogFile CLI/ODBC configuration keyword” on page 369
v “StaticMode CLI/ODBC configuration keyword” on page 370
v “StaticPackage CLI/ODBC configuration keyword” on page 370
This keyword is used to specify the Static Profiling Log File name and optionally
the directory where it will be saved.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related tasks:
v “Creating static SQL with CLI/ODBC/JDBC Static Profiling” on page 185
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “StaticCapFile CLI/ODBC configuration keyword” on page 368
v “StaticMode CLI/ODBC configuration keyword” on page 370
v “StaticPackage CLI/ODBC configuration keyword” on page 370
This option allows you to specify how the SQL issued by the CLI/ODBC
application for this DSN will be processed:
v DISABLED = Static mode disabled. No special processing. The CLI/ODBC
statements will be executed as dynamic SQL with no change. This is the default.
v CAPTURE = Capture Mode. Execute the CLI/ODBC statements as dynamic
SQL. If the SQL statements are successful, they will be captured into a file
(known as the Capture File) to be bound by the DB2CAP command later.
v MATCH = Match mode. Execute the CLI/ODBC statements as static SQL
statements if a matching statement is found in the Capture Files specified in
StaticPackage. The Capture File must first be bound by the DB2CAP command.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related tasks:
v “Creating static SQL with CLI/ODBC/JDBC Static Profiling” on page 185
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “StaticCapFile CLI/ODBC configuration keyword” on page 368
v “StaticLogFile CLI/ODBC configuration keyword” on page 369
v “StaticPackage CLI/ODBC configuration keyword” on page 370
Only the first 7 characters of the indicated package name will be used. A one-byte
suffix will be added to represent each isolation level, as follows:
v 0 for Uncommitted Read (UR)
v 1 for Cursor Stability (CS)
v 2 for Read Stability (RS)
v 3 for Repeatable Read (RR)
v 4 for No Commit (NC)
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Isolation levels” in SQL Reference, Volume 1
Related tasks:
v “Creating static SQL with CLI/ODBC/JDBC Static Profiling” on page 185
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “StaticCapFile CLI/ODBC configuration keyword” on page 368
v “StaticLogFile CLI/ODBC configuration keyword” on page 369
v “StaticMode CLI/ODBC configuration keyword” on page 370
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
By default, DB2 CLI writes data passed in through SQLPutData() function calls to
an internal statement-level buffer. On the subsequent SQLParamData() call, the
contents of the buffer are then written to an internal connection-level
communication buffer and sent to the server. If only one statement handle is used
to insert data into a target database on a particular connection at a given point in
time, then you can improve performance by setting StreamPutData=1. This causes
DB2 CLI to write the put data directly to the connection-level buffer. If, however,
multiple statements concurrently insert data into a target database on a particular
connection, then setting StreamPutData=1 may decrease performance and result in
unexpected application errors, as the statements in the shared connection-level
communication buffer will be prone to serialization.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLParamData function (CLI) - Get next parameter for which a data value is
needed” in Call Level Interface Guide and Reference, Volume 2
v “SQLPutData function (CLI) - Passing data value for a parameter” in Call Level
Interface Guide and Reference, Volume 2
Related concepts:
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
If there is a large number of tables defined in the database, a tabletype string can
be specified to reduce the time it takes for the application to query table
information, and reduce the number of tables listed by the application.
Any number of the values can be specified. Each type must be delimited with
single quotes, separated by commas, and in uppercase. The entire string must also
be enclosed in double quotes. For example:
TableType="’TABLE’,’VIEW’"
TableType is used to provide a default for the DB2 CLI function that retrieves the
list of tables, views, aliases, and synonyms in the database. If the application does
not specify a table type on the function call, and this keyword is not used,
information about all table types is returned. If the application does supply a value
for the tabletype on the function call, then that argument value will override this
keyword value.
If TableType includes any value other than TABLE, then the DBName keyword
setting cannot be used to restrict information to a particular DB2 for z/OS
database.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “DBName CLI/ODBC configuration keyword” on page 314
v “SchemaList CLI/ODBC configuration keyword” on page 365
When working with Large Objects (CLOBS, BLOBS, etc...), when data conversion
occurs, or when data is sent to the server in pieces, a temporary file is often
created on the client machine to store the information. Using this option you can
specify a location for these temporary files. The system temporary directory will be
used if nothing is specified.
The keyword is placed in the data source specific section of the db2cli.ini file, and
has the following syntax:
v TempDir= F:\DB2TEMP
The path specified must already exist and the user executing the application must
have the appropriate authorities to write files to it. When the DB2 CLI Driver
attempts to create temporary files, an SQLSTATE of HY507 will be returned if the
path name is invalid, or if the temporary files cannot be created in the directory
specified.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Large object usage in CLI applications” on page 96
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
When this option is on (1), CLI/ODBC trace records are appended to the file
indicated by the TraceFileName configuration parameter or to files in the
subdirectory indicated by the TracePathName configuration parameter. Trace will
have no effect if neither TraceFileName or TracePathName is set.
The TraceRefreshInterval keyword sets the interval in seconds at which the Trace
keyword is read from the db2cli.ini file. This allows you to dynamically turn off
the CLI/ODBC trace within n seconds.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2 databases.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Environment attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
v “TraceFileName CLI/ODBC configuration keyword” on page 378
v “TraceFlush CLI/ODBC configuration keyword” on page 379
v “TracePathName CLI/ODBC configuration keyword” on page 381
v “TraceRefreshInterval CLI/ODBC configuration keyword” on page 383
When TraceComm is set on (1) then the following information about each network
request will be included in the trace file:
v which DB2 CLI functions are processed completely on the client and which DB2
CLI functions involve communication with the server
v the number of bytes sent and received in each communication with the server
v the time spent communicating data between the client and server
This option is only used when the Trace CLI/ODBC option is turned on.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
This option is only used when the Trace CLI/ODBC option is turned on.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Trace CLI/ODBC configuration keyword” on page 375
v “TraceFlushOnError CLI/ODBC configuration keyword” on page 379
If the file specified does not exist, then it will be created; otherwise, the new trace
information will be appended to the end of the file. However, the path the file is
expected in must exist.
If the filename given is invalid or if the file cannot be created or written to, no
trace will occur and no error message will be returned.
This option is only used when the Trace option is turned on. This will be done
automatically when you set this option in the CLI/ODBC Configuration utility.
DB2 CLI trace should only be used for debugging purposes. It will slow down the
execution of the CLI/ODBC driver, and the trace information can grow quite large
if it is left on for extended periods of time.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2 databases.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Trace CLI/ODBC configuration keyword” on page 375
v “TraceFlush CLI/ODBC configuration keyword” on page 379
v “TracePathName CLI/ODBC configuration keyword” on page 381
TraceFlush specifies how often trace information is written to the CLI trace file. By
default, TraceFlush is set to 0 and each DB2 CLI trace file is kept open until the
traced application or thread terminates normally. If the application terminates
abnormally, some trace information that was not written to the trace log file may
be lost.
Set this keyword to a positive integer to force the DB2 CLI driver to close and
re-open the appropriate trace file after the specified number of trace entries. The
smaller the value of the TraceFlush keyword, the greater the impact DB2 CLI
tracing has on the performance of the application. Setting TraceFlush=1 has the
most impact on performance, but will ensure that each entry is written to disk
before the application continues to the next statement.
This option is only used when the Trace CLI/ODBC option is turned on.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Trace CLI/ODBC configuration keyword” on page 375
v “TraceFileName CLI/ODBC configuration keyword” on page 378
v “TracePathName CLI/ODBC configuration keyword” on page 381
Setting TraceFlushOnError=1 forces the DB2 CLI driver to close and re-open the
trace file each time an error is encountered. If TraceFlushOnError is left at its
default value of 0, then trace file will only be closed when the application
terminates normally or the interval specified by the TraceFlush keyword is reached.
If the application process were to terminate abnormally when
TraceFlushOnError=0, then valuable trace information may be lost. Setting
TraceFlushOnError=1 may impact performance, but will ensure that trace entries
associated with errors are written to disk.
This option is only used when the Trace CLI/ODBC option is turned on.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “TraceErrImmediate CLI/ODBC configuration keyword” on page 377
v “TraceFlush CLI/ODBC configuration keyword” on page 379
When TraceLocks is set to 1, lock timeouts will be recorded in the trace file.
This option is only used when the CLI/ODBC TRACE option is turned on.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
Each thread or process that uses the same DLL or shared library will have a
separate DB2 CLI/ODBC trace file created in the specified directory. A
concatenation of the application process ID and the thread sequence number is
automatically used to name trace files.
No trace will occur, and no error message will be returned, if the subdirectory
given is invalid or if it cannot be written to.
This option is only used when the Trace option is turned on. This will be done
automatically when you set this option in the CLI/ODBC Configuration utility.
DB2 CLI trace should only be used for debugging purposes. It will slow down the
execution of the CLI/ODBC driver, and the trace information can grow quite large
if it is left on for extended periods of time.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Trace CLI/ODBC configuration keyword” on page 375
v “TraceFileName CLI/ODBC configuration keyword” on page 378
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
When TracePIDTID is set to 1, the process ID and thread ID for each captured item
will be recorded in the trace file. This effect is helpful when the Trace keyword is
enabled and multiple applications are executing. This is because Trace writes trace
information for all executing applications to a single file. Enabling TracePIDTID
differentiates the recorded information by process and thread.
This option is only used when the CLI/ODBC Trace option is turned on.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Trace CLI/ODBC configuration keyword” on page 375
v “TraceFileName CLI/ODBC configuration keyword” on page 378
v “TraceFlush CLI/ODBC configuration keyword” on page 379
v “TracePathName CLI/ODBC configuration keyword” on page 381
v “TracePIDList CLI/ODBC configuration keyword” on page 382
Setting this keyword before an application is initialized allows you to turn off
dynamically the CLI/ODBC trace within n seconds.
Only the Trace and TracePIDList keywords will be refreshed from the db2cli.ini file
if this keyword is set. No other CLI/ODBC configuration keywords will be re-read.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Trace CLI/ODBC configuration keyword” on page 375
v “TracePIDList CLI/ODBC configuration keyword” on page 382
This option is only used when the CLI/ODBC Trace option is turned on.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
384 CLI Guide and Reference, Volume 1
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Trace CLI/ODBC configuration keyword” on page 375
v “TraceFileName CLI/ODBC configuration keyword” on page 378
v “TraceFlush CLI/ODBC configuration keyword” on page 379
v “TracePathName CLI/ODBC configuration keyword” on page 381
When TraceTime is set to 1, elapsed time counters will be captured in the trace file.
For example:
SQLPrepare( hStmt=1:1, pszSqlStr="SELECT * FROM ORG", cbSqlStr=−3 )
–––> Time elapsed – +6.785751E+000 seconds ( StmtOut="SELECT * FROM ORG" )
SQLPrepare( )
<––– SQL_SUCCESS Time elapsed – +2.527400E–002 seconds
This option is only used when the CLI/ODBC Trace option is turned on.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Trace CLI/ODBC configuration keyword” on page 375
v “TraceFileName CLI/ODBC configuration keyword” on page 378
v “TraceFlush CLI/ODBC configuration keyword” on page 379
Setting TraceTimeStamp to a value other than the default of 0 means the current
timestamp or absolute execution time is added to the beginning of each line of
trace information as it is being written to the DB2 CLI trace file. The following
settings indicate what type of timestamp information is captured in the trace file:
v 0 = no timestamp information
v 1 = processor ticks and ISO timestamp (absolute execution time in seconds and
milliseconds, followed by a timestamp)
v 2 = processor ticks (absolute execution time in seconds and milliseconds)
v 3 = ISO timestamp
This option is only used when the CLI/ODBC Trace option is turned on.
(This option is contained in the Common section of the initialization file and
therefore applies to all connections to DB2.)
Related concepts:
v “CLI/ODBC/JDBC trace facility” on page 189
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Trace CLI/ODBC configuration keyword” on page 375
v “TraceFileName CLI/ODBC configuration keyword” on page 378
v “TraceFlush CLI/ODBC configuration keyword” on page 379
v “TracePathName CLI/ODBC configuration keyword” on page 381
v “TraceTime CLI/ODBC configuration keyword” on page 385
In the case where a third party application is involved and the prompt
level used by the application is something other than
SQL_DRIVER_NO_PROMPT, DB2 CLI will open a dialog to request the
missing information from the user. Setting Trusted_Connection to Yes, by
providing it to the input connection string for SQLDriverConnect()
(“Trusted_Connection=Yes”), causes DB2 CLI to ignore any user ID or
password string (including blank strings) from the connection string and
ignore the prompt level of the connection function. DB2 CLI will use the
current authenticated user to attempt the connection to the database. If the
connection attempt fails, the user will be prompted for the user ID and
password.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Kerberos authentication details” in Administration Guide: Implementation
The words in parentheses are IBM’s terminology for the equivalent SQL92 isolation
levels. Note that no commit is not an SQL92 isolation level and is supported only
on DB2 Universal Database for AS/400.
This keyword is only applicable if the default isolation level is used. If the
application specifically sets the isolation level for a connection or statement handle,
then this keyword will have no effect on that handle.
Related concepts:
v “db2cli.ini initialization file” on page 277
v “Isolation levels” in SQL Reference, Volume 1
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “Statement attributes (CLI) list” in Call Level Interface Guide and Reference, Volume
2
The specified userid value is used if a userid is not provided by the application at
connect time.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “PWD CLI/ODBC configuration keyword” on page 357
This keyword applies only to the following catalog functions that accept search
patterns as arguments:
v SQLColumnPrivileges()
v SQLColumns()
v SQLProcedureColumns()
v SQLProcedures()
v SQLTablePrivileges()
v SQLTables()
Note that catalog functions may only accept search patterns on particular
arguments. Refer to the documentation of the specific function for details.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “SQLColumnPrivileges function (CLI) - Get privileges associated with the
columns of a table” in Call Level Interface Guide and Reference, Volume 2
v “SQLColumns function (CLI) - Get column information for a table” in Call Level
Interface Guide and Reference, Volume 2
v “SQLProcedureColumns function (CLI) - Get input/output parameter
information for a procedure” in Call Level Interface Guide and Reference, Volume 2
v “SQLProcedures function (CLI) - Get list of procedure names” in Call Level
Interface Guide and Reference, Volume 2
v “SQLTablePrivileges function (CLI) - Get privileges associated with a table” in
Call Level Interface Guide and Reference, Volume 2
v “SQLTables function (CLI) - Get table information” in Call Level Interface Guide
and Reference, Volume 2
Prior to DB2 UDB Version 8, the invoker of a procedure had to have EXECUTE
privilege on any package invoked from the procedure. Now, the invoker must have
EXECUTE privilege on the procedure and only the definer of the procedure has to
have EXECUTE privilege on any required packages.
This keyword controls which method is used to invoke the procedure. Setting
UseOldStpCall on causes the procedure to be invoked using the deprecated
sqleproc() API when the precompiler fails to resolve a procedure on a CALL
statement. Turning this keyword off will invoke procedures where GRANT
EXECUTE must be granted on the procedure.
Related concepts:
v “db2cli.ini initialization file” on page 277
Related tasks:
v “Calling stored procedures from CLI applications” on page 113
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
v “ServerMsgMask CLI/ODBC configuration keyword” on page 366
v “Connection attributes (CLI) list” in Call Level Interface Guide and Reference,
Volume 2
Related concepts:
v “db2cli.ini initialization file” on page 277
Related reference:
For example, if you wanted a BOM and minimal XML declaration (without an
encoding attribute) to be generated during implicit serialization, you would set
XMLDeclaration = 3, where 3 is the sum of 1 (the value to indicate generation of a
BOM) and 2 (the value to indicate generation of a minimal XML declaration).
Related concepts:
v “db2cli.ini initialization file” on page 277
v “XML data encoding” in XML Guide
v “XML data handling in CLI applications - Overview” on page 117
v “XML data type” in XML Guide
Related reference:
v “CLI/ODBC configuration keywords listing by category” on page 279
This chapter describes the data conversions supported in CLI, along with the
details of SQL to C and C to SQL data type conversions.
The first column contains the data type of the SQL data type. The remaining
columns represent the C data types. If the C data type columns contain:
D The conversion is supported and this is the default conversion for the SQL
data type.
X all IBM DBMSs support the conversion.
blank no IBM DBMS supports the conversion.
As an example, the table indicates that an SQLCHAR (or a C character) string can
be converted into an SQL_C_LONG (a signed long). In contrast, an SQLINTEGER
cannot be converted to an SQL_C_DBCHAR.
Refer to the tables of data type attributes (precision, scale, length, and display) for
more information on the data type formats.
Table 27. Supported data conversions
S S
Q Q
L S S L
S _ Q Q _
Q S C L L C
L S Q S S _ _ _ _
S S _ Q L Q Q T S C C D
S Q Q S S S C L _ L L Y Q _ _ B
S Q L L S S Q Q S Q _ _ C _ _ P L S C B C
S Q L _ _ S Q Q S S L L S Q L D C _ C C E _ Q L L L
S Q L _ C C Q L L S Q Q _ _ Q L _ E _ D _ _ _ C L O O O
Q L _ S C _ _ L _ _ Q L L C C L _ C C D E T T T _ _ B B B
L _ C Q _ S U _ C C L _ _ _ _ _ C _ I E C Y Y I D C _ _ _
_ C _ L T T T C _ _ _ C C S U C _ N M C I P P M A _ L L L
C _ D _ I I I _ S U C _ _ B B _ D U A I M E E E T B O O O
_ W B C N N N S S S _ S U I I F O M L M A _ _ S A I C C C
C C C _ Y Y Y H H H L L L G G L U E _ A L D T T L N A A A
H H H B I I I O O O O O O I I O B R I L 1 A I A I A T T T
SQL A A A I N N N R R R N N N N N A L I B 6 2 T M M N R O O O
data type R R R T T T T T T T G G G T T T E C M 4 8 E E P K Y R R R
SQL_CHAR D X X X X X X X X X X X X X X X X X X X X X X
4
SQL_WCHAR D X X X X X X X X X X X X X X X X X X X X X X
SQL_ D X X X X X X X X X X X X X X X X X X X X X X
VARCHAR
SQL_ D X X X X X X X X X X X X X X X X X X X X X X
WVARCHAR4
SQL_ D X X X X X X X X X X X X X X X X X X X X X X
LONG
VARCHAR
Notes:
1. The C type SQL_C_TINYINT is treated by DB2 CLI as the type
SQL_C_STINYINT so either type can be considered to be the default.
2. The C type SQL_C_SHORT is treated by DB2 CLI as the type SQL_C_SSHORT
so either type can be considered to be the default.
3. The C type SQL_C_LONG is treated by DB2 CLI as the type SQL_C_SLONG so
either type can be considered to be the default.
4. This type is not supported in the DB2 database but other supported types can
be returned to the client as this type because of the setting of a configuration
keyword, such as MAPCharToWChar
Related concepts:
v “Data types and data conversion in CLI applications” on page 39
Related reference:
v “C data types for CLI applications” on page 43
v “C to SQL data conversion in CLI” on page 406
v “SQL symbolic and default data types for CLI applications” on page 41
v “SQL to C data conversion in CLI” on page 399
The tables list the conversions defined by ODBC to be valid for a given SQL data
type.
If the fCType argument contains a value shown in the table but which specifies a
conversion not supported by the driver, SQLFetch(), or SQLGetData() returns
SQLSTATE HYC00 (Driver not capable).
When SQL data is converted to character C data, the character count returned in
pcbValue does not include the null termination byte. If rgbValue is a null pointer,
SQLBindCol() or SQLGetData() returns SQLSTATE HY009 (Invalid argument value).
When converting to floating point values, SQLSTATE 22003 will not be returned if
non-significant digits of the resulting value are lost.
Notes:
1. SQLSTATE 00000 is not returned by SQLGetDiagRec(), rather it is indicated when the
function returns SQL_SUCCESS.
2. Length of data includes any XML declaration in the target encoding.
When the date SQL data type is converted to the character C data type, the
resulting string is in the "yyyy-mm-dd” format.
When the time SQL data type is converted to the character C data type, the
resulting string is in the "hh:mm:ss” format.
SQLSTATE 00000 is not returned by SQLGetDiagRec(), rather it is indicated when the function returns
SQL_SUCCESS.
Related concepts:
v “XML data type” in XML Guide
Related reference:
v “C data types for CLI applications” on page 43
v “C to SQL data conversion in CLI” on page 406
v “Data conversions supported in CLI” on page 397
v “Patch2 CLI/ODBC configuration keyword” on page 352
v “SQL symbolic and default data types for CLI applications” on page 41
The tables list the conversions defined by ODBC to be valid for a given SQL data
type.
If the fSqlType argument contains a value shown in the table but which specifies a
conversion not supported by the driver, SQLBindParameter() or SQLSetParam()
returns SQLSTATE HYC00 (Driver not capable).
Note: a The date component of TIMESTAMP is set to the system date of the machine at
which the application is running.
Related reference:
v “C data types for CLI applications” on page 43
v “Data conversions supported in CLI” on page 397
v “SQL symbolic and default data types for CLI applications” on page 41
v “SQL to C data conversion in CLI” on page 399
IBM periodically makes documentation updates available. If you access the online
version on the DB2 Information Center at ibm.com®, you do not need to install
documentation updates because this version is kept up-to-date by IBM. If you have
installed the DB2 Information Center, it is recommended that you install the
documentation updates. Documentation updates allow you to update the
information that you installed from the DB2 Information Center CD or downloaded
from Passport Advantage as new information becomes available.
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 Redbooks™ 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 we can improve the DB2 documentation, send an e-mail 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 e-mail 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.
Related tasks:
v “Invoking command help from the command line processor” in Command
Reference
v “Invoking message help from the command line processor” in Command
Reference
v “Updating the DB2 Information Center installed on your computer or intranet
server” on page 421
Related reference:
v “DB2 technical library in hardcopy or PDF format” on page 416
Although the tables identify books available in print, the books might not be
available in your country or region.
The information in these books is fundamental to all DB2 users; you will find this
information useful whether you are a programmer, a database administrator, or
someone who works with DB2 Connect or other DB2 products.
Table 45. DB2 technical information
Name Form Number Available in print
Administration Guide: SC10-4221 Yes
Implementation
Administration Guide: Planning SC10-4223 Yes
Administrative API Reference SC10-4231 Yes
Administrative SQL Routines and SC10-4293 No
Views
Call Level Interface Guide and SC10-4224 Yes
Reference, Volume 1
Call Level Interface Guide and SC10-4225 Yes
Reference, Volume 2
Command Reference SC10-4226 No
Data Movement Utilities Guide SC10-4227 Yes
and Reference
Data Recovery and High SC10-4228 Yes
Availability Guide and Reference
Developing ADO.NET and OLE SC10-4230 Yes
DB Applications
Developing Embedded SQL SC10-4232 Yes
Applications
Note: The DB2 Release Notes provide additional information specific to your
product’s release and fix pack level. For more information, see the related
links.
Related concepts:
v “Overview of the DB2 technical information” on page 415
v “About the Release Notes” in Release notes
Related tasks:
v “Ordering printed DB2 books” on page 418
Printed versions of many of the DB2 books available on the DB2 PDF
Documentation CD 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 CD are available in print.
Procedure:
Related concepts:
v “Overview of the DB2 technical information” on page 415
Related reference:
v “DB2 technical library in hardcopy or PDF format” on page 416
Procedure:
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.
Related tasks:
v “Invoking command help from the command line processor” in Command
Reference
v “Invoking message help from the command line processor” in Command
Reference
For DB2 Version 8 topics, go to the Version 8 Information Center URL at:
http://publib.boulder.ibm.com/infocenter/db2luw/v8/.
Related tasks:
v “Updating the DB2 Information Center installed on your computer or intranet
server” on page 421
Procedure:
Note: Adding a language does not guarantee that the computer has the fonts
required to display the topics in the preferred language.
v 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 determine if there is an update available for the entire DB2 Information Center,
look for the 'Last updated' value on the Information Center home page. Compare
the value in your locally installed home page to the date of the most recent
downloadable update at http://www.ibm.com/software/data/db2/udb/support/
icupdate.html. You can then update your locally-installed Information Center if a
more recent downloadable update is available.
Note: Updates are also available on CD. For details on how to configure your
Information Center to install updates from CD, see the related links.
If update packages are available, use the Update feature to download the
packages. (The Update feature is only available in stand-alone mode.)
3. Stop the stand-alone Information Center, and restart the DB2 Information
Center service on your computer.
Procedure:
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, run the help_end script using the fully qualified path for the DB2
Information Center:
<DB2 Information Center dir>/doc/bin/help_end
Related concepts:
v “DB2 Information Center installation options” in Quick Beginnings for DB2 Servers
Related tasks:
v “Installing the DB2 Information Center using the DB2 Setup wizard (Linux)” in
Quick Beginnings for DB2 Servers
v “Installing the DB2 Information Center using the DB2 Setup wizard (Windows)”
in Quick Beginnings for DB2 Servers
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:
Related concepts:
v “Visual Explain overview” in Administration Guide: Implementation
Related concepts:
v “Introduction to problem determination” in Troubleshooting Guide
v “Overview of the DB2 technical information” on page 415
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 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:
IBM Director of Licensing
IBM Corporation
North Castle Drive
Armonk, NY 10504-1785
U.S.A.
For license inquiries regarding double-byte (DBCS) information, contact the IBM
Intellectual Property Department in your country/region or send inquiries, in
writing, to:
IBM World Trade Asia Corporation
Licensing
2-31 Roppongi 3-chome, Minato-ku
Tokyo 106, Japan
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.
Any references in this information to non-IBM Web sites are provided for
convenience only and do not in any manner serve as an endorsement of those Web
sites. The materials at those Web sites are not part of the materials for this IBM
product, and use of those Web sites is at your own risk.
IBM may use or distribute any of the information you supply in any way it
believes appropriate without incurring any obligation to you.
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:
Trademarks
Company, product, or service names identified in the documents of the DB2
Version 9 documentation library may be trademarks or service marks of
International Business Machines Corporation or other companies. Information on
the trademarks of IBM Corporation in the United States, other countries, or both is
located at http://www.ibm.com/legal/copytrade.shtml.
Microsoft, Windows, Windows NT®, and the Windows logo are trademarks of
Microsoft Corporation in the United States, other countries, or both.
Intel, Itanium®, Pentium®, and Xeon® are trademarks of Intel Corporation in the
United States, other countries, or both.
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
This book incorporates text which is copyright 1992, 1993, 1994, 1997 by Microsoft
Corporation. The text was taken by permission from Microsoft’s ODBC 2.0
Programmer’s Reference and SDK Guide ISBN 1-55615-658-8, and from Microsoft’s
ODBC 3.0 Software Development Kit and Programmer’s Reference ISBN 1-57231-516-4.
Index 433
CLI/ODBC keywords (continued) COT scalar function
TraceRefreshInterval 383 for CLI applications 174
TraceStmtOnly 384 CURDATE scalar function 174
TraceTime 385 CurrentFunctionPath CLI/ODBC configuration keyword 302
TraceTimestamp 386 CurrentImplicitXMLParseOption CLI/ODBC configuration
Trusted_Connection 386 keyword 302
TxnIsolation 388 CurrentMaintainedTableTypesForOpt CLI/ODBC
UID 388 configuration keyword 303
Underscore 389 CurrentPackagePath CLI/ODBC configuration keyword 304
UseOldStpCall 390 CurrentPackageSet CLI/ODBC configuration keyword 305
UseServerMsgSP 391 CurrentRefreshAge CLI/ODBC configuration keyword 306
WarningList 391 CurrentSchema CLI/ODBC configuration keyword 306
XMLDeclaration 392 CurrentSQLID CLI/ODBC configuration keyword 306
CLI/ODBC/JDBC CursorHold CLI/ODBC configuration keyword 307
static profiling cursors
capture file 187 CLI (call level interface)
creating static SQL 185 bookmarks 78
trace considerations 65
facility 189 selection 68
files 194 dynamic scrollable 65
ClientAcctStr CLI/ODBC configuration keyword 294 holding across rollbacks 55
ClientApplName CLI/ODBC configuration keyword 295 scrollable
ClientBuffersUnboundLOBS CLI/ODBC configuration retrieving data with in CLI 76
keyword 296 CursorTypes CLI/ODBC configuration keyword 308
ClientUserID CLI/ODBC configuration keyword 297 CURTIME scalar function 174
ClientWrkStnName CLI/ODBC configuration keyword 298
CLIPkg CLI/ODBC configuration keyword 299
CLOB (character large object)
data type
D
data
CLI applications 96
conversions
conversion to C 399
CLI 397
column binding offsets 91
data conversion
column-wise binding 89
C data types 41
columns
C to SQL data types 406
binding, in CLI 85
data types 39
commit
default data types 41
behavior
description 39
in CLI stored procedures 115
SQL data types 41
transactions 30
SQL to C data types 399
compound SQL
data retrieval
CLI
in pieces, CLI 95
executing in 123
data types
return codes 125
C language 41
CONCAT scalar function
C, in CLI 43
CLI 174
conversion
concise descriptor functions 160
CLI 397
connections
SQL 41
attributes
Database CLI/ODBC configuration keyword 309
changing 163
DATABASE scalar function 174
connection strings 163
DATE SQL data type
multiple 55
conversion to C 399
ConnectNode CLI/ODBC configuration keyword 299
DateTimeStringFormat CLI/ODBC configuration
ConnectTimeout CLI/ODBC configuration keyword 300
keyword 310
ConnectType CLI/ODBC configuration keyword 301
DAYNAME scalar function
contacting IBM 433
for CLI applications 174
conversions
DAYOFMONTH scalar function 174
data types, in CLI 397
DAYOFWEEK scalar function
CONVERT scalar function 174
for CLI applications 174
coordinated transactions
DAYOFWEEK_ISO scalar function
distributed 137
for CLI applications 174
establishing 138
DAYOFYEAR scalar function 174
copying
DB2
descriptors
as transaction manager 138
in CLI applications 158
DB2 CLI
core level functions 3
sample program files 235
COS scalar function
DB2 copies
for CLI applications 174
CLI/ODBC applications 217
Index 435
drivers
CLI 7, 9
I
manager 9 IBM DB2 Driver for ODBC and CLI
ODBC 7, 9 CLI trace 266
DSN CLI/ODBC keyword 323 configuring 249
DTC environment variables 250
registering XA library with Microsoft DTC 253
db2oreg1.exe 252 Microsoft ODBC driver manager 254
registering ODBC data sources 259
connecting to databases 257
DB2 registry variables
E supported as environment variables 251
embedded SQL DB2 trace 266
compared with CLI 4 db2diag.log 266
mixing with DB2 CLI 183 db2support 266
Encina, running applications on 141 deploying with applications 269
environment attributes environment variables 251
changing 163 installing 245
ESCAPE clauses multiple copies 246
vendor 171 with an existing client 247
examples LDAP support 265
distinct types license requirements 270
CLI applications 147 obtaining 243
executing overview 241
SQL in CLI 24 problem determination and investigation 266
EXP scalar function 174 registering ODBC data sources 259
restrictions 266
running applications 263
F supported DB2 CLI and ODBC functions 264
fetching supported XA functions 265
LOB data in CLI 99 uninstalling 273
File DSN IFNULL scalar function 174
database to connect 309 IgnoreWarnings CLI/ODBC configuration keyword 327
host name 327 IgnoreWarnList CLI/ODBC configuration keyword 328
IP address 327 implementation parameter descriptor (IPD) 151
protocol used 356 implementation row descriptor (IRD) 151
service name 366 importing
file input/output for LOB data in CLI 101 data
FileDSN CLI/ODBC keyword 323 with the CLI LOAD utility 110
FLOAT SQL data type IN DATABASE statement 314
conversion to C 399 Information Center
FloatPrecRadix CLI/ODBC configuration keyword 324 updating 421
FLOOR scalar function 174 versions 420
freeing CLI handles viewing in different languages 420
in CLI application 38 INI file
freeing statement resources in CLI 37 db2cli.ini 277
initialization
task 17
initialization file
G purpose 163
GranteeList CLI/ODBC configuration keyword 324 initializing
GrantorList CLI/ODBC configuration keyword 325 CLI applications 18
Graphic CLI/ODBC configuration keyword 326 INSERT scalar function 174
GRAPHIC SQL data type inserting data
conversion to C 399 XML
CLI applications 118
Instance CLI/ODBC keyword 328
H INTEGER SQL data type
handles conversion to C 399
descriptor 151 Interrupt CLI/ODBC keyword 329
freeing 38 INVALID_HANDLE 50
types 15 IPD descriptor 151
help IRD descriptor 151
displaying 420 isolation levels
for SQL statements 419 ODBC 9
Hostname CLI/ODBC configuration keyword 327 issuing SQL in CLI 23
HOUR scalar function 174
Index 437
ODBC (continued) prepared SQL statements
IBM DB2 Driver for ODBC and CLI (continued) in CLI applications
obtaining 243 creating 24
overview 241 printed books
problem determination and investigation 266 ordering 418
registering ODBC data sources 259 problem determination
restrictions 266 online information 423
running database applications 263 tutorials 423
supported CLI and ODBC functions 264 process-based transaction manager 141
supported XA functions 265 ProgramName CLI/ODBC configuration keyword 356
uninstalling 273 Protocol CLI/ODBC configuration keyword 356
registering ODBC data sources PWD CLI/ODBC configuration keyword 357
IBM DB2 Driver for ODBC and CLI 259 PWDPlugin CLI/ODBC keyword 358
ODBC (open database connectivity)
and DB2 CLI 3, 9
core level functions 3
isolation levels 9
Q
QUARTER scalar function 174
setting up UNIX environment 210
queries
vendor escape clauses 171
system catalog information 167
offsets
QueryTimeoutInterval CLI/ODBC configuration
binding columns 91
keyword 358
changing parameter bindings 84
OleDbReportIsLongForLongTypes CLI/ODBC configuration
keyword 347
OleDbReturnCharAsWChar CLI/ODBC configuration R
keyword 348 RADIANS scalar function
OleDbSQLColumnsSortByOrdinal CLI/ODBC configuration in CLI applications 174
keyword 348 RAND scalar function
OptimizeForNRows CLI/ODBC configuration keyword 349 in CLI applications 174
options ReadCommonSectionOnNullConnect CLI/ODBC configuration
connection 163 keyword 359
environment 163 REAL SQL data type
querying and setting 163 conversion
statement 163 to C data type 399
ordering DB2 books 418 ReceiveTimeout CLI/ODBC configuration keyword 360
reentrance 133
Reopt CLI/ODBC configuration keyword 360
P REPEAT scalar function
list 174
package names
REPLACE scalar function
and binding 203
list 174
packages
ReportPublicPrivileges CLI/ODBC configuration
and bind option limitations 205
keyword 362
parallelism
ReportRetryErrorsAsWarnings CLI/ODBC configuration
setting degree of 311
keyword 361
parameter markers
result sets
binding
specifying rowset returned from, in CLI 73
column-wise array input, in CLI 81
terminology, CLI 70
in CLI applications 26, 29
RetCatalogAsCurrServer CLI/ODBC configuration
row-wise array input, in CLI 82
keyword 362
changing bindings 84
RetOleDbConnStr CLI/ODBC configuration keyword 363
parameter status array, CLI 83
retrieving data
parameters
array
diagnostics, in CLI 83
column-wise binding 89
parsing
row-wise binding 90
explicit
bulk, with bookmarks in CLI 105
CLI applications 118
CLI 87
implicit
in pieces, CLI 95
CLI applications 118
with bookmarks in CLI 79
Patch1 CLI/ODBC configuration keyword 350
with scrollable cursors, in CLI 76
Patch2 CLI/ODBC configuration keyword 352
XML
pattern values 168
CLI applications 119
performance
retrieving query results
CLI array input chaining 62
CLI 33
PI scalar function 174
retrieving row sets
Port CLI/ODBC configuration keyword 355
CLI examples 71
POWER scalar function
RetryOnError CLI/ODBC configuration keyword 364
list 174
Index 439
SQL_ATTR_ (continued) SQLEndTran CLI function 32
TXN_ISOLATION SQLError CLI function 144
TxnIsolation 388 SQLErrorW CLI function 144
SQL_C_BINARY 406 SQLExecDirect CLI function
SQL_C_BIT 406 overview 20
SQL_C_CHAR 406 Unicode version 144
SQL_C_DATE 406 SQLExecDirectW CLI function 144
SQL_C_DBCHAR 406 SQLExecute CLI function
SQL_C_DOUBLE 406 overview 20
SQL_C_FLOAT 406 SQLExtendedPrepare CLI function
SQL_C_LONG 406 Unicode version 144
SQL_C_SHORT 406 SQLExtendedPrepareW CLI function 144
SQL_C_TIME 406 SQLFetch CLI function
SQL_C_TIMESTAMP 406 overview 20
SQL_C_TINYINT 406 SQLForeignKeys CLI function
SQL_CONCURRENT_TRANS 138 Unicode version 144
SQL_COORDINATED_TRANS 138 SQLForeignKeysW CLI function 144
SQL_ERROR 50 SQLFreeStmt CLI function
SQL_NEED_DATA 50 overview 20
SQL_NO_DATA_FOUND 50 SQLGetConnectAttr CLI function
SQL_NTS 47 Unicode version 144
SQL_ONEPHASE 138 SQLGetConnectAttrW CLI function 144
SQL_STILL_EXECUTING 50 SQLGetConnectOption CLI function 144
SQL_SUCCESS 50 SQLGetConnectOptionW CLI function 144
SQL_SUCCESS_WITH_INFO 50 SQLGetCursorName CLI function
SQL_TWOPHASE 138 Unicode version 144
SQLAllocStmt deprecated CLI function 20 SQLGetCursorNameW CLI function 144
SQLBindCol CLI function 20 SQLGetData CLI function
SQLBindParameter function 26 overview 20
SQLBrowseConnect CLI function SQLGetDescField CLI function
Unicode version 144 Unicode version 144
SQLBrowseConnectW CLI function 144 SQLGetDescFieldW CLI function 144
SQLBulkOperations CLI function SQLGetDescRec CLI function
deleting bulk data 109 Unicode version 144
inserting bulk data 106 SQLGetDescRecW CLI function 144
retrieving bulk data 105 SQLGetDiagField CLI function
updating bulk data 107 Unicode version 144
SQLColAttribute CLI function SQLGetDiagFieldW CLI function 144
Unicode version 144 SQLGetDiagRec CLI function
SQLColAttributes CLI function Unicode version 144
overview 20 SQLGetDiagRecW CLI function 144
Unicode version 144 SQLGetInfo CLI function
SQLColAttributesW CLI function 144 Unicode version 144
SQLColAttributeW CLI function 144 SQLGetInfoW CLI function 144
SQLColumnPrivileges CLI function SQLGetStmtAttr CLI function
Unicode version 144 Unicode version 144
SQLColumnPrivilegesW CLI function 144 SQLGetStmtAttrW CLI function 144
SQLColumns CLI function SQLNativeSql CLI function
Unicode version 144 Unicode version 144
SQLColumnsW CLI function 144 SQLNativeSqlW CLI function 144
SQLConnect CLI function SQLNumResultCols CLI function
Unicode version 144 overview 20
SQLConnectW CLI function 144 SQLOverrideFileName CLI/ODBC configuration
SQLDataSources CLI function keyword 368
overview 20 SQLPrepare CLI function
Unicode version 144 overview 20
SQLDataSourcesW CLI function 144 Unicode version 144
SQLDescribeCol CLI function SQLPrepareW CLI function 144
overview 20 SQLPrimaryKeys CLI function
Unicode version 144 Unicode version 144
SQLDescribeColW CLI function 144 SQLPrimaryKeysW CLI function 144
SQLDriverConnect CLI function SQLProcedureColumns CLI function
default values 163 Unicode version 144
Trusted_connection CLI/ODBC configuration SQLProcedureColumnsW CLI function 144
keyword 386 SQLProcedures CLI function
Unicode version 144 Unicode version 144
SQLDriverConnectW CLI function 144 SQLProceduresW CLI function 144
Index 441
units of work (UOW) XML serialization
distributed 30 CLI applications 117, 119
UNIX XMLDeclaration CLI/ODBC configuration keyword 392
setting up ODBC environment 210
unixODBC driver manager
build scripts 213
configurations 213
Y
YEAR scalar function
setting up 212
list 174
updates
bulk data, with bookmarks in CLI 107
data in CLI 35
DB2 Information Center 421
Information Center 421
UseOldStpCall CLI/ODBC configuration keyword 390
USER scalar function 174
user-defined types (UDTs)
in CLI 148
UseServerMsgSP CLI/ODBC configuration keyword 391
V
VARBINARY SQL data type
conversion to C 399
VARCHAR data type
conversion to C 399
VARGRAPHIC data type
conversion to C 399
vendor escape clauses 171
Visual Explain
tutorial 423
W
WarningList CLI/ODBC configuration keyword 391
WEEK scalar function
listed 174
WEEK_ISO scalar function
listed 174
Windows
CLI environment 215
setting up CLI environment 215
X
X/Open CAE 51
X/Open Company 3
X/Open SQL CLI 3
XA
IBM DB2 Driver for ODBC and CLI 265
registering XA library with DTC 252
XML
declarations
CLI applications 117
XML data
CLI applications 117
inserting 118
retrieval 119
updating 118
XML data retrieval
CLI applications 119
XML data type
CLI applications 117
XML declarations
CLI applications 117
XML parsing
CLI applications 118
Printed in USA
SC10-4224-00
Spine information: