SQL Call Level Interface
SQL Call Level Interface
SQL Call Level Interface
IBM i
Database
SQL call level interface
7.1
IBM i
Database
SQL call level interface
7.1
Note
Before using this information and the product it supports, read the information in “Notices,” on
page 321.
This edition applies to IBM i 7.1 (product number 5770-SS1) and to all subsequent releases and modifications until
otherwise indicated in new editions. This version does not run on all reduced instruction set computer (RISC)
models nor does it run on CISC models.
© Copyright IBM Corporation 1999, 2010.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract
with IBM Corp.
Contents
SQL call level interface . . . . . . . . 1 SQLExecute - Execute a statement . . . . . 103
What's new for IBM i 7.1 . . . . . . . . . . 1 SQLExtendedFetch - Fetch array of rows . . . 105
PDF file for SQL call level interface . . . . . . . 1 SQLFetch - Fetch next row . . . . . . . . 107
Getting started with DB2 for i CLI . . . . . . . 2 SQLFetchScroll - Fetch from a scrollable cursor 113
| Differences between DB2 for i CLI and embedded SQLForeignKeys - Get the list of foreign key
| SQL . . . . . . . . . . . . . . . . 2 columns . . . . . . . . . . . . . . 115
Advantages of using DB2 for i CLI instead of SQLFreeConnect - Free connection handle . . . 120
embedded SQL . . . . . . . . . . . . 5 SQLFreeEnv - Free environment handle . . . 121
Deciding between DB2 for i CLI, dynamic SQL, SQLFreeHandle - Free a handle . . . . . . 122
and static SQL . . . . . . . . . . . . . 6 SQLFreeStmt - Free (or reset) a statement handle 123
Writing a DB2 for i CLI application . . . . . . . 6 SQLGetCol - Retrieve one column of a row of
Initialization and termination tasks in a DB2 for i the result set . . . . . . . . . . . . 125
CLI application . . . . . . . . . . . . 7 SQLGetConnectAttr - Get the value of a
Transaction processing task in a DB2 for i CLI connection attribute . . . . . . . . . . 131
application . . . . . . . . . . . . . 10 SQLGetConnectOption - Return current setting
Diagnostics in a DB2 for i CLI application . . . 16 of a connect option . . . . . . . . . . 132
Data types and data conversion in DB2 for i CLI SQLGetCursorName - Get cursor name. . . . 134
functions . . . . . . . . . . . . . . 18 SQLGetData - Get data from a column . . . . 138
Working with the XML data type . . . . . . 19 SQLGetDescField - Get descriptor field . . . . 139
Working with string arguments in DB2 for i CLI SQLGetDescRec - Get descriptor record . . . 142
functions . . . . . . . . . . . . . . 21 SQLGetDiagField - Return diagnostic
DB2 for i CLI functions . . . . . . . . . . 22 information (extensible) . . . . . . . . . 144
Categories of DB2 for i CLI functions . . . . . 23 SQLGetDiagRec - Return diagnostic information
SQLAllocConnect - Allocate connection handle 26 (concise) . . . . . . . . . . . . . . 147
SQLAllocEnv - Allocate environment handle . . 29 SQLGetEnvAttr - Return current setting of an
SQLAllocHandle - Allocate handle. . . . . . 32 environment attribute . . . . . . . . . 150
SQLAllocStmt - Allocate a statement handle . . 33 SQLGetFunctions - Get functions . . . . . . 151
SQLBindCol - Bind a column to an application SQLGetInfo - Get general information . . . . 154
variable. . . . . . . . . . . . . . . 35 SQLGetLength - Retrieve length of a string
SQLBindFileToCol - Bind LOB file reference to value . . . . . . . . . . . . . . . 166
LOB column . . . . . . . . . . . . . 40 SQLGetPosition - Return starting position of
SQLBindFileToParam - Bind LOB file reference to string . . . . . . . . . . . . . . . 168
LOB parameter . . . . . . . . . . . . 43 SQLGetStmtAttr - Get the value of a statement
SQLBindParam - Bind a buffer to a parameter attribute . . . . . . . . . . . . . . 171
marker . . . . . . . . . . . . . . . 46 SQLGetStmtOption - Return current setting of a
SQLBindParameter - Bind a parameter marker to statement option . . . . . . . . . . . 173
a buffer. . . . . . . . . . . . . . . 51 SQLGetSubString - Retrieve portion of a string
SQLCancel - Cancel statement . . . . . . . 60 value . . . . . . . . . . . . . . . 175
SQLCloseCursor - Close cursor statement . . . 61 SQLGetTypeInfo - Get data type information 178
SQLColAttribute - Return a column attribute . . 62 SQLLanguages - Get SQL dialect or
SQLColAttributes - Obtain column attributes . . 68 conformance information . . . . . . . . 183
SQLColumnPrivileges - Get privileges associated SQLMoreResults - Determine whether there are
with the columns of a table . . . . . . . . 69 more result sets . . . . . . . . . . . 185
SQLColumns - Get column information for a SQLNativeSql - Get native SQL text . . . . . 187
table . . . . . . . . . . . . . . . . 72 SQLNextResult - Process the next result set . . 189
SQLConnect - Connect to a data source . . . . 76 SQLNumParams - Get number of parameters in
SQLCopyDesc - Copy description statement . . 79 an SQL statement . . . . . . . . . . . 191
SQLDataSources - Get list of data sources . . . 80 SQLNumResultCols - Get number of result
SQLDescribeCol - Describe column attributes . . 84 columns . . . . . . . . . . . . . . 193
SQLDescribeParam - Return description of a SQLParamData - Get next parameter for which
parameter marker . . . . . . . . . . . 88 a data value is needed . . . . . . . . . 195
SQLDisconnect - Disconnect from a data source 90 SQLParamOptions - Specify an input array for a
SQLDriverConnect - Connect to a data source . . 92 parameter . . . . . . . . . . . . . 197
SQLEndTran - Commit or roll back a transaction 96 SQLPrepare - Prepare a statement . . . . . 199
SQLError - Retrieve error information . . . . 98 SQLPrimaryKeys - Get primary key columns of
SQLExecDirect - Execute a statement directly 101 a table . . . . . . . . . . . . . . . 203
A callable SQL interface is a programming interface (API) for database access that uses function calls to run
dynamic SQL statements.
DB2 for i CLI is an alternative to embedded dynamic SQL. The important difference between embedded
dynamic SQL and DB2 for i CLI is how the SQL statements are run. On the IBM® i operating system, this
interface is available to any of the Integrated Language Environment® (ILE) languages.
DB2 for i CLI also provides full Level 1 Microsoft Open Database Connectivity (ODBC) support, plus
many Level 2 functions. For the most part, ODBC is a superset of the American National Standards
Institute (ANSI) and ISO SQL CLI standard.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
To help you see where technical changes have been made, this information uses:
v The image to mark where new or changed information begins.
v The image to mark where new or changed information ends.
In PDF files, you might see revision bars (|) in the left margin of new and changed information.
To find other information about what's new or changed this release, see the Memo to users.
| To view or download the PDF version of this document, select SQL call level interface (about 1048 KB).
You need Adobe Reader installed on your system to view or print these PDFs. You can download a free
copy from the Adobe Web site (http://get.adobe.com/reader/).
It is important to understand what DB2 for i CLI, or any callable SQL interface, is based on, and compare
it with existing interfaces.
ISO standard 9075:1999 – Database Language SQL Part 3: Call-Level Interface provides the standard
definition of CLI. The goal of this interface is to increase the portability of applications by enabling them
to become independent of any one database server.
ODBC provides a Driver Manager for Windows, which offers a central point of control for each ODBC
driver (a dynamic link library (DLL) that implements ODBC function calls and interacts with a specific
Database Management System (DBMS)).
An FAQ, which elaborates on some items discussed in this topic collection, is available on the IBM DB2
for i5/OS™ Web site .
| An application that uses an embedded SQL interface requires a precompiler to convert the SQL
| statements into code. Code is compiled, bound to the database, and processed. In contrast, a DB2 for i
| CLI application does not require precompilation or binding, but instead uses a standard set of functions
| to run SQL statements and related services at run time.
| This difference is important because, traditionally, precompilers have been specific to a database product,
| which effectively ties your applications to that product. DB2 for i CLI enables you to write portable
| applications that are independent of any particular database product. This independence means that a
| DB2 for i CLI application does not need to be recompiled or rebound to access-different database
| products. An application selects the appropriate database products at run time.
| DB2 for i CLI and embedded SQL also differ in the following ways:
| v DB2 for i CLI does not require the explicit declaration of cursors. DB2 for i CLI generates them as
| needed. The application can then use the generated cursor in the normal cursor fetch model for
| multiple row SELECT statements and positioned UPDATE and DELETE statements.
| v The OPEN statement is not necessary in DB2 for i CLI. Instead, the processing of a SELECT automatically
| causes a cursor to be opened.
| v Unlike embedded SQL, DB2 for i CLI allows the use of parameter markers on the equivalent of the
| EXECUTE IMMEDIATE statement (the SQLExecDirect() function).
| v A COMMIT or ROLLBACK in DB2 for i CLI is issued through the SQLTransact() or SQLEndTran() function
| call rather than by passing it as an SQL statement.
| v For some statements, a corresponding connection attribute is provided as a different means of
| accomplishing the same function as running the statement would. For example, CLI provides a
| connection attribute that can be used to free locators allocated in the CLI application. This connection
| attribute is more convenient to use that the statement because it allows for an array of locators to be
| passed on the SQLSetConnectAttr() API call.
| v DB2 for i CLI manages statement-related information on behalf of the application, and provides a
| statement handle to refer to it as an abstract object. This handle avoids the need for the application to
| use product-specific data structures.
| v Similar to the statement handle, the environment handle and connection handle provide a means to refer
| to all global variables and connection specific information.
| v DB2 for i CLI uses the SQLSTATE values defined by the X/Open SQL CAE specification. Although the
| format and many of the values are consistent with values that are used by the IBM relational database
| products, there are differences.
| v CLI uses the SQLSTATE values defined by the X/Open SQL CAE specification. Although the format
| and many of the values are consistent with values that are used by the IBM relational database
| products, there are differences.
| Despite these differences, there is an important common concept between embedded SQL and DB2 for i
| CLI:
| v DB2 for i CLI can process any SQL statement that can be prepared dynamically in embedded SQL. This
| is guaranteed because DB2 for i CLI does not actually process the SQL statement itself, but passes it to
| the Database Management System (DBMS) for dynamic processing.
| Table 1 lists each SQL statement, and whether it can be processed using DB2 for i CLI.
| Table 1. SQL statements
1 3
| SQL statement Dyn CLI
| ALLOCATE CURSOR
| ALLOCATE DESCRIPTOR
| ASSOCIATE LOCATORS
| ALTER PROCEDURE X
| ALTER SEQUENCE X
| ALTER TABLE X X
2
| BEGIN DECLARE SECTION
| CALL X X
| CLOSE SQLFreeStmt()
| COMMENT ON X X
| COMMIT X SQLTransact(), SQLEndTran()
| CONNECT (Type 1) SQLConnect()
| CONNECT (Type 2) SQLConnect()
| CREATE ALIAS X
| CREATE FUNCTION X
| Each DBMS might have additional statements that can be dynamically prepared, in which case DB2 for i
| CLI passes them to the DBMS. There is one exception, COMMIT and ROLLBACK can be dynamically
| prepared by some DBMSs but are not passed. Instead, the SQLTransact() or SQLEndTran() should be used
| to specify either COMMIT or ROLLBACK.
Deciding between DB2 for i CLI, dynamic SQL, and static SQL
Which interfaces you choose depends on your application.
| DB2 for i CLI is ideally suited for query-based applications that require portability but not require the
| APIs or utilities offered by a particular Database Management System (DBMS) (for example, catalog
| database, backup, restore). This does not mean that using DB2 for i CLI calls DBMS-specific APIs from an
| application. It means that the application is no longer portable.
Another important consideration is the performance comparison between dynamic and static SQL.
Dynamic SQL is prepared at run time, while static SQL is prepared at the precompile stage. Because
preparing statements requires additional processing time, static SQL might be more efficient. If you
choose static over dynamic SQL, then DB2 for i CLI is not an option.
In most cases the choice between either interface is open to personal preference. Your previous experience
might make one alternative seem more intuitive than the other.
Every DB2 for i CLI application contains the three main tasks that are shown in the following figure. If
the functions are not called in the sequence that is shown in the figure, an error results.
The initialization task allocates and initializes resources in preparation for the main Transaction Processing
task.
The transaction processing task, the main task of the application, passes queries and modifications to the
SQL to DB2 for i CLI.
The termination task frees allocated resources. The resources generally consist of data areas that are
identified by unique handles. After freeing the resources, other tasks can use these handles.
In addition to the three central tasks that control a DB2 for i CLI application, there are numerous general
tasks, such as diagnostic message handlers, throughout an application.
See “Categories of DB2 for i CLI functions” on page 23 for an overview of how the CLI functions fit into
these key task areas.
Related concepts:
“DB2 for i CLI functions” on page 22
These DB2 for i call level interface APIs are available for database access on the IBM i operating system.
Each of the DB2 for i CLI function descriptions is presented in a consistent format.
The following figure shows the function call sequences for both the initialization and termination tasks.
The transaction processing task in the middle of the diagram is shown in “Transaction processing task in
a DB2 for i CLI application” on page 10.
| The termination task frees handles. A handle is a variable that refers to a data object that is controlled by
| CLI. . Using handles frees the application from having to allocate and manage global variables or data
| structures, such as descriptor areas, or the SQL Diagnostic Area used in embedded SQL interfaces for
| IBM Database Management Systems (DBMSs). An application then passes the appropriate handle when it
| calls other DB2 for i CLI functions. Here are the types of handles:
| Environment handle
| The environment handle refers to the data object that contains global information regarding the
| state of the application. This handle is allocated by calling SQLAllocEnv(), and freed by calling
| SQLFreeEnv(). An environment handle must be allocated before a connection handle can be
| allocated. Only one environment handle can be allocated per application.
| Connection handle
| A connection handle refers to a data object that contains information that is associated with a
| connection that is managed by DB2 for i CLI. This includes general status information,
| transaction status, and diagnostic information. Each connection handle is allocated by calling
| SQLAllocConnect() and freed by calling SQLFreeConnect(). An application must allocate a
| connection handle for each connection to a database server.
| Statement handle
| Statement handles are discussed in “Transaction processing task in a DB2 for i CLI application”
| on page 10.
| Descriptor handle
| A descriptor handle is available for applications that want to use certain CLI functions for
| reading and modifying individual bound parameter attributes on a API call basis for statements
| that have parameters or result sets associated with them. These functions can be used as
| alternatives to SQLBindCol() and SQLBindParameter() functions. See SQLGetDescField(),
| SQLGetDescRec(), SQLSetDescField(), and SQLSetDescRec() functions for more information.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*******************************************************
** file = basiccon.c
** - demonstrate basic connection to two datasources.
** - error handling ignored for simplicity
**
** Functions used:
**
** SQLAllocConnect SQLDisconnect
** SQLAllocEnv SQLFreeConnect
** SQLConnect SQLFreeEnv
**
**
********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "sqlcli.h"
int
connect(SQLHENV henv,
SQLHDBC * hdbc);
#define MAX_DSN_LENGTH 18
#define MAX_UID_LENGTH 10
#define MAX_PWD_LENGTH 10
#define MAX_CONNECTIONS 5
int
main()
{
SQLHENV henv;
SQLHDBC hdbc[MAX_CONNECTIONS];
connect(henv, &hdbc[1]);
printf("\nDisconnecting .....\n");
SQLDisconnect(hdbc[0]); /* disconnect first connection */
SQLDisconnect(hdbc[1]); /* disconnect second connection */
SQLFreeConnect(hdbc[0]); /* free first connection handle */
SQLFreeConnect(hdbc[1]); /* free second connection handle */
SQLFreeEnv(henv); /* free environment handle */
return (SQL_SUCCESS);
}
/********************************************************************
** connect - Prompt for connect options and connect **
********************************************************************/
int
connect(SQLHENV henv,
SQLHDBC * hdbc)
{
SQLRETURN rc;
SQLCHAR server[MAX_DSN_LENGTH + 1], uid[MAX_UID_LENGTH + 1],
pwd[MAX_PWD_LENGTH
+ 1];
SQLCHAR buffer[255];
SQLSMALLINT outlen;
The figure shows the steps and the DB2 for i CLI functions in the transaction processing task. This task
contains these steps:
| 1. “Allocating statement handles in a DB2 for i CLI application” on page 12
As soon as the statement is processed, the remaining processing depends on the type of SQL statement.
For SELECT statements, the program uses functions like SQLNumResultCols(), SQLDescribeCol(),
SQLBindCol(), SQLFetch(), and SQLCloseCursor() to process the result set. For statements that update
data, SQLRowCount()can be used to determine the number of affected rows. For other types of SQL
statements, the processing is complete after the statement is processed. SQLFreeStmt()is then used in all
cases to indicate that the handle is no longer needed.
The information about an SQL statement that is managed by DB2 for i CLI includes dynamic arguments,
cursor information, bindings for dynamic arguments and columns, result values, and status information
(these are discussed later). Each statement handle is associated with a connection handle.
Allocate a statement handle to run a statement. You can concurrently allocate up to 160 000 handles. This
applies to all types of handles, including descriptor handles that are implicitly allocated by the
implementation code.
The first method splits the preparation of the statement from the processing. This method is used when:
v The statement is processed repeatedly (typically with different parameter values). This avoids having
to prepare the same statement more than once.
v The application requires information about the columns in the result set before statement processing.
The second method combines the preparation step and the processing step into one. This method is used
when:
v The statement is processed once. This avoids having to call two functions to process the statement.
v The application does not require information about the columns in the result set before the statement is
processed.
Binding parameters in SQL statements in a DB2 for i call level interface (CLI) application
| Both processing methods allow the use of parameter markers in place of an expression (or host variable in
| embedded SQL) in an SQL statement.
Parameter markers are represented by the '?' character and indicate the position in the SQL statement
where the contents of application variables are to be substituted when the statement is processed. The
markers are referenced sequentially, from left to right, starting at 1.
When an application variable is associated with a parameter marker, it is bound to the parameter marker.
Binding is carried out by calling the SQLBindParameter() function with:
v The number of the parameter marker
v A pointer to the application variable
v The SQL type of the parameter
v The data type and length of the variable
The application variable is called a deferred argument because only the pointer is passed when
SQLBindParameter() is called. No data is read from the variable until the statement is processed. This
applies to both buffer arguments and arguments that indicate the length of the data in the buffer.
Deferred arguments allow the application to modify the contents of the bound parameter variables, and
repeat the processing of the statement with the new values.
When calling SQLBindParameter(), it is possible to bind a variable of a different type from that required
by the SQL statement. In this case DB2 for i CLI converts the contents of the bound variable to the correct
type. For example, the SQL statement might require an integer value, but your application has a string
representation of an integer. The string can be bound to the parameter, and DB2 for i CLI converts the
string to an integer when you process the statement.
If the SQL statement uses parameter markers instead of expressions (or host variables in embedded SQL),
you must bind the application variable to the parameter marker.
Related concepts:
“Data types and data conversion in DB2 for i CLI functions” on page 18
The table shows all of the supported SQL types and their corresponding symbolic names. The symbolic
names are used in SQLBindParam(), SQLBindParameter(), SQLSetParam(), SQLBindCol(), and SQLGetData()
to indicate the data types of the arguments.
Related reference:
“SQLBindParameter - Bind a parameter marker to a buffer” on page 51
SQLBindParameter() is used to associate (bind) parameter markers in an SQL statement to application
variables. Data is transferred from the application to the Database Management System (DBMS) when
SQLExecute() or SQLExecDirect() is called. Data conversion might occur when the data is transferred.
“SQLPrepare - Prepare a statement” on page 199
SQLPrepare() associates an SQL statement with the input statement handle and sends the statement to
the DBMS to be prepared. The application can reference this prepared statement by passing the statement
handle to other functions.
“SQLExecute - Execute a statement” on page 103
SQLExecute() runs a statement that was successfully prepared using SQLPrepare() once or multiple times.
The statement is processed with the current values of any application variables that were bound to
parameter markers by SQLBindParam().
“SQLExecDirect - Execute a statement directly” on page 101
SQLExecDirect() directly runs the specified SQL statement. The statement can only be processed once.
Also, the connected database server must be able to prepare the statement.
If the statement is SELECT, these steps are generally needed to retrieve each row of the result set.
1. Establish the structure of the result set, number of columns, column types and lengths.
2. Bind application variables to columns in order to receive the data.
3. Repeatedly fetch the next row of data, and receive it into the bound application variables.
Columns that were not previously bound can be retrieved by calling SQLGetData() after each
successful fetch.
The first step requires analyzing the processed or prepared statement. If the SQL statement is generated
by the application, this step is not necessary. This is because the application knows the structure of the
result set and the data types of each column. If the SQL statement is generated (for example, entered by a
user) at run time, the application needs to query:
v The number of columns
v The type of each column
v The names of each column in the result set
This information can be obtained by calling SQLNumResultCols() and SQLDescribeCol() (or
SQLColAttribute()) after preparing the statement or after executing the statement.
The second step allows the application to retrieve column data directly into an application variable on the
next call to SQLFetch(). For each column to be retrieved, the application calls SQLBindCol() to bind an
application variable to a column in the result set. Similar to variables bound to parameter markers using
SQLSetParam(), columns are bound using deferred arguments. This time the variables are output
arguments, and data is written to them when SQLFetch() is called. SQLGetData() can also be used to
retrieve data, so calling SQLBindCol() is optional.
The third step is to call SQLFetch() to fetch the first or next row of the result set. If any columns have
been bound, the application variable is updated. If any data conversion is indicated by the data types
specified on the call to SQLBindCol, the conversion occurs when SQLFetch() is called.
The last (optional) step is to call SQLGetData() to retrieve any columns that were not previously bound.
All columns can be retrieved this way, provided they were not bound, or a combination of both methods
can be used. SQLGetData() is also useful for retrieving variable length columns in smaller pieces, which
cannot be done with bound columns. Data conversion can also be indicated here, as in SQLBindCol().
Related concepts:
“Data types and data conversion in DB2 for i CLI functions” on page 18
The table shows all of the supported SQL types and their corresponding symbolic names. The symbolic
names are used in SQLBindParam(), SQLBindParameter(), SQLSetParam(), SQLBindCol(), and SQLGetData()
to indicate the data types of the arguments.
Related reference:
“SQLBindCol - Bind a column to an application variable” on page 35
SQLBindCol() is used to associate (bind) columns in a result set to application variables (storage buffers)
for all data types. Data is transferred from the Database Management System (DBMS) to the application
when SQLFetch() is called.
“SQLColAttribute - Return a column attribute” on page 62
SQLColAttribute() obtains an attribute for a column of the result set, and is also used to determine the
number of columns. SQLColAttribute() is a more extensible alternative to the SQLDescribeCol() function.
“SQLDescribeCol - Describe column attributes” on page 84
SQLDescribeCol() returns the result descriptor information (column name, type, precision) for the
indicated column in the result set generated by a SELECT statement.
“SQLFetch - Fetch next row” on page 107
SQLFetch() advances the cursor to the next row of the result set, and retrieves any bound columns.
“SQLGetData - Get data from a column” on page 138
SQLGetData() retrieves data for a single column in the current row of the result set. This is an alternative
to SQLBindCol(), which transfers data directly into application variables on a call to SQLFetch().
SQLGetData() can also be used to retrieve large character-based data in pieces.
“SQLNumResultCols - Get number of result columns” on page 193
SQLNumResultCols() returns the number of columns in the result set associated with the input statement
handle.
Processing UPDATE, DELETE, MERGE, and INSERT statements in a DB2 for i CLI application:
| If the statement modifies data (UPDATE, DELETE, MERGE, or INSERT), no action is required other than
| the normal check for diagnostic messages. In this case, SQLRowCount() can be used to obtain the number
| of rows affected by the SQL statement.
If the SQL statement is a Positioned UPDATE or DELETE, it is necessary to use a cursor. A cursor is a
moveable pointer to a row in the result table of a SELECT statement. In embedded SQL, cursors are used
to retrieve, update or delete rows. When using DB2 for i CLI, it is not necessary to define a cursor,
because one is generated automatically.
In the case of Positioned UPDATE or DELETE statements, you need to specify the name of the cursor
within the SQL statement. You can either define your own cursor name using SQLSetCursorName(), or
query the name of the generated cursor using SQLGetCursorName(). It is best to use the generated name,
because all error messages refer to this name, and not the one defined by SQLSetCursorName().
Related reference:
“SQLNumResultCols - Get number of result columns” on page 193
SQLNumResultCols() returns the number of columns in the result set associated with the input statement
handle.
If the statement neither queries nor modifies data, there is no further action other than the normal check
for diagnostic messages.
A transaction is a recoverable unit of work, or a group of SQL statements that can be treated as one
atomic operation. This means that all the operations within the group are to be completed (committed) or
undone (rolled back), as if they were a single operation.
When using DB2 for i call level interface (CLI), transactions are started implicitly with the first access to
the database using SQLPrepare(), SQLExecDirect(), or SQLGetTypeInfo(). The transaction ends when you
use SQLTransact() to either roll back or commit the transaction. This means that any SQL statements
processed between these are treated as one unit of work.
Here are some effects of calling SQLTransact() in a DB2 for i call level interface (CLI) application.
Each function description in “DB2 for i CLI functions” on page 22 lists the possible codes returned for
each function.
Table 2. DB2 for i CLI function return codes
Return code Value Explanation
SQL_SUCCESS 0 The function is completed successfully, no additional SQLSTATE information
available.
SQL_SUCCESS_WITH_INFO 1 The function is completed successfully, with a warning or other information. Call
SQLError() to receive the SQLSTATE and any other error information. The
SQLSTATE has a class of 01.
SQL_NO_DATA_FOUND 100 The function returned successfully, but no relevant data is found.
SQL_ERROR -1 The function fails. Call SQLError() to receive the SQLSTATE and any other error
information.
SQL_INVALID_HANDLE -2 The function fails because an input handle is not valid (environment, connection or
statement handle).
SQL_NEED_DATA 99 The application tries to run an SQL statement, but DB2 for i CLI lacks parameter
data that the application indicates will be passed at run time.
SQLSTATE values are alphanumeric strings of 5 characters (bytes) with a format of ccsss, where cc
indicates class and sss indicates subclass. Any SQLSTATE that has a class of:
v 01, is a warning.
v HY, is generated by the CLI driver (either DB2 for i CLI or ODBC).
The SQLError() function also returns an error code if the code is generated by the system. When the
application is connected to an IBM database server, the error code is SQLCODE. If the code is generated
by DB2 for i CLI instead of on the system, the error code is set to -99999.
DB2 for i CLI SQLSTATE values include both additional IBM-defined SQLSTATE values that are returned
by the database server, and DB2 for i CLI-defined SQLSTATE values for conditions that are not defined in
the X/Open specification. This allows for the maximum amount of diagnostic information to be returned.
When applications are run in Windows using ODBC, it is also possible to receive ODBC-defined
SQLSTATE values.
Follow these guidelines for using SQLSTATE values within your application:
v Always check the function return code before calling SQLError() to determine if diagnostic information
is available.
v Use the SQLSTATE values rather than the error code.
v To increase your application's portability, build dependencies only on the subset of DB2 for i CLI
SQLSTATE values that are defined by the X/Open specification, and return the additional DB2 for i
CLI SQLSTATE values as information only. (Dependencies refers to the application making logic flow
decisions based on specific SQLSTATE values.)
v For maximum diagnostic information, return the text message along with the SQLSTATE (if applicable,
the text message includes the IBM-defined SQLSTATE). It is also useful for the application to print out
the name of the function that returned the error.
1
| SQL_WCHAR and SQL_WVARCHAR can be used to indicate Unicode data.
2
| Note that there is no DECFLOAT(7) data type. However, DB2 will accept this data type from applications.
Before the data transfer actually takes place, the source, target or both data types are indicated when
calling SQLBindParam(), SQLBindParameter(), SQLSetParam(), SQLBindCol() or SQLGetData(). These
functions use the symbolic type names shown in Table 3 on page 18, to identify the data types involved.
See “SQLFetch - Fetch next row” on page 107, or “SQLGetCol - Retrieve one column of a row of the
result set” on page 125 for examples of the functions that use the symbolic data types.
For a list of supported data type conversions in DB2 for i CLI, see the data type compatibility table in
Assignments and comparisons. Other conversions can be achieved by using SQL scalar functions or the
SQL CAST function in the SQL syntax of the statement being processed.
The functions mentioned in the previous paragraph can be used to convert data to other types. Not all
data conversions are supported or make sense.
Whenever truncation that is rounding or data type incompatibilities occur on a function call, either
SQL_ERROR or SQL_SUCCESS_WITH_INFO is returned. Further information is then indicated by the
SQLSTATE value and other information returned by SQLError().
DB2 CLI applications can retrieve and store XML data using the SQL_XML data type. This data type
corresponds to the native XML data type of the DB2 for idatabase, which is used to define columns that
store well-formed XML documents. The SQL_XML type can be bound to the following C types:
SQL_C_BINARY, SQL_VARBINARY, SQL_C_CHAR, SQL_VARCHAR, SQL_C_WCHAR,
andSQL_WVARCHAR. Using binary types, however, instead of character types, is recommended to avoid
possible data loss or corruption resulting from CCSID conversion when character types are used. To store
XML data in an XML column, bind a binary (SQL_C_BINARY or SQL_VARBINARY) or character
(SQL_C_CHAR, SQL_VARCHAR, SQL_C_WCHAR, or SQL_VARWCHAR) buffer that contains the XML
value to the SQL_XML SQL type and execute the INSERT or UPDATE SQL statements. To retrieve XML
data from the database, bind the result set to a binary (SQL_C_BINARY or SQL_VARBINARY) or
character (SQL_C_CHAR, SQL_VARCHAR, SQL_C_WCHAR, or SQL_WVARCHAR) type. Character
types should be used with caution because of encoding issues. 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 internal form to the serialized string form. For character typed buffers, the XML value is
implicitly serialized to the application CCSID associated with the character type. By default, an XML
declaration is included in the output serialized string. This default behavior can be changed by setting
the SQL_ATTR_XML_DECLARATION connection attribute.
When you update or insert data into XML columns of a table, the input data must be in the serialized
string format. 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_VARBINARY,
SQL_C_CHAR, SQL_VARCHAR_, SQL_C_WCHAR, SQL_BLOB, SQL_CLOB, SQL_BLOB_LOCATOR,
SQL_CLOB_LOCATOR or SQL_VARCHAR. When you bind a data buffer that contains XML data as
SQL_C_BINARY or SQL_VARBINARY, DB2 for i 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. When you bind a data buffer that contains XML data as
SQL_C_CHAR, SQL_VARCHAR, SQL_C_WCHAR, or SQL_WVARCHAR, DB2 CLI processes the XML
data as externally encoded data.
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)
When you select data from XML columns in a table, the output data is in the serialized string format. For
XML data, when you use SQLBindCol() API 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_VARBINARY,
SQL_C_CHAR, SQL_VARCHAR, SQL_C_WCHAR, SQL_BLOB, SQL_CLOB, SQL_BLOB_LOCATOR,
SQL_CLOB_LOCATOR or SQL_WVARCHAR. When retrieving a result set from an XML column, it is
recommended that you bind your application variable to the SQL_C_BINARY or SQL_VARBINARY 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 binary types avoids these issues. XML data is returned to the application as
internally encoded data.
v If the C type is SQL_C_CHAR or SQL_VARCHAR, DB2 for i CLI returns the data in job CCSID.
v If the C type is SQL_C_WCHAR or SQL_WVARCHAR, DB2 for i 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)
The length argument indicates to DB2 for i call level interface (CLI) either the length of the allocated
buffer (not including the null byte terminator) or the special value SQL_NTS. If SQL_NTS is passed, DB2
for i CLI determines the length of the string by locating the null terminating character.
Output string arguments have two associated length arguments, one to specify the length of the allocated
buffer and one to return the length of the string returned by DB2 for i CLI. The returned length value is
the total length of the string available for return, whether it fits in the buffer or not.
For SQL column data, if the output is an empty string, SQL_NULL_DATA is returned in the length
argument.
If a function is called with a null pointer for an output length argument, DB2 for i CLI does not return a
length. This might be useful when it is known that the buffers are large enough for all possible results. If
DB2 for i CLI attempts to return the SQL_NULL_DATA value to indicate a column contains null data and
the output length argument is a null pointer, the function call fails.
Every character string that DB2 for i CLI returns is terminated with a null terminating character
(hexadecimal 00), except for strings that are returned from graphic data types. This requires that all
buffers allocate enough space for the maximum number that is expected, plus one for the
null-terminating character.
For example, if SQLFetch() returns SQL_SUCCESS_WITH_INFO, and an SQLSTATE of 01004, at least one
of the buffers bound to a column is too small to hold the data. For each buffer that is bound to a column,
the application can compare the buffer length with the output length and determine which column is
truncated.
See Categories of DB2 for i CLIs for a categorical listing of the functions.
The following table shows the type of information that is described in each section of the function
description.
Type Description
Purpose This section gives a brief overview of what the function does. It also indicates if any
functions should be called before and after calling the function being described.
Syntax This section contains the C language prototype for the i5/OS environment.
Arguments This section lists each function argument, along with its data type, a description and
whether it is an input or output argument.
Each DB2 for i CLI argument is either an input or output argument. With the exception
of SQLGetInfo(), DB2 for i CLI only modifies arguments that are indicated as output.
Some functions contain input or output arguments which are known as deferred or bound
arguments. These arguments are pointers to buffers allocated by the application. These
arguments are associated with (or bound to) either a parameter in an SQL statement, or
a column in a result set. The data areas specified by the function are accessed by DB2 for
i CLI at a later time. It is important that these deferred data areas are still valid at the
time DB2 for i CLI accesses them.
Usage This section provides information about how to use the function, and any special
considerations. Possible error conditions are not discussed here, but are listed in the
diagnostics section instead.
Return codes This section lists all the possible function return codes. When SQL_ERROR or
SQL_SUCCESS_WITH_INFO is returned, error information can be obtained by calling
SQLError().
Refer to “Diagnostics in a DB2 for i CLI application” on page 16 for more information
about return codes.
Type Description
Diagnostics This section contains a table that lists the SQLSTATEs explicitly returned by DB2 for i
CLI (SQLSTATEs generated by the Database Management System (DBMS) might also be
returned) and indicates the cause of the error. These values are obtained by calling
SQLError() after the function returns SQL_ERROR or SQL_SUCCESS_WITH_INFO.
An * in the first column indicates that the SQLSTATE is returned only by DB2 for i CLI,
and is not returned by other ODBC drivers.
Refer to “Diagnostics in a DB2 for i CLI application” on page 16 for more information
about diagnostics.
Restrictions This section indicates any differences or limitations between DB2 for i CLI and ODBC
that might affect an application.
Example This section is a code fragment demonstrating the use of the function. The complete
source used for all code fragments is listed in “Examples: DB2 for i CLI applications” on
page 306.
References This section lists related DB2 for i CLI functions.
Syntax
SQLRETURN SQLAllocConnect (SQLHENV henv,
SQLHDBC *phdbc);
Function arguments
Table 5. SQLAllocConnect arguments
Data type Argument Use Description
SQLHENV henv Input Environment handle
SQLHDBC * phdbc Output Pointer to connection handle
Usage
The output connection handle is used by DB2 for i CLI to reference all information related to the
connection, including general status information, transaction state, and error information.
If the pointer to the connection handle (phdbc) points to a valid connection handle allocated by
SQLAllocConnect(), the original value is overwritten as a result of this call. This is an application
programming error and is not detected by DB2 for i CLI
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
If SQL_ERROR is returned, the phdbc argument is set to SQL_NULL_HDBC. The application should call
SQLError() with the environment handle (henv), with hdbc set to SQL_NULL_HDBC, and with hstmt set
to SQL_NULL_HSTMT.
Diagnostics
Table 6. SQLAllocConnect SQLSTATEs
CLI SQLSTATE Description Explanation
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not phdbc is a null pointer.
valid
Example
The following example shows how to obtain diagnostic information for the connection and the
environment. For more examples of using SQLError(), refer to “Example: Interactive SQL and the
equivalent DB2 for i CLI function calls” on page 313 for a complete listing of typical.c.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*******************************************************************
** initialize
** - allocate environment handle
** - allocate connection handle
** - prompt for server, user id, & password
** - connect to server
*******************************************************************/
if (uid[0] == ’\0’)
{ rc = SQLConnect (*hdbc, server, SQL_NTS, NULL, SQL_NTS, NULL, SQL_NTS);
if (rc != SQL_SUCCESS )
check_error (*henv, *hdbc, SQL_NULL_HSTMT, rc);
}
else
{ rc = SQLConnect (*hdbc, server, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);
if (rc != SQL_SUCCESS )
check_error (*henv, *hdbc, SQL_NULL_HSTMT, rc);
}
}/* end initialize */
/*******************************************************************/
int check_error (SQLHENV henv,
SQLHDBC hdbc,
SQLHSTMT hstmt,
SQLRETURN frc)
{
SQLRETURN rc;
switch (frc){
case SQL_SUCCESS : break;
case SQL_ERROR :
case SQL_INVALID_HANDLE:
printf("\n ** FATAL ERROR, Attempting to rollback transaction **\n");
rc = SQLTransact(henv, hdbc, SQL_ROLLBACK);
if (rc != SQL_SUCCESS)
printf("Rollback Failed, Exiting application\n");
else
printf("Rollback Successful, Exiting application\n");
terminate(henv, hdbc);
exit(frc);
break;
case SQL_SUCCESS_WITH_INFO :
printf("\n ** Warning Message, application continuing\n");
break;
case SQL_NO_DATA_FOUND :
printf("\n ** No Data Found ** \n");
break;
default :
printf("\n ** Invalid Return Code ** \n");
printf(" ** Attempting to rollback transaction **\n");
SQLTransact(henv, hdbc, SQL_ROLLBACK);
terminate(henv, hdbc);
exit(frc);
break;
}
return(SQL_SUCCESS);
References
v “SQLAllocEnv - Allocate environment handle” on page 29
v “SQLConnect - Connect to a data source” on page 76
v “SQLDisconnect - Disconnect from a data source” on page 90
v “SQLFreeConnect - Free connection handle” on page 120
v “SQLGetConnectAttr - Get the value of a connection attribute” on page 131
v “SQLSetConnectOption - Set connection option” on page 231
An application must call this function before SQLAllocConnect() or any other DB2 for i CLI functions.
The henv value is passed in all later function calls that require an environment handle as input.
Syntax
SQLRETURN SQLAllocEnv (SQLHENV *phenv);
Function arguments
Table 7. SQLAllocEnv arguments
Data type Argument Use Description
SQLHENV * phenv Output Pointer to environment handle
Usage
There can be only one active environment at any one time per application. Any later call to
SQLAllocEnv() returns the existing environment handle.
By default, the first successful call to SQLFreeEnv() releases the resources associated with the handle. This
occurs no matter how many times SQLAllocEnv() is successfully called. If the environment attribute
SQL_ATTR_ENVHNDL_COUNTER is set to SQL_TRUE, SQLFreeEnv() must be called once for each
successful SQLAllocEnv() call before the resources associated with the handle are released.
To ensure that all DB2 for i CLI resources are kept active, the program that calls SQLAllocEnv() should
not stop or leave the stack. Otherwise, the application loses open cursors, statement handles, and other
resources it has allocated.
Return codes
v SQL_SUCCESS
v SQL_ERROR
If SQL_ERROR is returned and phenv is equal to SQL_NULL_HENV, then SQLError() cannot be called
because there is no handle with which to associate additional diagnostic information.
If the return code is SQL_ERROR and the pointer to the environment handle is not equal to
SQL_NULL_HENV, then the handle is a restricted handle. This means the handle can only be used in a call
to SQLError() to obtain more error information, or to SQLFreeEnv().
Diagnostics
Table 8. SQLAllocEnv SQLSTATEs
SQLSTATE Description Explanation
58004 System error Unrecoverable system error
Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*******************************************************
** file = basiccon.c
** - demonstrate basic connection to two datasources.
#include <stdio.h>
#include <stdlib.h>
#include "sqlcli.h"
int
connect(SQLHENV henv,
SQLHDBC * hdbc);
#define MAX_DSN_LENGTH 18
#define MAX_UID_LENGTH 10
#define MAX_PWD_LENGTH 10
#define MAX_CONNECTIONS 5
int
main()
{
SQLHENV henv;
SQLHDBC hdbc[MAX_CONNECTIONS];
printf("\nDisconnecting .....\n");
SQLFreeConnect(hdbc[0]); /* free first connection handle */
SQLFreeConnect(hdbc[1]); /* free second connection handle */
SQLFreeEnv(henv); /* free environment handle */
return (SQL_SUCCESS);
}
/********************************************************************
** connect - Prompt for connect options and connect **
********************************************************************/
int
connect(SQLHENV henv,
SQLHDBC * hdbc)
{
SQLRETURN rc;
SQLCHAR server[MAX_DSN_LENGTH + 1], uid[MAX_UID_LENGTH + 1],
pwd[MAX_PWD_LENGTH
+ 1];
SQLCHAR buffer[255];
SQLSMALLINT outlen;
gets((char *) server);
printf("Enter User Name:\n");
gets((char *) uid);
printf("Enter Password Name:\n");
gets((char *) pwd);
References
v “SQLAllocConnect - Allocate connection handle” on page 26
v “SQLFreeEnv - Free environment handle” on page 121
v “SQLAllocStmt - Allocate a statement handle” on page 33
Syntax
SQLRETURN SQLAllocHandle (SQLSMALLINT htype,
SQLINTEGER ihandle,
SQLINTEGER *handle);
Function arguments
Table 9. SQLAllocHandle arguments
Data type Argument Use Description
SQLSMALLINT htype Input Type of handle to allocate. Must be either
SQL_HANDLE_ENV, SQL_HANDLE_DBC,
SQL_HANDLE_DESC, or
SQL_HANDLE_STMT.
SQLINTEGER ihandle Input The handle that describes the context in
which the new handle is allocated; however,
if htype is SQL_HANDLE_ENV, this is
SQL_NULL_HANDLE.
SQLINTEGER * handle Output Pointer to the handle.
Usage
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
References
v “SQLAllocConnect - Allocate connection handle” on page 26
v “SQLAllocEnv - Allocate environment handle” on page 29
v “SQLAllocStmt - Allocate a statement handle” on page 33
Syntax
SQLRETURN SQLAllocStmt (SQLHDBC hdbc,
SQLHSTMT *phstmt);
Function arguments
Table 11. SQLAllocStmt arguments
Data type Argument Use Description
SQLHDBC hdbc Input Connection handle
SQLHSTMT * phstmt Output Pointer to statement handle
Usage
DB2 for i CLI uses each statement handle to relate all the descriptors, result values, cursor information,
and status information to the SQL statement processed. Although each SQL statement must have a
statement handle, you can reuse the handles for different statements.
A call to this function requires that hdbc references an active database connection.
| To process a positioned UPDATE or DELETE statement, the application must use different statement
| handles for the SELECT statement and the UPDATE or DELETE statement.
If the input pointer to the statement handle (phstmt) points to a valid statement handle allocated by a
previous call to SQLAllocStmt(), then the original value is overwritten as a result of this call. This is an
application programming error and is not detected by DB2 for i CLI.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
| If SQL_ERROR is returned, the phstmt argument is set to SQL_NULL_HSTMT. The application should call
| SQLError() with the same hdbc argument and with the hstmt argument set to SQL_NULL_HSTMT.
Diagnostics
Table 12. SQLAllocStmt SQLSTATEs
SQLSTATE Description Explanation
08003 Connection not open The connection specified by the hdbc argument is not
open. The connection must be established successfully
(and the connection must be open) for the driver to
allocate an hstmt.
Example
References
v “SQLConnect - Connect to a data source” on page 76
v “SQLFreeStmt - Free (or reset) a statement handle” on page 123
v “SQLGetStmtOption - Return current setting of a statement option” on page 173
v “SQLSetStmtOption - Set statement option” on page 251
This function is also used to specify any data conversion that is required. It is called once for each
column in the result set that the application needs to retrieve.
| SQLPrepare() or SQLExecDirect() is typically called before this function. It might also be necessary to call
| SQLDescribeCol() or SQLColAttribute() to get the attributes of the corresponding result set column.
SQLBindCol() must be called before SQLFetch() to transfer data to the storage buffers that are specified by
this call.
Syntax
SQLRETURN SQLBindCol (SQLHSTMT hstmt,
SQLSMALLINT icol,
SQLSMALLINT fCType,
SQLPOINTER rgbValue,
SQLINTEGER cbValueMax,
SQLINTEGER *pcbValue);
Function arguments
| Table 13. SQLBindCol arguments
| Data type Argument Use Description
| SQLHSTMT hstmt Input Statement handle.
| SQLSMALLINT icol Input Number identifying the column. Columns
| are numbered sequentially, from left to right,
| starting at 1.
Note:
For this function, both rgbValue and pcbValue are deferred outputs, meaning that the storage locations
these pointers point to are not updated until SQLFetch() is called. The locations referred to by these
pointers must remain valid until SQLFetch() is called.
Usage
The application calls SQLBindCol() once for each column in the result set that it wants to retrieve. When
SQLFetch() is called, the data in each of these bound columns is placed in the assigned location (given by
the pointers rgbValue and pcbValue).
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 specify the correct data
type of the storage locations, or to indicate data conversion to other data types. Refer to “Data types and
data conversion in DB2 for i CLI functions” on page 18 for more information.
For subsequent Fetch requests, the application can change the binding of these columns or bind unbound
columns by calling FSQLBindCol(). The new binding does not apply to data fetched, it is used when the
next SQLFetch() is called. To unbind a single column, call SQLBindCol() with rgbValue set to NULL. To
unbind all the columns, the application should call SQLFreeStmt() with the fOption input set to
SQL_UNBIND.
| Columns are identified by a number, assigned sequentially from left to right as they appear in the result
| set, starting at 1. The number of columns in the result set can be determined by calling
| SQLNumResultCols() or SQLColAttribute() with the FieldIdentifier argument set to SQL_DESC_COUNT.
All character data is treated as the default job coded character set identifier (CCSID) if the
SQL_ATTR_UTF8 environment attribute is not set to SQL_TRUE.
| An application can choose to bind anywhere from zero columns to all columns. The data in the unbound
| columns (and only the unbound columns) can be retrieved using SQLGetData() after SQLFetch() has been
| called. SQLBindCol() is more efficient than SQLGetData(), and should be used whenever possible.
The application must ensure enough storage is allocated for the data to be retrieved. If the buffer is to
contain variable length data, the application must allocate as much storage as the maximum length of the
bound column requires; otherwise, the data might be truncated.
| The default is null termination for output character strings. To change this you must set the
| SQLSetEnvAttr() attribute SQL_ATTR_OUTPUT_NTS to SQL_FALSE. The output values for pcbValue after
| a call to SQLFetch() behave in the following way for character data types:
| v If the SQL_ATTR_OUTPUT_NTS attribute is set to SQL_TRUE (the default), then SQL_NTS is returned
| in the pcbValue.
| v If the SQL_ATTR_OUTPUT_NTS attribute is set to SQL_FALSE, then the value of cbValueMax, which is
| the maximum bytes available, is returned in pcbValue.
| v If truncation occurs, then the value of cbValueMax, which is the actual bytes available, is returned in
| pcbValue.
Truncation occurs when argument cbValueMax does not allocate space for the amount of fetched data. If
the environment is set to run with null terminated strings, make sure to allocate space for the additional
byte in cbValueMax. For additional truncation information, refer to “SQLFetch - Fetch next row” on page
107.
DB2 for i CLI differs from DB2 CLI for Linux, UNIX, and Windows in the way it returns length
information in the pcbValue argument. After a fetch for an SQL_VARCHAR column, DB2 for i CLI returns
the bytes that are fetched in the first 2 bytes of the VARCHAR structure that is bound. DB2 for i CLI does
not return the length in pcbValue as it does for SQL_CHAR. This is different from DB2 CLI for Linux,
UNIX, and Windows, which have no representation of C VARCHAR and include the length information
in the pcbValue buffer when the application binds to the SQL_CHAR column.
For decimal floating point data types, a precision of 32, 64, or 128 can be specified by using the default
symbolic C data type constants. For example, to specify a decimal floating point data type with a
precision of 128 bytes, fCType can be set to SQL_C_DECIMAL128.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 14. SQLBindCol SQLSTATEs
SQLSTATE Description Explanation
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
58004 System error Unrecoverable system error.
Example
References
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLExecute - Execute a statement” on page 103
v “SQLFetch - Fetch next row” on page 107
v “SQLPrepare - Prepare a statement” on page 199
The LOB file reference arguments (file name, file name length, file reference options) refer to a file within
the application's environment (on the client). Before fetching each row, the application must make sure
that these variables contain the name of a file, the length of the file name, and a file option
(new/overwrite/append). These values can be changed between each fetch.
Syntax
SQLRETURN SQLBindFileToCol (SQLHSTMT StatementHandle,
SQLSMALLINT ColumnNumber,
SQLCHAR *FileName,
SQLSMALLINT *FileNameLength,
SQLINTEGER *FileOptions,
SQLSMALLINT MaxFileNameLength,
SQLINTEGER *StringLength,
SQLINTEGER *IndicatorValue);
Function arguments
Table 15. SQLBindFileToCol arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLSMALLINT ColumnNumber Input Number identifying the column. Columns are
numbered sequentially, from left to right, starting at
1.
SQLCHAR * FileName Input Pointer to the location that contains the file name or
(deferred) an array of file names at the time of the next fetch
using the StatementHandle. This is either the complete
path name of the file(s) or a relative file name(s). If
relative file name(s) are provided, they are appended
to the current path of the running application. This
pointer cannot be NULL.
SQLSMALLINT * FileNameLength Input Pointer to the location that contains the length of the
(deferred) file name (or an array of lengths) at the time the next
fetch using the StatementHandle. If this pointer is
NULL, then a length of SQL_NTS is assumed.
Usage
The application calls SQLBindFileToCol() once for each column that should be transferred directly to a
file when a row is fetched. LOB data is written directly to the file without any data conversion, and
without appending null-terminators.
FileName, FileNameLength, and FileOptions must be set before each fetch. When SQLFetch() or
SQLFetchScroll() is called, the data for any column which has been bound to a LOB file reference is
written to the file or files pointed to by that file reference. Errors associated with the deferred input
argument values of SQLBindFileToCol() are reported at fetch time. The LOB file reference, and the
deferred StringLength and IndicatorValue output arguments are updated between fetch operations.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 16. SQLBindFileToCol SQLSTATEs
SQLSTATE Description Explanation
58004 Unexpected system failure Unrecoverable system error.
Restrictions
This function is not available when connected to DB2 servers that do not support Large Object data
types.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLFetch - Fetch next row” on page 107
v “SQLBindFileToParam - Bind LOB file reference to LOB parameter” on page 43
The LOB file reference arguments (file name, file name length, file reference options) refer to a file within
the application's environment (on the client). Before calling SQLExecute() or SQLExecDirect(), the
application must make sure that this information is available in the deferred input buffers. These values
can be changed between SQLExecute() calls.
Syntax
SQLRETURN SQLBindFileToParam (SQLHSTMT StatementHandle,
SQLSMALLINT ParameterNumber,
SQLSMALLINT DataType,
SQLCHAR *FileName,
SQLSMALLINT *FileNameLength,
SQLINTEGER *FileOptions,
SQLSMALLINT MaxFileNameLength,
SQLINTEGER *IndicatorValue);
Function arguments
Table 17. SQLBindFileToParam arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLSMALLINT ParameterNumber Input Parameter marker number. Parameters are numbered
sequentially, from left to right, starting at 1.
SQLSMALLINT DataType Input SQL data type of the column. The data type must be
one of:
v SQL_BLOB
v SQL_CLOB
v SQL_DBCLOB
SQLCHAR * FileName Input Pointer to the location that contains the file name or
(deferred) an array of file names when the statement
(StatementHandle) is processed. This is either the
complete path name of the file or a relative file
name. If a relative file name is provided, it is
appended to the current path of the client process.
Usage
The application calls SQLBindFileToParam() once for each parameter marker whose value should be
obtained directly from a file when a statement is processed. Before the statement is processed, FileName,
FileNameLength, and FileOptions values must be set. When the statement is processed, the data for any
parameter that has been bound with SQLBindFileToParam() is read from the referenced file and passed to
the data source.
A LOB parameter marker can be associated with (bound to) an input file using SQLBindFileToParam(), or
with a stored buffer using SQLBindParameter(). The most recent bind parameter function call determines
the type of binding that is in effect.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 18. SQLBindFileToParam SQLSTATEs
SQLSTATE Description Explanation
58004 Unexpected system failure Unrecoverable system error.
HY004 SQL data type out of range The value specified for DataType is not a valid SQL type for this
function call.
HY009 Argument value that is not valid FileName, FileOptions, or FileNameLength is a null pointer.
Restrictions
This function is not available when the application is connected to DB2 servers that do not support large
object data types.
References
v “SQLBindParam - Bind a buffer to a parameter marker” on page 46
v “SQLExecute - Execute a statement” on page 103
v “SQLParamOptions - Specify an input array for a parameter” on page 197
SQLBindParam() binds an application variable to a parameter marker in an SQL statement. This function
can also be used to bind an application variable to a parameter of a stored procedure CALL statement
where the parameter can be input or output.
Syntax
SQLRETURN SQLBindParam (SQLHSTMT hstmt,
SQLSMALLINT ipar,
SQLSMALLINT fCType,
SQLSMALLINT fSqlType,
SQLINTEGER cbParamDef,
SQLSMALLINT ibScale,
SQLPOINTER rgbValue,
SQLINTEGER *pcbValue);
Function arguments
Table 19. SQLBindParam arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLSMALLINT ipar Input Parameter marker number, ordered
sequentially left to right, starting at 1.
Usage
When SQLBindParam() is used to bind an application variable to an output parameter for a stored
procedure, DB2 for i CLI provides some performance enhancement if the rgbValue buffer is placed
consecutively in memory after the pcbValue buffer.
For decimal floating point data types, a precision of 32, 64, or 128 can be specified by using the default
symbolic C data type constants. For example, to specify a decimal floating point data type with a
precision of 128 bytes, fCType can be set to SQL_C_DECIMAL128.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 20. SQLBindParam SQLSTATEs
SQLSTATE Description Explanation
07006 Restricted data type Same as SQLSetParam().
attribute violation
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY003 Program type out of range Same as SQLSetParam().
HY004 SQL data type out of range Same as SQLSetParam().
HY009 Argument value that is not Both rgbValue and pcbValue are null pointers, or ipar is
valid less than one.
HY010 Function sequence error Function is called after SQLExecute() or SQLExecDirect()
has returned SQL_NEED_DATA, but data has not been
sent for all data-at-execution parameters.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
HY014 Too many handles The maximum number of handles has been allocated.
HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
not valid or it contains a value that is not valid.
References
| This function must also be used to bind application storage to a parameter of a stored procedure where
| the parameter can be input, output, or both.
Syntax
SQLRETURN SQLBindParameter(SQLHSTMT StatementHandle,
SQLSMALLINT ParameterNumber,
SQLSMALLINT InputOutputType,
SQLSMALLINT ValueType,
SQLSMALLINT ParameterType,
SQLINTEGER ColumnSize,
SQLSMALLINT DecimalDigits,
SQLPOINTER ParameterValuePtr,
SQLINTEGER BufferLength,
SQLINTEGER *StrLen_or_IndPtr);
Function arguments
| Table 21. SQLBindParameter arguments
| Data type Argument Use Description
| SQLHSTMT StatementHandle Input Statement handle.
| SQLSMALLINT ParameterNumber Input Parameter marker number, ordered sequentially
| left to right, starting at 1.
Usage
A parameter marker is represented by a "?" character in an SQL statement and is used to indicate a
position in the statement where an application supplied value is to be substituted when the statement is
processed. This value is obtained from an application variable.
The application must bind a variable to each parameter marker in the SQL statement before executing the
SQL statement. For this function, ParameterValuePtr and StrLen_or_IndPtr are deferred arguments; the
storage locations must be valid and contain input data values when the statement is processed. This
means either keeping the SQLExecDirect() or SQLExecute() call in the same procedure scope as the
SQLBindParameter() calls, or these storage locations must be dynamically allocated or declared statically
or globally.
| Parameter markers are referred to by number (ParameterNumber) and are numbered sequentially from left
| to right as the corresponding ? appears in the statement text, starting at 1.
All parameters bound by this function remain in effect until SQLFreeStmt() is called with either the
SQL_DROP or SQL_RESET_PARAMS option, or until SQLBindParameter() is called again for the same
parameter ParameterNumber number.
After the SQL statement and the results have been processed, the application might want to reuse the
statement handle to process 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.
The C buffer data type that is given by ValueType must be compatible with the SQL data type that is
indicated by ParameterType, or an error occurs.
Because the data in the variables referenced by ParameterValuePtr and StrLen_or_IndPtr is not verified
until the statement is processed, data content or format errors are not detected or reported until
SQLExecute() or SQLExecDirect() is called.
The InputOutputType argument specifies the type of the parameter. All parameters in the SQL statements
that do not call procedures are input parameters. Parameters in stored procedure calls can be input,
input/output, or output parameters. Even though the DB2 stored procedure argument convention
typically implies that all procedure arguments are input/output, the application programmer can still
choose to specify more exactly the input or output nature on the SQLBindParameter() to follow a more
rigorous coding style. Also, note that these types should be consistent with the parameter types specified
when the stored procedure is registered with the SQL CREATE PROCEDURE statement.
v If an application cannot determine the type of a parameter in a procedure call, set InputOutputType to
SQL_PARAM_INPUT; if the data source returns a value for the parameter, DB2 for i CLI discards it.
v If an application has marked a parameter as SQL_PARAM_INPUT_OUTPUT or
SQL_PARAM_OUTPUT and the data source does not return a value, DB2 for i CLI sets the
StrLen_or_IndPtr buffer to SQL_NULL_DATA.
v If an application marks a parameter as SQL_PARAM_OUTPUT, data for the parameter is returned to
the application after the CALL statement has been processed. If the ParameterValuePtr and
StrLen_or_IndPtr arguments are both null pointers, DB2 for i CLI discards the output value. If the data
source does not return a value for an output parameter, DB2 for i CLI sets the StrLen_or_IndPtr buffer
to SQL_NULL_DATA.
v For this function, both ParameterValuePtr and StrLen_or_IndPtr are deferred arguments. In the case
where InputOutputType is set to SQL_PARAM_INPUT or SQL_PARAM_INPUT_OUTPUT, the storage
locations must be valid and contain input data values when the statement is processed. This means
either keeping the SQLExecDirect() or SQLExecute() call in the same procedure scope as the
SQLBindParameter() calls, or, these storage locations must be dynamically allocated or statically /
globally declared.
When SQLBindParameter() is used to bind an application variable to an output parameter for a stored
procedure, DB2 for i CLI can provide some performance enhancement if the ParameterValuePtr buffer is
placed consecutively in memory after the StrLen_or_IndPtr buffer. For example:
struct { SQLINTEGER StrLen_or_IndPtr;
SQLCHAR ParameterValuePtr[MAX_BUFFER];
} column;
For decimal floating point data types, a precision of 32, 64, or 128 can be specified by using the default
symbolic C data type constants. For example, to specify a decimal floating point data type with a
precision of 128 bytes, ValueType can be set to SQL_C_DECIMAL128.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 22. SQLBindParameter SQLSTATEs
SQLSTATE Description Explanation
07006 Conversion not valid The conversion from the data value identified by the ValueType
argument to the data type identified by the ParameterType
argument is not a meaningful conversion. (For example,
conversion from SQL_C_DATE to SQL_DOUBLE.)
40003 08S01 Communication link failure The communication link between the application and data source
fails before the function is completed.
58004 Unexpected system failure Unrecoverable system error.
HY001 Memory allocation failure DB2 for i CLI is unable to allocate memory required to support
the processing or completion of the function.
HY003 Program type out of range The value specified by the argument ParameterNumber not a valid
data type or SQL_C_DEFAULT.
HY004 SQL data type out of range The value specified for the argument ParameterType is not a valid
SQL data type.
HY009 Argument value not valid The argument ParameterValuePtr is a null pointer and the
argument StrLen_or_IndPtr is a null pointer, and InputOutputType
is not SQL_PARAM_OUTPUT.
HY010 Function sequence error Function is called after SQLExecute() or SQLExecDirect() has
returned SQL_NEED_DATA, but data has not been sent for all
data-at-execution parameters.
HY013 Unexpected memory handling DB2 for i CLI is unable to access memory required to support the
error processing or completion of the function.
HY014 Too many handles The maximum number of handles has been allocated.
HY021 Inconsistent descriptor The descriptor information checked during a consistency check is
information not consistent.
HY090 String or buffer length not valid The value specified for the BufferLength argument is less than 0.
References
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLExecute - Execute a statement” on page 103
v “SQLParamData - Get next parameter for which a data value is needed” on page 195
v “SQLPutData - Pass data value for a parameter” on page 214
Syntax
SQLRETURN SQLCancel (SQLHSTMT hstmt);
Function arguments
Table 23. SQLCancel arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle
Usage
A successful return code indicates that the implementation has accepted the cancel request; it does not
ensure that the processing is canceled.
Return codes
v SQL_SUCCESS
v SQL_INVALID_HANDLE
v SQL_ERROR
Diagnostics
Table 24. SQLCancel SQLSTATEs
SQLSTATE Description Explanation
HY009 * Argument value that is not hstmt is not a statement handle.
valid
Restrictions
Syntax
SQLRETURN SQLCloseCursor (SQLHSTMT hstmt);
Function arguments
Table 25. SQLCloseCursor arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle
Usage
Calling SQLCloseCursor() closes any cursor associated with the statement handle and discards any
pending results. If no open cursor is associated with the statement handle, the function has no effect.
If the statement handle references a stored procedure that has multiple result sets, the SQLCloseCursor()
closes only the current result set. Any additional result sets remain open and usable.
Return codes
v SQL_SUCCESS
v SQL_INVALID_HANDLE
v SQL_ERROR
Diagnostics
Table 26. SQLCloseCursor SQLSTATEs
SQLSTATE Description Explanation
08003 * Connection not open The connection for hstmt is not established.
HY009 * Argument value that is not hstmt is not a statement handle.
valid
HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
not valid or it contains a value that is not valid.
This function (or SQLDescribeCol()) must be called before SQLBindCol(), if the application does not know
the various attributes (such as data type and length) of the column.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLColAttributeW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLColAttribute (SQLHSTMT StatementHandle,
SQLSMALLINT ColumnNumber,
SQLSMALLINT FieldIdentifier,
SQLPOINTER CharacterAttributePtr,
SQLSMALLINT BufferLength,
SQLSMALLINT *StringLengthPtr,
SQLPOINTER NumericAttributePtr);
Function arguments
Table 27. SQLColAttribute arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLSMALLINT ColumnNumber Input The number of the record in the IRD from
which the field value is to be retrieved. This
argument corresponds to the column number
of result data, ordered sequentially from left
to right, starting at 1. Columns can be
described in any order.
SQL_ATTR_READONLY
SQL_ATTR_WRITE
SQL_ATTR_READWRITE_UNKNOWN
Usage
Instead of returning a specific set of arguments like SQLDescribeCol(), SQLColAttribute() can be used to
specify which attribute you want to receive for a specific column. If the required information is a string,
it is returned in CharacterAttributePtr. If the required information is a number, it is returned in
NumericAttributePtr.
Although SQLColAttribute() allows for future extensions, it requires more calls to receive the same
information than SQLDescribeCol() for each column.
If a FieldIdentifier descriptor type does not apply to the database server, an empty string is returned in
CharacterAttributePtr or zero is returned in NumericAttributePtr, depending on the expected result of the
descriptor.
Columns are identified by a number (numbered sequentially from left to right starting with 1) and can be
described in any order.
Call SQLNumResultCols() before calling SQLColAttribute() to determine whether a result set exists.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Diagnostics
Table 29. SQLColAttribute SQLSTATEs
SQLSTATE Description Explanation
01004 Data truncated The requested information is returned as a
null-terminated string and its length exceeded the length
of the application buffer as specified in cbInfoValueMax.
The argument pcbInfoValue contains the actual (not
truncated) length of the requested information.
07009 Column number that is not The value specified for the argument ColumnNumber is
valid less than 1.
HY009 Argument value that is not The value specified for the argument FieldIdentifier is not
valid equal to a value specified in Table 27 on page 62.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLDescribeCol - Describe column attributes” on page 84
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLExecute - Execute a statement” on page 103
v “SQLPrepare - Prepare a statement” on page 199
Although this release version of DB2 CLI continues to support SQLColAttributes(), it is recommended
that you begin using SQLColAttribute() in your DB2 CLI programs so that they conform to the latest
standards.”
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLColAttributesW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLColAttributes (SQLHSTMT StatementHandle,
SQLSMALLINT ColumnNumber,
SQLSMALLINT FieldIdentifier,
SQLPOINTER CharacterAttributePtr,
SQLSMALLINT BufferLength,
SQLSMALLINT *StringLengthPtr,
SQLPOINTER NumericAttributePtr);
Note: Refer to “SQLColAttribute - Return a column attribute” on page 62 for a description of the
applicable sections.
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLColumnPrivilegesW(). Refer to “Unicode in DB2 for iCLI” on page
| 305 for more information about Unicode support forDB2 for i CLI.
Syntax
SQLRETURN SQLColumnPrivileges (
SQLHSTMT StatementHandle,
SQLCHAR *CatalogName,
SQLSMALLINT NameLength1,
SQLCHAR *SchemaName,
SQLSMALLINT NameLength2,
SQLCHAR *TableName
SQLSMALLINT NameLength3,
SQLCHAR *ColumnName,
SQLSMALLINT NameLength4);
Function arguments
Table 30. SQLColumnPrivileges arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLCHAR * CatalogName Input Catalog qualifier of a 3 part table name. This
must be a NULL pointer or a zero length
string.
SQLSMALLINT NameLength1 Input Length of CatalogName. This must be set to 0.
SQLCHAR * SchemaName Input Schema qualifier of table name.
SQLSMALLINT NameLength2 Input Length of SchemaName.
SQLCHAR * TableName Input Table Name.
SQLSMALLINT NameLength3 Input Length of TableName.
SQLCHAR * ColumnName Input Buffer that can contain a pattern-value to
qualify the result set by column name.
SQLSMALLINT NameLength4 Input Length of ColumnName.
Usage
The results are returned as a standard result set containing the columns listed in Table 31 on page 70. The
result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, and
PRIVILEGE. If multiple privileges are associated with any given column, each privilege is returned as a
separate row. A typical application might want to call this function after a call to SQLColumns() to
determine column privilege information. The application should use the character strings returned in the
TABLE_SCHEM, TABLE_NAME, COLUMN_NAME columns of the SQLColumns() result set as input
arguments to this function
Because calls to SQLColumnPrivileges() in many cases map to a complex and thus expensive query
against the system catalog, they should be used sparingly, and the results saved rather than repeating the
calls.
| The VARCHAR columns of the catalog-functions result set have been declared with a maximum length
| attribute of 128 to be consistent with SQL92 limits. Because DB2 for i names are always 128 characters or
| less in length, the application can choose to always set aside 128 characters (plus the null-terminator) for
| the output buffer, or alternatively, call SQLGetInfo() with SQL_MAX_CATALOG_NAME_LEN,
| SQL_MAX_SCHEMA_NAME_LEN, SQL_MAX_TABLE_NAME_LEN, and
| SQL_MAX_COLUMN_NAME_LEN. The SQL_MAX_CATALOG_NAME_LEN value determines the actual
| length of the TABLE_CAT supported by the connected Database Management System (DBMS). The
| SQL_MAX_SCHEMA_NAME_LEN value determines the actual length of the TABLE_SCHEM supported
| by the connected DBMS. The SQL_MAX_TABLE_NAME_LEN value determines the actual length of the
| TABLE_NAME supported by the connected DBMS. The SQL_MAX_COLUMN_NAME_LEN value
| determines the actual length of the COLUMN_NAME supported by the connected DBMS.
Note: The column names used by DB2 for i CLI follow the X/Open CLI CAE specification style. The
column types, contents and order are identical to those defined for the SQLColumnPrivileges()
result set in ODBC.
If there is more than one privilege associated with a column, then each privilege is returned as a separate
row in the result set.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 32. SQLColumnPrivileges SQLSTATEs
SQLSTATE Description Explanation
HY001 Memory allocation failure The driver is unable to allocate
memory required to support the
processing or completion of the
function.
HY009 String or buffer length that is not The value of one of the name length
valid arguments is less than 0, but not
equal to SQL_NTS.
HY010 Function sequence error There is an open cursor for this
statement handle, or there is no
connection for this statement handle.
HY021 Internal descriptor that is not valid The internal descriptor cannot be
addressed or allocated, or it contains
a value that is not valid.
Restrictions
None.
Example
/* From the CLI sample TBINFO.C */
/* ... */
/* call SQLColumnPrivileges */
printf("\n Call SQLColumnPrivileges for:\n");
printf(" tbSchema = %s\n", tbSchema);
printf(" tbName = %s\n", tbName);
sqlrc = SQLColumnPrivileges( hstmt, NULL, 0,
tbSchema, SQL_NTS,
tbName, SQL_NTS,
colNamePattern, SQL_NTS);
References
v “SQLColumns - Get column information for a table” on page 72
v “SQLTables - Get table information” on page 264
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLColumnsW(). Refer to “Unicode in DB2 for iCLI” on page 305 for
| more information about Unicode support for DB2 for i CLI.
Syntax
SQLRETURN SQLColumns (SQLHSTMT hstmt,
SQLCHAR *szCatalogName,
SQLSMALLINT cbCatalogName,
SQLCHAR *szSchemaName,
SQLSMALLINT cbSchemaName,
SQLCHAR *szTableName,
SQLSMALLINT cbTableName,
SQLCHAR *szColumnName,
SQLSMALLINT cbColumnName);
Function arguments
| Table 33. SQLColumns arguments
| Data type Argument Use Description
| SQLHSTMT hstmt Input Statement handle.
| SQLCHAR * szCatalogName Input Buffer that might contain a pattern-value to
| qualify the result set. Catalog is the first part
| of a three-part table name.
Usage
This function retrieves information about the columns of a table or a list of tables.
| SQLColumns() returns a standard result set. Table 34 on page 73 lists the columns in the result set.
The szCatalogName, szSchemaName, szTableName, and szColumnName arguments accept search patterns. An
escape character can be specified in conjunction with a wildcard character to allow that actual character
to be used in the search pattern. The escape character is specified on the SQL_ATTR_ESCAPE_CHAR
environment attribute.
This function does not return information about the columns in a result set, which is retrieved by
SQLDescribeCol() or SQLColAttribute(). If an application wants to obtain column information for a result
set, it should always call SQLDescribeCol() or SQLColAttribute() for efficiency. SQLColumns() maps to a
complex query against the system catalogs, and can require a large amount of system resources.
Table 34. Columns returned by SQLColumns
Column number/name Data type Description
1 TABLE_CAT VARCHAR(128) The current server.
2 TABLE_SCHEM VARCHAR(128) The name of the schema containing
TABLE_NAME.
3 TABLE_NAME VARCHAR(128) Name of the table, view or alias.
4 COLUMN_NAME VARCHAR(128) Column identifier. The name of the column of
the specified view, table, or table's column the
alias is built for.
5 DATA_TYPE SMALLINT not NULL DATA_TYPE identifies the SQL data type of the
column.
6 TYPE_NAME VARCHAR(128) not NULL TYPE_NAME is a character string representing
the name of the data type corresponding to
DATA_TYPE. If the data type is FOR BIT DATA,
then the corresponding string FOR BIT DATA is
appended to the data type, for example, CHAR
() FOR BIT DATA.
7 COLUMN_SIZE INTEGER If DATA_TYPE is an approximate numeric data
type, this column contains the number of bits of
mantissa precision of the column. For exact
numeric data types, this column contains the
total number of decimal digit allowed in the
column. For time and timestamp data types, this
column contains the number of digits of
precision of the fractional seconds component;
otherwise, this column is NULL.
Note: The ODBC definition of precision is
typically the number of digits to store the data
type.
8 BUFFER_LENGTH INTEGER The maximum number of bytes to store data
from this column if SQL_DEFAULT were
specified on the SQLBindCol() , SQLGetData()and
SQLBindParam() calls.
9 DECIMAL_DIGITS SMALLINT The scale of the column. NULL is returned for
data types where scale is not applicable.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 35. SQLColumns SQLSTATEs
SQLSTATE Description Explanation
HY001 Memory allocation failure The driver is unable to allocate
memory required to support the
processing or completion of the
function.
HY009 String or buffer length that is not The value of one of the name length
valid arguments is less than 0, but not
equal SQL_NTS.
HY010 Function sequence error There is an open cursor for this
statement handle, or there is no
connection for this statement handle.
HY021 Internal descriptor that is not valid The internal descriptor cannot be
addressed or allocated, or it contains
a value that is not valid.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLConnectW(). Refer to “Unicode in DB2 for iCLI” on page 305 for
more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLConnect (SQLHDBC hdbc,
SQLCHAR *szDSN,
SQLSMALLINT cbDSN,
SQLCHAR *szUID,
SQLSMALLINT cbUID,
SQLCHAR *szAuthStr,
SQLSMALLINT cbAuthStr);
Function arguments
Table 36. SQLConnect arguments
Data type Argument Use Description
SQLHDBC hdbc Input Connection handle.
SQLCHAR * szDSN Input Data source: name or alias name of the
database.
SQLSMALLINT cbDSN Input Length of contents of szDSN argument.
SQLCHAR * szUID Input Authorization name (user identifier).
SQLSMALLINT cbUID Input Length of contents of szUID argument.
SQLCHAR * szAuthStr Input Authentication string (password).
SQLSMALLINT cbAuthStr Input Length of contents of szAuthStr argument.
Usage
You can define various connection characteristics (options) in the application using
SQLSetConnectOption().
The input length arguments to SQLConnect() (cbDSN, cbUID, cbAuthStr) can be set to the actual length of
their associated data. This does not include any null-terminating character or to SQL_NTS to indicate that
the associated data is null-terminated.
Leading and trailing blanks in the szDSN and szUID argument values are stripped before processing
unless they are enclosed in quotation marks.
When running in server mode, both szUID and szAuthStr must be passed in order for the connection to
run on behalf of a user ID other than the current user. If either parameter is NULL or both are NULL, the
connection is started using the user ID that is in effect for the current job running the CLI program.
The data source must already be defined on the system for the connect function to work. On the System
i® platform, you can use the Work with Relational Database Directory Entries (WRKRDBDIRE) command
to determine which data sources have been defined, and to optionally define additional data sources.
If the application does not supply a target database (szDSN), the CLI uses the local database as the
default.
Non-server mode connections to the *LOCAL relational database do not lead to validation of the
connecting userid and password. The *CURUSR value will be used for the connection processing.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 37. SQLConnect SQLSTATEs
SQLSTATE Description Explanation
08001 Unable to connect to data The driver is unable to establish a connection with the
source data source (server).
08002 Connection in use The specified hdbc has been used to establish a
connection with a data source and the connection is still
open.
08004 Data source rejected The data source (server) rejected the establishment of the
establishment of connection connection.
28000 Authorization specification The value specified for the argument szUID or the value
that is not valid specified for the argument szAuthStr violated restrictions
defined by the data source.
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not The value specified for argument cbDSN is less than 0,
valid but not equal to SQL_NTS and the argument szDSN is
not a null pointer.
Restrictions
The implicit connection (or default database) option for IBM DBMSs is not supported. SQLConnect() must
be called before any SQL statements can be processed. i5/OS does not support multiple simultaneous
connections to the same data source in a single job.
When you are using DB2 for i CLI on a newer release, SQLConnect() can encounter an SQL0144 message.
This indicates that the data source (the server) has obsolete SQL packages that must be deleted. To delete
these packages, run the following command on the data source:
DLTSQLPKG SQLPKG(QGPL/QSQCLI*)
Example
References
v “SQLAllocConnect - Allocate connection handle” on page 26
v “SQLAllocStmt - Allocate a statement handle” on page 33
Any existing data in the data structure associated with the target handle is overwritten, except that the
ALLOC_TYPE field is not changed.
Syntax
SQLRETURN SQLCopyDesc (SQLHDESC sDesc)
(SQLHDESC tDesc);
Function arguments
Table 38. SQLCopyDesc arguments
Data type Argument Use Description
SQLHDESC sDesc Input Source descriptor handle
SQLHDESC tDesc Input Target descriptor handle
Usage
Handles for the automatically-generated row and parameter descriptors of a statement can be obtained
by calling GetStmtAttr().
Return codes
v SQL_SUCCESS
v SQL_INVALID_HANDLE
v SQL_ERROR
For more information about cataloging, refer to the usage notes for SQLConnect() or see the online help
for the Work with Relational Database (RDB) Directory Entries (WRKRDBDIRE) command.
SQLDataSources() is typically called before a connection is made, to determine the databases that are
available to connect to.
If you are running DB2 for i CLI in SQL server mode, some restrictions apply when you use
SQLDataSources().
For more information about running in server mode refer to the “Restrictions for running DB2 for i CLI
in server mode” on page 304.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLDataSourcesW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLDataSources (SQLHENV EnvironmentHandle,
SQLSMALLINT Direction,
SQLCHAR *ServerName,
SQLSMALLINT BufferLength1,
SQLSMALLINT *NameLength1Ptr,
SQLCHAR *Description,
SQLSMALLINT BufferLength2,
SQLSMALLINT *NameLength2Ptr);
Function arguments
Table 39. SQLDataSources arguments
Data type Argument Use Description
SQLHENV EnvironmentHandle Input Environment handle.
SQLSMALLINT Direction Input This is used by application to request the first data
source name in the list or the next one in the list.
Direction can take on only the following values:
v SQL_FETCH_FIRST
v SQL_FETCH_NEXT
SQLCHAR * ServerName Output Pointer to buffer to hold the data source name
retrieved.
SQLSMALLINT BufferLength1 Input Maximum length in characters of the buffer pointed
to by ServerName. This should be less than or equal
to SQL_MAX_DSN_LENGTH + 1.
SQLSMALLINT * NameLength1Ptr Output Pointer to location where the maximum number of
characters available to return in the ServerName is
stored.
SQLCHAR * Description Output Pointer to buffer where the description of the data
source is returned. DB2 for i CLI returns the
Comment field associated with the database
catalogued to the Database Management System
(DBMS).
Usage
The application can call this function any time by setting Direction to either SQL_FETCH_FIRST or
SQL_FETCH_NEXT.
If SQL_FETCH_NEXT is specified:
v Directly following the SQL_FETCH_FIRST call, the second database in the list is returned
v Before any other SQLDataSources() call, the first database in the list is returned
v When there are no more databases in the list, SQL_NO_DATA_FOUND is returned. If the function is
called again, the first database is returned.
v Any other time, the next database in the list is returned.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Error conditions
Table 40. SQLDataSources SQLSTATEs
SQLSTATE Description Explanation
01004 Data truncated The data source name returned in the argument ServerName is
longer than the value specified in the argument BufferLength1. The
argument NameLength1Ptr contains the length of the full data
source name. (Function returns SQL_SUCCESS_WITH_INFO.)
Authorization
None.
Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/* From CLI sample datasour.c */
/* ... */
#include <stdio.h>
#include <stdlib.h>
#include <sqlcli1.h>
#include "samputil.h" /* Header file for CLI sample code */
/* ... */
/*******************************************************************
** main
** - initialize
** - terminate
*******************************************************************/
int main() {
SQLHANDLE henv ;
SQLRETURN rc ;
SQLCHAR source[SQL_MAX_DSN_LENGTH + 1], description[255] ;
SQLSMALLINT buffl, desl ;
/* ... */
) != SQL_NO_DATA_FOUND
) printf( "%-30s %s\n", source, description ) ;
return( SQL_SUCCESS ) ;
If the application needs only one attribute of the descriptor information, the SQLColAttribute() function
can be used in place of SQLDescribeCol().
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLDescribeColW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLDescribeCol (SQLHSTMT hstmt,
SQLSMALLINT icol,
SQLCHAR *szColName,
SQLSMALLINT cbColNameMax,
SQLSMALLINT *pcbColName,
SQLSMALLINT *pfSqlType,
SQLINTEGER *pcbColDef,
SQLSMALLINT *pibScale,
SQLSMALLINT *pfNullable);
Function arguments
Table 41. SQLDescribeCol arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLSMALLINT icol Input Column number to be described.
SQLCHAR * szColName Output Pointer to column name buffer.
SQLSMALLINT cbColNameMax Input Size of szColName buffer.
SQLSMALLINT * pcbColName Output Bytes available to return for szColName
argument. Truncation of column name
(szColName) to cbColNameMax - 1 bytes
occurs if pcbColName is greater than or equal
to cbColNameMax. If pfSqlType denotes a
graphic SQL data type, this variable indicates
the maximum number of double-byte
characters the column can hold.
SQLSMALLINT * pfSqlType Output SQL data type of column.
SQLINTEGER * pcbColDef Output Precision of column as defined in the
database.
Usage
Columns are identified by a number and are numbered sequentially from left to right starting with 1, and
can be described in any order.
A valid pointer and buffer space must be made available for the szColName argument. If a null pointer is
specified for any of the remaining pointer arguments, DB2 for i CLI assumes that the information is not
needed by the application and nothing is returned.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*******************************************************************
** file = typical.c
...
/*******************************************************************
** display_results
**
** - for each column
** - get column name
** - bind column
** - display column headings
** - fetch each row
** - if value truncated, build error message
** - if column null, set value to "NULL"
** - display row
** - print truncation message
** - free local storage
*******************************************************************/
display_results(SQLHSTMT hstmt,
SQLSMALLINT nresultcols)
{
SQLCHAR colname[32];
SQLSMALLINT coltype;
SQLSMALLINT colnamelen;
SQLSMALLINT nullable;
SQLINTEGER collen[MAXCOLS];
SQLSMALLINT scale;
SQLINTEGER outlen[MAXCOLS];
SQLCHAR * data[MAXCOLS];
SQLCHAR errmsg[256];
SQLRETURN rc;
SQLINTEGER i;
SQLINTEGER displaysize;
References
v “SQLColAttribute - Return a column attribute” on page 62
v “SQLColAttributes - Obtain column attributes” on page 68
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLNumResultCols - Get number of result columns” on page 193
v “SQLPrepare - Prepare a statement” on page 199
Syntax
SQLRETURN SQLDescribeParam (SQLHSTMT StatementHandle,
SQLSMALLINT ParameterNumber,
SQLSMALLINT *DataTypePtr,
SQLINTEGER *ParameterSizePtr,
SQLSMALLINT *DecimalDigitsPtr,
SQLSMALLINT *NullablePtr);
Function arguments
Table 43. SQLDescribeParam arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLSMALLINT ParameterNumber Input Parameter marker number ordered sequentially in
increasing parameter order, starting at 1.
SQLSMALLINT * DataTypePtr Output Pointer to a buffer in which to return the SQL data
type of the parameter.
SQLINTEGER * ParameterSizePtr Output Pointer to a buffer in which to return the size of the
column or expression of the corresponding
parameter marker as defined by the data source.
SQLSMALLINT * DecimalDigitsPtr Output Pointer to a buffer in which to return the number of
decimal digits of the column or expression of the
corresponding parameter as defined by the data
source.
SQLSMALLINT * NullablePtr Output Pointer to a buffer in which to return a value that
indicates whether the parameter allows NULL
values. This value is read from the
SQL_DESC_NULLABLE field of the implementation
parameter descriptor.
v SQL_NO_NULLS – The parameter does not allow
NULL values (this is the default value).
v SQL_NULLABLE – The parameter allows NULL
values.
v SQL_NULLABLE_UNKNOWN – Cannot
determine if the parameter allows NULL values.
Usage
Parameter markers are numbered in increasing parameter order, starting with 1, in the order they appear
in the SQL statement.
SQLDescribeParam() does not return the type (input, output, or both input and output) of a parameter in
an SQL statement. Except in calls to procedures, all parameters in SQL statements are input parameters.
To determine the type of each parameter in a call to a procedure, an application calls
SQLProcedureColumns().
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 44. SQLDescribeParam SQLSTATEs
SQLSTATE Description Explanation
01000 Warning Informational message. (Function returns
SQL_SUCCESS_WITH_INFO.)
07009 Descriptor index that is not valid The value specified for the argument
ParameterNumber less than 1.
Restrictions
None.
References
v “SQLBindParam - Bind a buffer to a parameter marker” on page 46
v “SQLCancel - Cancel statement” on page 60
v “SQLExecute - Execute a statement” on page 103
v “SQLPrepare - Prepare a statement” on page 199
After calling this function, either call SQLConnect() to connect to another database, or call
SQLFreeConnect().
Syntax
SQLRETURN SQLDisconnect (SQLHDBC hdbc);
Function arguments
Table 45. SQLDisconnect arguments
Data type Argument Use Description
SQLHDBC hdbc Input Connection handle
Usage
If an application calls SQLDisconnect before it has freed all the statement handles associated with the
connection, DB2 for i CLI frees them after it successfully disconnects from the database.
If SQL_SUCCESS_WITH_INFO is returned, it implies that even though the disconnect from the database
is successful, additional error or implementation specific information is available. For example:
v A problem is encountered on the clean up after the disconnect, or,
v If there is no current connection because of an event that occurred independently of the application
(such as communication failure).
After a successful SQLDisconnect() call, the application can re-use hdbc to make another SQLConnect()
request.
If the hdbc is participating in a DUOW two-phase commit connection, the disconnect might not occur
immediately. The actual disconnect occurs at the next commit issued for the distributed transaction.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 46. SQLDisconnect SQLSTATEs
SQLSTATE Description Explanation
01002 Disconnect error An error occurred during the disconnect. However, the
disconnect succeeded. (Function returns
SQL_SUCCESS_WITH_INFO.)
08003 Connection not open The connection specified in the argument hdbc is not
open.
25000 Transaction state that is not There is a transaction in process on the connection
valid specified by the argument hdbc. The transaction remains
active, and the connection cannot be disconnected.
58004 System error Unrecoverable system error.
Example
References
v “SQLAllocConnect - Allocate connection handle” on page 26
v “SQLConnect - Connect to a data source” on page 76
v “SQLTransact - Commit or roll back a transaction” on page 267
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLDriverConnectW(). Refer to “Unicode in DB2 for iCLI” on page
305 for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLDriverConnect (SQLHDBC ConnectionHandle,
SQLPOINTER WindowHandle,
SQLCHAR *InConnectionString,
SQLSMALLINT StringLength1,
SQLCHAR *OutConnectionString,
SQLSMALLINT BufferLength,
SQLSMALLINT *StringLength2Ptr,
SQLSMALLINT DriverCompletion);
Function arguments
Table 47. SQLDriverConnect arguments
Data type Argument Use Description
SQLHDBC ConnectionHandle Input Connection handle.
SQLPOINTER WindowHandle Input For DB2 for Linux, UNIX, and Windows, this is the
parent handle. On i5/OS, it is ignored.
SQLCHAR * InConnectionString Input A full, partial, or empty (null pointer) connection
string.
SQLSMALLINT StringLength1 Input Length of InConnectionString.
SQLCHAR * OutConnectionString Output Pointer to buffer for the completed connection string.
Possible values:
v SQL_DRIVER_COMPLETE
v SQL_DRIVER_COMPLETE_REQUIRED
v SQL_DRIVER_NOPROMPT
Usage
The connection string is used to pass one or more values that are needed to complete a connection. The
contents of the connection string and the value of DriverCompletion determine how the connection should
be established.
| ;
| DSN
UID
PWD
DB2 CLI-defined-keyword
|
Input user ID and password strings passed in argument InConnectionString are treated as case sensitive.
The value of DriverCompletion is verified to be valid, but all result in the same behavior. A connection is
attempted with the information that is contained in the connection string. If there is not enough
information, SQL_ERROR is returned.
As soon as a connection is established, the complete connection string is returned. Applications that need
to set up multiple connections to the same database for a given user ID should store this output
connection string. This string can then be used as the input connection string value on future
SQLDriverConnect() calls.
Non-server mode connections to the *LOCAL relational database do not lead to validation of the
connecting userid and password. The *CURUSR value will be used for the connection processing.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_NO_DATA_FOUND
v SQL_INVALID_HANDLE
v SQL_ERROR
Error conditions
All of the diagnostics that are generated by SQLConnect() can be returned here as well. The following
table shows the additional diagnostics that can be returned.
Restrictions
None.
Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/* From CLI sample drivrcon.c */
/* ... */
/********************************************************************
** drv_connect - Prompt for connect options and connect **
********************************************************************/
int
drv_connect(SQLHENV henv,
SQLHDBC * hdbc,
SQLCHAR con_type)
{
SQLRETURN rc;
SQLCHAR server[SQL_MAX_DSN_LENGTH + 1];
SQLCHAR uid[MAX_UID_LENGTH + 1];
SQLCHAR pwd[MAX_PWD_LENGTH + 1];
SQLCHAR con_str[255];
SQLCHAR buffer[255];
SQLSMALLINT outlen;
rc = SQLDriverConnect(*hdbc,
(SQLPOINTER) NULL,
con_str,
SQL_NTS,
buffer, 255, &outlen,
SQL_DRIVER_NOPROMPT);
if (rc != SQL_SUCCESS) {
printf("Error while connecting to database, RC= %ld\n", rc);
CHECK_HANDLE( SQL_NULL_HENV, *hdbc, rc);
return (SQL_ERROR);
} else {
printf("Successful Connect\n");
return (SQL_SUCCESS);
}
}
References
All changes to the database that have been made on the connection since connect time or the previous
call to SQLEndTran(), whichever is the most recent, are committed or rolled back.
If a transaction is active on a connection, the application must call SQLEndTran() before it can disconnect
from the database.
Syntax
SQLRETURN SQLEndTran (SQLSMALLINT hType,
SQLHENV handle,
SQLSMALLINT fType);
Function arguments
Table 49. SQLEndTran arguments
Data type Argument Use Description
SQLSMALLINT hType Input Type of handle. It must contain
SQL_HANDLE_ENV or SQL_HANDLE_DBC.
SQLHENV handle Input Handle to use when performing the COMMIT or
ROLLBACK.
SQLSMALLINT fType Input Wanted action for the transaction. The value for this
argument must be one of:
v SQL_COMMIT
v SQL_ROLLBACK
v SQL_COMMIT_HOLD
v SQL_ROLLBACK_HOLD
v SQL_SAVEPOINT_NAME_ROLLBACK
v SQL_SAVEPOINT_NAME_RELEASE
Usage
If no transaction is currently active on the connection, calling SQLEndTran() has no effect on the database
server and returns SQL_SUCCESS.
SQLEndTran() might fail while executing the COMMIT or ROLLBACK due to a loss of connection. In this
case the application might be unable to determine whether the COMMIT or ROLLBACK has been
processed, and a database administrator's help might be required. Refer to the Database Management
System (DBMS) product information for more information about transaction logs and other transaction
management tasks.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 50. SQLEndTran SQLSTATEs
SQLSTATE Description Explanation
08003 Connection not open The hdbc is not in a connected state.
08007 Connection failure during The connection associated with the hdbc fails during the
transaction processing of the function during the processing of the
function and it cannot be determined whether the requested
COMMIT or ROLLBACK occurs before the failure.
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to support
the processing or completion of the function.
HY010 Function sequence error SQL_SAVEPOINT_NAME_ROLLBACK or
SQL_SAVEPOINT_NAME_RELEASE is used, but the
savepoint name is not established by calling
SQLSetConnectAttr() for attribute
SQL_ATTR_SAVEPOINT_NAME.
HY012 Transaction operation state The value specified for the argument fType is neither
that is not valid SQL_COMMIT nor SQL_ROLLBACK.
HY013 * Memory management The driver is unable to access memory required to support
problem the processing or completion of the function.
The information consists of a standardized SQLSTATE, an error code, and a text message. Refer to
“Diagnostics in a DB2 for i CLI application” on page 16 for more information.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLErrorW(). Refer to “Unicode in DB2 for iCLI” on page 305 for
more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLError (SQLHENV henv,
SQLHDBC hdbc,
SQLHSTMT hstmt,
SQLCHAR *szSqlState,
SQLINTEGER *pfNativeError,
SQLCHAR *szErrorMsg,
SQLSMALLINT cbErrorMsgMax,
SQLSMALLINT *pcbErrorMsg);
Function arguments
Table 51. SQLError arguments
Data type Argument Use Description
SQLHENV henv Input Environment handle. To obtain diagnostic
information associated with an environment,
pass a valid environment handle. Set hdbc to
SQL_NULL_HDBC. Set hstmt to
SQL_NULL_HSTMT.
SQLHDBC hdbc Input Database connection handle. To obtain
diagnostic information associated with a
connection, pass a valid database connection
handle, and set hstmt to SQL_NULL_HSTMT.
The henv argument is ignored.
SQLHSTMT hstmt Input Statement handle. To obtain diagnostic
information associated with a statement, pass
a valid statement handle. The henv and hdbc
arguments are ignored.
SQLCHAR * szSqlState Output SQLSTATE as a string of 5 characters
terminated by a null character. The first 2
characters indicate error class; the next 3
indicate subclass. The values correspond
directly to SQLSTATE values defined in the
X/Open SQL CAE specification and the
ODBC specification, augmented with IBM
specific and product specific SQLSTATE
values.
Usage
The SQLSTATEs are those defined by the X/OPEN SQL CAE and the X/Open SQL CLI snapshot,
augmented with IBM specific and product specific SQLSTATE values.
v To obtain diagnostic information associated with an environment, pass a valid environment handle. Set
hdbc to SQL_NULL_HDBC. Set hstmt to SQL_NULL_HSTMT.
v To obtain diagnostic information associated with a connection, pass a valid database connection handle,
and set hstmt to SQL_NULL_HSTMT. The henv argument is ignored.
v To obtain diagnostic information associated with a statement, pass a valid statement handle. The henv
and hdbc arguments are ignored.
If diagnostic information generated by one DB2 for i CLI function is not retrieved before a function other
than SQLError() is called with the same handle, the information for the previous function call is lost. This
is true whether diagnostic information is generated for the second DB2 for i CLI function call.
To avoid truncation of the first level error message, declare a buffer length of
SQL_MAX_MESSAGE_LENGTH + 1. To avoid truncation of the second level error message, set the size
of the buffer to a value greater than SQL_MAX_MESSAGE_LENGTH.
Return codes
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
v SQL_SUCCESS
Diagnostics
SQLSTATEs are not defined because SQLError() does not generate diagnostic information for itself.
SQL_ERROR is returned if argument szSqlState, pfNativeError, szErrorMsg, or pcbErrorMsg is a null
pointer.
Example
SQL call level interface 99
SQLError
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*************************************************************************
** file = typical.c
************************************************************************/
int print_error (SQLHENV henv,
SQLHDBC hdbc,
SQLHSTMT hstmt)
{
SQLCHAR buffer[SQL_MAX_MESSAGE_LENGTH + 1];
SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1];
SQLINTEGER sqlcode;
SQLSMALLINT length;
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLExecDirectW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLExecDirect (SQLHSTMT hstmt,
SQLCHAR *szSqlStr,
SQLINTEGER cbSqlStr);
Function arguments
Table 52. SQLExecDirect arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle. There must not be an
open cursor associated with hstmt. See
“SQLFreeStmt - Free (or reset) a statement
handle” on page 123 for more information.
SQLCHAR * szSqlStr Input SQL statement string. The connected
database server must be able to prepare the
statement.
SQLINTEGER cbSqlStr Input Length of contents of szSqlStr argument. The
length must be set to either the exact length
of the statement, or if the statement is
null-terminated, set to SQL_NTS.
Usage
The SQL statement cannot be a COMMIT or ROLLBACK. Instead, SQLTransact() must be called to issue
COMMIT or ROLLBACK. For more information about supported SQL statements refer to Table 1 on page
3.
The SQL statement string might contain parameter markers. A parameter marker is represented by a "?"
character, and indicates a position in the statement where the value of an application variable is to be
substituted, when SQLExecDirect() is called. SQLBindParam() binds (or associates) an application variable
to each parameter marker, to indicate if any data conversion should be performed at the time the data is
transferred. All parameters must be bound before calling SQLExecDirect().
If the SQL statement is a SELECT, SQLExecDirect() generates a cursor name, and open the cursor. If the
application has used SQLSetCursorName() to associate a cursor name with the statement handle, DB2 for i
CLI associates the application generated cursor name with the internally generated one.
To retrieve a row from the result set generated by a SELECT statement, call SQLFetch() after
SQLExecDirect() returns successfully.
If the SQL statement is a Positioned DELETE or a Positioned UPDATE, the cursor referenced by the
statement must be positioned on a row. Additionally the SQL statement must be defined on a separate
statement handle under the same connection handle.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Diagnostics
Table 53. SQLExecDirect SQLSTATEs
SQLSTATE Description Explanation
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value The argument szSqlStr is a null pointer.
Example
References
v “SQLExecute - Execute a statement” on page 103
v “SQLFetch - Fetch next row” on page 107
v “SQLSetParam - Set parameter” on page 244
Syntax
SQLRETURN SQLExecute (SQLHSTMT hstmt);
Function arguments
Table 54. SQLExecute arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle. There must not be an
open cursor associated with hstmt, see
“SQLFreeStmt - Free (or reset) a statement
handle” on page 123 for more information.
Usage
The SQL statement string might contain parameter markers. A parameter marker is represented by a "?"
character, and indicates a position in the statement where the value of an application variable is to be
substituted, when SQLExecute() is called. SQLBindParam() is used to bind (or associate) an application
variable to each parameter marker, and to indicate if any data conversion should be performed at the
time the data is transferred. All parameters must be bound before calling SQLExecute().
As soon as the application has processed the results from the SQLExecute() call, it can process the
statement again with new (or the same) values in the application variables.
If the prepared SQL statement is a SELECT, SQLExecute() generates a cursor name, and opens the cursor.
If the application has used SQLSetCursorName() to associate a cursor name with the statement handle,
DB2 for i CLI associates the application generated cursor name with the internally generated cursor
name.
To process a SELECT statement more than once, the application must close the cursor by calling call
SQLFreeStmt() with the SQL_CLOSE option. There must not be an open cursor on the statement handle
when calling SQLExecute().
To retrieve a row from the result set generated by a SELECT statement, call SQLFetch() after
SQLExecute() returns successfully.
| If the SQL statement is a positioned DELETE or a positioned UPDATE statement, the cursor referenced
| by the statement must be positioned on a row at the time SQLExecute() is called, and must be defined on
| a separate statement handle under the same connection handle.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Diagnostics
The SQLSTATEs for SQLExecute() include all those for SQLExecDirect() (see Table 53 on page 102) except
for HY009, and with the addition of the SQLSTATEs in the following table.
| Table 55. SQLExecute SQLSTATEs
| SQLSTATE Description Explanation
| HY009 Statement option is not Attributes associated with the statement being executed
| valid are not valid.
| HY010 Function sequence error The specified hstmt is not in prepared state. SQLExecute()
| is called without first calling SQLPrepare.
| HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
| not valid or it contains a value that is not valid.
| Note: There are many other SQLSTATE values that can be generated by the Database Management System (DBMS),
| on processing of the statement.
|
Example
References
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLPrepare - Prepare a statement” on page 199
v “SQLFetch - Fetch next row” on page 107
v “SQLSetParam - Set parameter” on page 244
Syntax
SQLRETURN SQLExtendedFetch (SQLHSTMT StatementHandle,
SQLSMALLINT FetchOrientation,
SQLINTEGER FetchOffset,
SQLINTEGER *RowCountPtr,
SQLSMALLINT *RowStatusArray);
Function arguments
Table 56. SQLExtendedFetch arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLSMALLINT FetchOrientation Input Fetch orientation. See Table 61 on page 113 for
possible values.
SQLINTEGER FetchOffset Input Row offset for relative positioning.
SQLINTEGER * RowCountPtr Output Number of the rows actually fetched. If an error
occurs during processing, RowCountPtr points to the
ordinal position of the row (in the rowset) that
precedes the row where the error occurred. If an
error occurs retrieving the first row RowCountPtr
points to the value 0.
SQLSMALLINT * RowStatusArray Output An array of status values. The number of elements
must equal the number of rows in the rowset (as
defined by the SQL_ROWSET_SIZE attribute). A
status value for each row fetched is returned:
v SQL_ROW_SUCCESS
Usage
SQLExtendedFetch() is used to perform an array fetch of a set of rows. An application specifies the size of
the array by calling SQLSetStmtAttr() with the SQL_ROWSET_SIZE attribute.
Before SQLExtendedFetch() is called the first time, the cursor is positioned before the first row. After
SQLExtendedFetch() is called, the cursor is positioned on the row in the result set corresponding to the
last row element in the rowset just retrieved.
For any columns in the result set that have been bound by the SQLBindCol() function, DB2 for i CLI
converts the data for the bound columns as necessary and stores it in the locations bound to these
columns. The result set must be bound in a row-wise fashion. This means that the values for all the
columns of the first row are contiguous, followed by the values of the second row, and so on. Also, if
indicator variables are used, they are all returned in one contiguous storage location.
When using this procedure to retrieve multiple rows, all columns must be bound, and the storage must
be contiguous. When using this function to retrieve rows from an SQL procedure result set, only the
SQL_FETCH_NEXT orientation is supported. The user is responsible for allocating enough storage for the
number of rows that are specified in SQL_ROWSET_SIZE.
The cursor must be a scrollable cursor for SQLExtendedFetch() to use any orientation other than
SQL_FETCH_NEXT. See “SQLSetStmtAttr - Set a statement attribute” on page 245 for information about
setting the SQL_ATTR_CURSOR_SCROLLABLE attribute.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Error conditions
| Table 57. SQLExtendedFetch SQLSTATEs
| SQLSTATE Description Explanation
| HY009 Argument value that is not valid
| The argument value RowCountPtr or RowStatusArray is a null
| pointer.
Restrictions
None.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLExecute - Execute a statement” on page 103
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLFetch - Fetch next row” on page 107
SQLFetch() can be used to receive the data directly into variables that you specify with SQLBindCol(), or
the columns can be received individually after the fetch by calling SQLGetData(). Data conversion is also
performed when SQLFetch() is called, if conversion is indicated when the column is bound.
Syntax
SQLRETURN SQLFetch (SQLHSTMT hstmt);
Function arguments
Table 58. SQLFetch arguments
Data type argument Use Description
SQLHSTMT hstmt Input Statement handle
Usage
SQLFetch() can only be called if the most recently processed statement on hstmt is a SELECT.
The number of application variables bound with SQLBindCol() must not exceed the number of columns
in the result set; otherwise SQLFetch() fails.
If SQLBindCol() has not been called to bind any columns, then SQLFetch() does not return data to the
application, but just advances the cursor. In this case SQLGetData() can then be called to obtain all of the
columns individually. Data in unbound columns is discarded when SQLFetch() advances the cursor to the
next row.
If any bound variables are not large enough to hold the data returned by SQLFetch(), the data is
truncated. If character data is truncated, and the SQLSetEnvAttr() attribute
SQL_ATTR_TRUNCATION_RTNC is set to SQL_TRUE, then the CLI return code
SQL_SUCCESS_WITH_INFO is returned, along with an SQLSTATE that indicates truncation. Note that
the default is SQL_FALSE for SQL_ATTR_TRUNCATION_RTNC. Also, in the case of character data
truncation, the SQLBindCol() deferred output argument pcbValue contains the actual length of the column
data retrieved from the data source. The application should compare the output length to the input
length (pcbValue and cbValueMax arguments from SQLBindCol()) to determine which character columns
have been truncated.
Truncation of numeric data types is not reported if the truncation involves digits to the right of the
decimal point. If truncation occurs to the left of the decimal point, an error is returned (refer to the
diagnostics section).
Truncation of graphic data types is treated the same as character data types. Except the rgbValue buffer is
filled to the nearest multiple of two bytes that is still less than or equal to the cbValueMax specified in
SQLBindCol(). Graphic data transferred between DB2 for i CLI and the application is never
null-terminated.
When all the rows have been retrieved from the result set, or the remaining rows are not needed,
SQLFreeStmt() should be called to close the cursor and discard the remaining data and associated
resources.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
SQL_NO_DATA_FOUND is returned if there are no rows in the result set, or previous SQLFetch() calls
have fetched all the rows from the result set.
Diagnostics
Table 59. SQLFetch SQLSTATEs
SQLSTATE Description Explanation
01004 Data truncated The data returned for one or more columns is truncated.
String values are right truncated.
(SQL_SUCCESS_WITH_INFO is returned if no error
occurred.)
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY010 Function sequence error The specified hstmt is not in an processed state. The
function is called without first calling SQLExecute or
SQLExecDirect.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
not valid or it contains a value that is not valid.
Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*************************************************************************
** file = fetch.c
**
** Example of executing an SQL statement.
** SQLBindCol & SQLFetch is used to retrieve data from the result set
** directly into application storage.
**
** Functions used:
**
** SQLAllocConnect SQLFreeConnect
** SQLAllocEnv SQLFreeEnv
** SQLAllocStmt SQLFreeStmt
** SQLConnect SQLDisconnect
**
** SQLBindCol SQLFetch
** SQLTransact SQLExecDirect
** SQLError
**
**************************************************************************/
#include <stdio.h>
#include <string.h>
#include "sqlcli.h"
/*******************************************************************
** main
** - initialize
** - terminate
*******************************************************************/
int main()
{
SQLHENV henv;
SQLHDBC hdbc;
SQLCHAR sqlstmt[MAX_STMT_LEN + 1]="";
SQLRETURN rc;
rc = initialize(&henv, &hdbc);
if (rc == SQL_ERROR) return(terminate(henv, hdbc));
{SQLHSTMT hstmt;
SQLCHAR sqlstmt[]="SELECT deptname, location from org where division = ’Eastern’";
SQLCHAR deptname[15],
location[14];
SQLINTEGER rlength;
rc = SQLAllocStmt(hdbc, &hstmt);
if (rc != SQL_SUCCESS )
check_error (henv, hdbc, SQL_NULL_HSTMT, rc);
rc = SQLFreeStmt(hstmt, SQL_DROP);
if (rc != SQL_SUCCESS )
check_error (henv, hdbc, SQL_NULL_HSTMT, rc);
}
terminate(henv, hdbc);
return (0);
}/* end main */
/*******************************************************************
** initialize
** - allocate environment handle
** - allocate connection handle
** - prompt for server, user id, & password
** - connect to server
*******************************************************************/
if (uid[0] == ’\0’)
{ rc = SQLConnect (*hdbc, server, SQL_NTS, NULL, SQL_NTS, NULL, SQL_NTS);
if (rc != SQL_SUCCESS )
check_error (*henv, *hdbc, SQL_NULL_HSTMT, rc);
}
else
{ rc = SQLConnect (*hdbc, server, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);
if (rc != SQL_SUCCESS )
check_error (*henv, *hdbc, SQL_NULL_HSTMT, rc);
}
return(SQL_SUCCESS);
}/* end initialize */
/*******************************************************************
** terminate
** - disconnect
** - free connection handle
** - free environment handle
*******************************************************************/
int terminate(SQLHENV henv,
SQLHDBC hdbc)
{
SQLRETURN rc;
return(rc);
}/* end terminate */
/*******************************************************************
** - print_error - call SQLError(), display SQLSTATE and message
*******************************************************************/
return ( SQL_ERROR);
} /* end print_error */
/*******************************************************************
** - check_error - call print_error(), checks severity of return code
*******************************************************************/
int check_error (SQLHENV henv,
SQLHDBC hdbc,
SQLHSTMT hstmt,
SQLRETURN frc)
{
SQLRETURN rc;
switch (frc){
case SQL_SUCCESS : break;
case SQL_ERROR :
case SQL_INVALID_HANDLE:
printf("\n ** FATAL ERROR, Attempting to rollback transaction **\n");
rc = SQLTransact(henv, hdbc, SQL_ROLLBACK);
if (rc != SQL_SUCCESS)
printf("Rollback Failed, Exiting application\n");
else
printf("Rollback Successful, Exiting application\n");
terminate(henv, hdbc);
exit(frc);
break;
case SQL_SUCCESS_WITH_INFO :
printf("\n ** Warning Message, application continuing\n");
break;
case SQL_NO_DATA_FOUND :
printf("\n ** No Data Found ** \n");
break;
default :
printf("\n ** Invalid Return Code ** \n");
printf(" ** Attempting to rollback transaction **\n");
SQLTransact(henv, hdbc, SQL_ROLLBACK);
terminate(henv, hdbc);
exit(frc);
break;
}
return(SQL_SUCCESS);
} /* end check_error */
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLExecute - Execute a statement” on page 103
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLGetCol - Retrieve one column of a row of the result set” on page 125
v “SQLFetchScroll - Fetch from a scrollable cursor” on page 113
SQLFetchScroll() can be used to receive the data directly into variables that you specify with
SQLBindCol(), or the columns can be received individually after the fetch by calling SQLGetData(). Data
conversion is also performed when SQLFetchScroll() is called, if conversion is indicated when the
column is bound.
Syntax
SQLRETURN SQLFetchScroll (SQLHSTMT hstmt,
SQLSMALLINT fOrient,
SQLINTEGER fOffset);
Function arguments
Table 60. SQLFetchScroll arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLSMALLINT fOrient Input Fetch orientation. See Table 61 for possible
values.
SQLINTEGER fOffset Input Row offset for relative positioning.
Usage
SQLFetchScroll() can only be called if the most recently processed statement on hstmt is a SELECT.
SQLFetchScroll() acts like SQLFetch(), except the fOrient parameter positions the cursor before any data
is retrieved. The cursor must be a scrollable cursor for SQLFetchScroll() to use any orientation other
than SQL_FETCH_NEXT.
When using this function to retrieve rows from an SQL procedure result set, only the SQL_FETCH_NEXT
orientation is supported.
SQLFetchScroll() supports array fetch, an alternative to the array fetch support provided by
SQLExtendedFetch(). See the SQLExtendedFetch() topic for details on array fetch.
The information returned in the RowCountPtr and RowStatusArray parameters of SQLExtendedFetch() are
handled by SQLFetchScroll() as follows:
v RowCountPtr: SQLFetchScroll() returns the number of rows fetched in the buffer pointed to by the
SQL_ATTR_ROWS_FETCHED_PTR statement attribute.
v RowStatusArray: SQLFetchScroll() returns the array of statuses for each row in the buffer pointed to by
the SQL_ATTR_ROW_STATUS_PTR statement attribute.
Table 61. Statement attributes
fOrient Description
SQL_FETCH_ABSOLUTE Move to the result set row specified by the fOffset
argument.
SQL_FETCH_FIRST Move to the first row of the result set.
SQL_FETCH_LAST Move to the last row of the result set.
SQL_FETCH_NEXT Move to the row following the current cursor position.
SQL_FETCH_PRIOR Move to the row preceding the current cursor position.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Diagnostics
| Table 62. SQLFetchScroll SQLSTATEs
| SQLSTATE Description Explanation
| 01004 Data truncated The data returned for one or more columns is truncated.
| String values are right truncated.
| (SQL_SUCCESS_WITH_INFO is returned if no error
| occurred.)
| HY001 Memory allocation failure The driver is unable to allocate memory required to
| support the processing or completion of the function.
| HY009 Argument value that is not Orientation that is not valid.
| valid
| HY010 Function sequence error The specified hstmt is not in an processed state. The
| function is called without first calling SQLExecute or
| SQLExecDirect.
| HY013 * Memory management The driver is unable to access memory required to
| problem support the processing or completion of the function.
| HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
| not valid or it contains a value that is not valid.
|
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLExecute - Execute a statement” on page 103
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLExtendedFetch - Fetch array of rows” on page 105
v “SQLGetCol - Retrieve one column of a row of the result set” on page 125
v “SQLFetch - Fetch next row” on page 107
v “SQLSetStmtAttr - Set a statement attribute” on page 245
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLForeignKeysW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLForeignKeys (SQLHSTMT StatementHandle,
SQLCHAR *PKCatalogName,
SQLSMALLINT NameLength1,
SQLCHAR *PKSchemaName,
SQLSMALLINT NameLength2,
SQLCHAR *PKTableName,
SQLSMALLINT NameLength3,
SQLCHAR *FKCatalogName,
SQLSMALLINT NameLength4,
SQLCHAR *FKSchemaName,
SQLSMALLINT NameLength5,
SQLCHAR *FKTableName,
SQLSMALLINT NameLength6);
Function arguments
Table 63. SQLForeignKeys arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLCHAR * PKCatalogName Input Catalog qualifier of the primary key table. This must
be a NULL pointer or a zero length string.
SQLSMALLINT NameLength1 Input Length of PKCatalogName. This must be set to 0.
SQLCHAR * PKSchemaName Input Schema qualifier of the primary key table.
SQLSMALLINT NameLength2 Input Length of PKSchemaName.
SQLCHAR * PKTableName Input Name of the table name containing the primary key.
SQLSMALLINT NameLength3 Input Length of PKTableName.
SQLCHAR * FKCatalogName Input Catalog qualifier of the table containing the foreign
key. This must be a NULL pointer or a zero length
string.
SQLSMALLINT NameLength4 Input Length of FKCatalogName. This must be set to 0.
SQLCHAR * FKSchemaName Input Schema qualifier of the table containing the foreign
key.
SQLSMALLINT NameLength5 Input Length of FKSchemaName.
SQLCHAR * FKTableName Input Name of the table containing the foreign key.
SQLSMALLINT NameLength6 Input Length of FKTableName.
Usage
If PKTableName contains a table name, and FKTableName is an empty string, SQLForeignKeys() returns a
result set that contains the primary key of the specified table and all of the foreign keys (in other tables)
that refer to it.
If FKTableName contains a table name, and PKTableName is an empty string, SQLForeignKeys() returns a
result set that contains all of the foreign keys in the specified table and the primary keys (in other tables)
to which they refer.
If both PKTableName and FKTableName contain table names, SQLForeignKeys() returns the foreign keys in
the table specified in FKTableName that refer to the primary key of the table specified in PKTableName.
This should be one key at the most.
If the schema qualifier argument that is associated with a table name is not specified, then for the schema
name the default is the one currently in effect for the current connection.
Table 64 lists the columns of the result set generated by the SQLForeignKeys() call. If the foreign keys that
are associated with a primary key are requested, the result set is ordered by FKTABLE_CAT,
FKTABLE_SCHEM, FKTABLE_NAME, and ORDINAL_POSITION. If the primary keys that are associated
with a foreign key are requested, the result set is ordered by PKTABLE_CAT, PKTABLE_SCHEM,
PKTABLE_NAME, and ORDINAL_POSITION.
Although new columns might be added and the names of the existing columns might be changed in
future releases, the position of the current columns does not change.
Table 64. Columns returned by SQLForeignKeys
Column number/name Data type Description
1 PKTABLE_CAT VARCHAR(128) The current server.
2 PKTABLE_SCHEM VARCHAR(128) The name of the schema containing PKTABLE_NAME.
3 PKTABLE_NAME VARCHAR(128) Name of the table containing the primary key.
not NULL
4 PKCOLUMN_NAME VARCHAR(128) Primary key column name.
not NULL
5 FKTABLE_CAT VARCHAR(128) The current server.
6 FKTABLE_SCHEM VARCHAR(128) The name of the schema containing FKTABLE_NAME.
7 FKTABLE_NAME VARCHAR(128) The name of the table containing the Foreign key.
not NULL
8 FKCOLUMN_NAME VARCHAR(128) Foreign key column name.
not NULL
9 KEY_SEQ SMALLINT not The ordinal position of the column in the key, starting at 1.
NULL
10 UPDATE_RULE SMALLINT Action to be applied to the foreign key when the SQL operation is
UPDATE:
v SQL_RESTRICT
v SQL_NO_ACTION
The update rule for IBM DB2 DBMSs is always either RESTRICT or
SQL_NO_ACTION. However, ODBC applications might encounter
the following UPDATE_RULE values when connected to non-IBM
RDBMSs:
v SQL_CASCADE
v SQL_SET_NULL
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 65. SQLForeignKeys SQLSTATEs
SQLSTATE Description Explanation
24000 Cursor state that is not valid A cursor is already opened on the statement handle.
40003 08S01 Communication link failure The communication link between the application and data source
fails before the function is completed.
HY001 Memory allocation failure DB2 for i CLI is unable to allocate memory required to support
the processing or completion of the function.
HY009 Argument value that is not valid The arguments PKTableName and FKTableName were both NULL
pointers.
HY010 Function sequence error
HY014 No more handles DB2 for i CLI is unable to allocate a handle due to internal
resources.
HY021 Internal descriptor that is not The internal descriptor cannot be addressed or allocated, or it
valid contains a value that is not valid.
HY090 String or buffer length that is not The value of one of the name length arguments is less than 0, but
valid not equal to SQL_NTS.
Restrictions
None.
Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/* From CLI sample browser.c */
/* ... */
SQLRETURN list_foreign_keys( SQLHANDLE hstmt,
SQLCHAR * schema,
SQLCHAR * tablename
) {
/* ... */
rc = SQLForeignKeys(hstmt, NULL, 0,
schema, SQL_NTS, tablename, SQL_NTS,
NULL, 0,
NULL, SQL_NTS, NULL, SQL_NTS);
CHECK_HANDLE( SQL_HANDLE_STMT, hstmt, rc ) ;
References
v “SQLPrimaryKeys - Get primary key columns of a table” on page 203
v “SQLStatistics - Get index and statistics information for a base table” on page 257
Either SQLFreeEnv() is called next to continue ending the application, or SQLAllocHandle() is called to
allocate a new connection handle.
Syntax
SQLRETURN SQLFreeConnect (SQLHDBC hdbc);
Function arguments
Table 66. SQLFreeConnect arguments
Data type Argument Use Description
SQLHDBC hdbc Input Connection handle
Usage
If this function is called when a connection still exists, SQL_ERROR is returned, and the connection
handle remains valid.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 67. SQLFreeConnect SQLSTATEs
SQLSTATE Description Explanation
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY010 Function sequence error The function is called before SQLDisconnect() for the
hdbc.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
Example
References
v “SQLDisconnect - Disconnect from a data source” on page 90
v “SQLFreeEnv - Free environment handle” on page 121
This function is the last DB2 for i CLI step that an application needs before it ends.
Syntax
SQLRETURN SQLFreeEnv (SQLHENV henv);
Function arguments
Table 68. SQLFreeEnv arguments
Data type Argument Use Description
SQLHENV henv Input Environment handle
Usage
If this function is called when there is still a valid connection handle, SQL_ERROR is returned, and the
environment handle remains valid.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 69. SQLFreeEnv SQLSTATEs
SQLSTATE Description Explanation
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY010 Function sequence error There is an hdbc which is in allocated or connected state.
Call SQLDisconnect and SQLFreeConnect for the hdbc
before calling SQLFreeEnv.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
Example
References
Syntax
SQLRETURN SQLFreeHandle (SQLSMALLINT htype,
SQLINTEGER handle);
Function arguments
Table 70. SQLFreeHandle arguments
Data type Argument Use Description
SQLSMALLINT hType Input Handle type that must be
SQL_HANDLE_ENV, SQL_HANDLE_DBC,
SQL_HANDLE_STMT, or
SQL_HANDLE_DESC.
SQLINTEGER handle Input The handle to be freed.
Usage
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 71. SQLFreeHandle SQLSTATEs
SQLSTATE Description Explanation
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY010 Function sequence error There is an hdbc which is in allocated or connected state.
Call SQLDisconnect and SQLFreeConnect for the hdbc
before calling SQLFreeHandle.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
References
v “SQLFreeConnect - Free connection handle” on page 120
v “SQLFreeEnv - Free environment handle” on page 121
v “SQLFreeStmt - Free (or reset) a statement handle” on page 123
SQLFreeStmt() is called after executing an SQL statement and processing the results.
Syntax
SQLRETURN SQLFreeStmt (SQLHSTMT hstmt,
SQLSMALLINT fOption);
Function arguments
Table 72. SQLFreeStmt arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle
SQLSMALLINT fOption Input Option specifying the manner of freeing the
statement handle. The option must have one
of the following values:
v SQL_CLOSE
v SQL_DROP
v SQL_UNBIND
v SQL_RESET_PARAMS
Usage
To reuse a statement handle to run a different statement and if the previous statement:
v Was a SELECT, you must close the cursor.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_IN_HANDLE
Diagnostics
Table 73. SQLFreeStmt SQLSTATEs
SQLSTATE Description Explanation
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not The value specified for the argument fOption is not
valid SQL_CLOSE, SQL_DROP, SQL_UNBIND, or
SQL_RESET_PARAMS.
HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
not valid or it contains a value that is not valid.
Example
References
v “SQLAllocStmt - Allocate a statement handle” on page 33
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLFetch - Fetch next row” on page 107
v “SQLFreeConnect - Free connection handle” on page 120
v “SQLSetParam - Set parameter” on page 244
After calling SQLGetCol() for each column, SQLFetch() is called to retrieve the next row.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetColW(). Refer to “Unicode in DB2 for iCLI” on page 305 for
more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetCol (SQLHSTMT hstmt,
SQLSMALLINT icol,
SQLSMALLINT fCType,
SQLPOINTER rgbValue,
SQLINTEGER cbValueMax,
SQLINTEGER *pcbValue);
Function arguments
Table 74. SQLGetCol arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLSMALLINT icol Input Column number for which the data retrieval
is requested.
SQLSMALLINT fCType Input Application data type of the column
identified by icol. The following types are
supported:
v SQL_BIGINT
v SQL_BINARY
v SQL_BLOB
v SQL_CHAR
v SQL_CLOB
v SQL_DATETIME
v SQL_DBCLOB
v SQL_DECFLOAT
v SQL_DECIMAL
v SQL_DOUBLE
v SQL_FLOAT
v SQL_GRAPHIC
v SQL_INTEGER
v SQL_NUMERIC
v SQL_REAL
v SQL_SMALLINT
v SQL_TYPE_DATE
v SQL_TYPE_TIME
v SQL_TYPE_TIMESTAMP
v SQL_VARBINARY
v SQL_VARGRAPHIC
Usage
SQLGetCol() can be used with SQLBindCol() for the same row, as long as the value of icol does not specify
a column that has been bound. The general steps are:
1. SQLFetch() - advances cursor to first row, retrieves first row, transfers data for bound columns.
2. SQLGetCol() - transfers data for specified (unbound) column.
3. Repeat step 2 for each column needed.
4. SQLFetch() - advances cursor to next row, retrieves next row, transfers data for bound columns.
5. Repeat steps 2, 3 and 4 for each row in the result set, or until the result set is no longer needed.
SQLGetCol() retrieves long columns if the C data type (fCType) is SQL_CHAR or if fCType is
SQL_DEFAULT and the column type is CHAR or VARCHAR.
On each SQLGetCol() call, if the data available for return is greater than or equal to cbValueMax,
truncation occurs. A function return code of SQL_SUCCESS_WITH_INFO that is coupled with an
SQLSTATE that denotes data truncation indicates truncation. The application can call SQLGetCol() again,
with the same icol value, to obtain later data from the same unbound column starting at the point of
truncation. To obtain the entire column, the application repeats such calls until the function returns
SQL_SUCCESS. The next call to SQLGetCol() returns SQL_NO_DATA_FOUND.
To discard the column data part way through the retrieval, the application can call SQLGetCol() with icol
set to the next column position of interest. To discard unretrieved data for the entire row, the application
should call SQLFetch() to advance the cursor to the next row; or, if it is not interested in any more data
from the result set, call SQLFreeStmt() to close the cursor.
The fCType input argument determines the type of data conversion (if any) needed before the column
data is placed into the storage area pointed to by rgbValue.
The contents returned in rgbValue is always null-terminated unless SQLSetEnvAttr() is used to change
the SQL_ATTR_OUTPUT_NTS attribute or if the application is retrieving the data in multiple chunks. If
the application is retrieving the data in multiple chunks, the null-terminating byte is only added to the
last portion of data.
Truncation of numeric data types is not reported if the truncation involves digits to the right of the
decimal point. If truncation occurs to the left of the decimal point, an error is returned (refer to the
diagnostics section).
For decimal floating point data types, a precision of 32, 64, or 128 can be specified by using the default
symbolic C data type constants. For example, to specify a decimal floating point data type with a
precision of 128 bytes, ValueType can be set to SQL_C_DECIMAL128.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
SQL_NO_DATA_FOUND is returned when the preceding SQLGetCol() call has retrieved all of the data
for this column.
SQL_SUCCESS is returned if a zero-length string is retrieved by SQLGetCol(). If this is the case, pcbValue
contains 0, and rgbValue contains a null terminator.
If the preceding call to SQLFetch() fails, SQLGetCol() should not be called because the result is undefined.
Diagnostics
Table 75. SQLGetCol SQLSTATEs
SQLSTATE Description Explanation
07006 Restricted data type The data value cannot be converted to the C data type
attribute violation specified by the argument fCType.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not The value of the argument cbValueMax is less than 1 and
valid the argument fCType is SQL_CHAR.
Restrictions
ODBC requires that icol not specify a column of a lower number than the column last retrieved by
SQLGetCol() for the same row on the same statement handle. ODBC also does not permit the use of
SQLGetCol() to retrieve data for a column that resides before the last bound column, (if any columns in
the row have been bound).
DB2 for i CLI has relaxed both of these rules by allowing the value of icol to be specified in any order
and before a bound column, provided that icol does not specify a bound column.
Example
Refer to the example in the “SQLFetch - Fetch next row” on page 107 for a comparison between using
bound columns and using SQLGetCol().
Refer to “Example: Interactive SQL and the equivalent DB2 for i CLI function calls” on page 313 for a
listing of the check_error, initialize, and terminate functions used in the following example.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*************************************************************************
** file = getcol.c
**
** Example of directly executing an SQL statement.
** Getcol is used to retrieve information from the result set.
** Compare to fetch.c
**
** Functions used:
**
** SQLAllocConnect SQLFreeConnect
** SQLAllocEnv SQLFreeEnv
** SQLAllocStmt SQLFreeStmt
** SQLConnect SQLDisconnect
**
** SQLBindCol SQLFetch
** SQLTransact SQLError
** SQLExecDirect SQLGetCursor
**************************************************************************/
#include <stdio.h>
#include <string.h>
#include "sqlcli.h"
/*******************************************************************
** main
** - initialize
** - terminate
*******************************************************************/
int main()
{
SQLHENV henv;
SQLHDBC hdbc;
SQLCHAR sqlstmt[MAX_STMT_LEN + 1]="";
SQLRETURN rc;
rc = initialize(&henv, &hdbc);
if (rc != SQL_SUCCESS) return(terminate(henv, hdbc));
{SQLHSTMT hstmt;
SQLCHAR sqlstmt[]="SELECT deptname, location from org where division = ’Eastern’";
SQLCHAR deptname[15],
location[14];
SQLINTEGER rlength;
rc = SQLAllocStmt(hdbc, &hstmt);
if (rc != SQL_SUCCESS )
check_error (henv, hdbc, SQL_NULL_HSTMT, rc);
terminate(henv, hdbc);
return (SQL_SUCCESS);
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLFetch - Fetch next row” on page 107
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetConnectAttrW(). Refer to “Unicode in DB2 for iCLI” on page
305 for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetConnectAttr( SQLHDBC hdbc,
SQLINTEGER fAttr,
SQLPOINTER pvParam),;
SQLINTEGER bLen,
SQLINTEGER *sLen);
Function arguments
Table 76. SQLGetConnectAttr arguments
Data type Argument Use Description
SQLHDBC hdbc Input Connection handle.
SQLINTEGER fAttr Input Attribute to retrieve. See
“SQLSetConnectAttr - Set a connection
attribute” on page 219 for a description of
the connect options.
SQLPOINTER pvParam Output Value associated with fAttr Depending on
the value of fAttr. This can be a 32-bit
integer value, or a pointer to a null
terminated character string.
SQLINTEGER bLen Input Maximum number of bytes to store in
pvParm, if the value is a character string;
otherwise, unused.
SQLINTEGER * sLen Output Length of the output data, if the attribute is
a character string; otherwise, unused.
Usage
Diagnostics
Table 77. SQLGetConnectAttr SQLSTATEs
SQLSTATE Description Explanation
08003 Connection not open An fAttr value that requires an open connection is
specified .
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Attribute type out of range An fAttr value that is not valid is specified.
SQLGetConnectOption() returns the current settings for the specified connection option.
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLGetConnectOptionW(). Refer to “Unicode in DB2 for iCLI” on page
| 305 for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetConnectOption( HDBC hdbc,
SQLSMALLINT fOption,
SQLPOINTER pvParam);
Function arguments
Table 78. SQLGetConnectOption arguments
Data type argument Use Description
HDBC hdbc Input Connection handle.
SQLSMALLINT fOption Input Option to retrieve. Refer to Table 146 on page 219 for
more information.
SQLPOINTER pvParam Output Value associated with fOption Depending on the value of
fOption, this can be a 32-bit integer value, or a pointer to
a null terminated character string. The maximum length
of any character string returned is
SQL_MAX_OPTION_STRING_LENGTH bytes (excluding
the null-terminating byte).
Usage
SQLGetConnectOption() provides the same function as SQLGetConnectAttr(). Both functions are supported
for compatibility reasons.
Diagnostics
Table 79. SQLGetConnectOption SQLSTATEs
SQLSTATE Description Explanation
08003 Connection not open An fOption value that requires an open connection is
specified .
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Option type out of range An fOption value that is not valid is specified.
References
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetCursorNameW(). Refer to “Unicode in DB2 for iCLI” on page
305 for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetCursorName (SQLHSTMT hstmt,
SQLCHAR *szCursor,
SQLSMALLINT cbCursorMax,
SQLSMALLINT *pcbCursor);
Function arguments
Table 80. SQLGetCursorName arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle
SQLCHAR * szCursor Output Cursor name
SQLSMALLINT cbCursorMax Input Length of buffer szCursor
SQLSMALLINT * pcbCursor Output Amount of bytes available to return for
szCursor
Usage
If a name is set explicitly using SQLSetCursorName(), this name is returned until the statement is dropped,
or until another explicit name is set.
If an explicit name is not set, an implicit name is generated when a SELECT statement is processed, and
this name is returned. Implicit cursor names always begin with SQLCUR.
The generated cursor names of ODBC start with SQL_CUR and X/Open CLI generated cursor names
begin with SQLCUR. DB2 for i CLI uses SQLCUR.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 81. SQLGetCursorName SQLSTATEs
SQLSTATE Description Explanation
01004 Data truncated The cursor name returned in szCursor is longer than the
value in cbCursorMax, and is truncated to cbCursorMax -
1 bytes. The argument pcbCursor contains the length of
the full cursor name available for return. The function
returns SQL_SUCCESS_WITH_INFO.
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not The argument szCursor or pcbCursor is a null pointer.
valid
The value specified for the argument cbCursorMax is less
than 1.
HY010 Function sequence error The statement hstmt is not in execute state. Call
SQLExecute(), SQLExecDirect() or SQLSetCursorName()
before calling SQLGetCursorName().
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
HY015 No cursor name available. There is no open cursor on the hstmt and no cursor name
has been set with SQLSetCursorName(). The statement
associated with hstmt does not support the use of a
cursor.
Example
Refer to “Example: Interactive SQL and the equivalent DB2 for i CLI function calls” on page 313 for a
listing of the check_error, initialize, and terminate functions used in the following example.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*************************************************************************
** file = getcurs.c
**
** Example of directly executing a SELECT and positioned UPDATE SQL statement.
** Two statement handles are used, and SQLGetCursor is used to retrieve the
** generated cursor name.
**
** Functions used:
**
** SQLAllocConnect SQLFreeConnect
** SQLAllocEnv SQLFreeEnv
** SQLAllocStmt SQLFreeStmt
** SQLConnect SQLDisconnect
**
** SQLBindCol SQLFetch
** SQLTransact SQLError
** SQLExecDirect SQLGetCursorName
**************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "sqlcli.h"
/*******************************************************************
** main
** - initialize
** - terminate
*******************************************************************/
int main()
{
SQLHENV henv;
SQLHDBC hdbc;
SQLRETURN rc,
rc2;
rc = initialize(&henv, &hdbc);
if (rc != SQL_SUCCESS) return(terminate(henv, hdbc));
{SQLHSTMT hstmt1,
hstmt2;
SQLCHAR sqlstmt[]="SELECT name, job from staff for update of job";
SQLCHAR updstmt[MAX_STMT_LEN + 1];
SQLCHAR name[10],
job[6],
newjob[6],
cursor[19];
rc = SQLAllocStmt(hdbc, &hstmt1);
if (rc != SQL_SUCCESS )
check_error (henv, hdbc, SQL_NULL_HSTMT, rc);
printf("Commiting Transaction\n");
rc = SQLTransact(henv, hdbc, SQL_COMMIT);
if (rc != SQL_NO_DATA_FOUND )
check_error (henv, hdbc, SQL_NULL_HSTMT, rc);
terminate(henv, hdbc);
return (0);
}/* end main */
References
v “SQLExecute - Execute a statement” on page 103
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLSetCursorName - Set cursor name” on page 233
After calling SQLGetData() for each column, SQLFetch() is called to retrieve the next row.
SQLGetData() is identical to SQLGetCol(). Both functions are supported for compatibility reasons.
Syntax
SQLRETURN SQLGetData (SQLHSTMT hstmt,
SQLSMALLINT icol,
SQLSMALLINT fCType,
SQLPOINTER rgbValue,
SQLINTEGER cbValueMax,
SQLINTEGER *pcbValue);
Note: Refer to “SQLGetCol - Retrieve one column of a row of the result set” on page 125 for a
description of the applicable sections.
This function is similar to that of SQLDescribeCol(), but SQLGetDescField() can retrieve data from
parameter descriptors as well as row descriptors.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetDescFieldW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetDescField (SQLHDESC hdesc,
SQLSMALLINT irec,
SQLSMALLINT fDescType,
SQLPOINTER rgbDesc,
SQLINTEGER bLen,
SQLINTEGER *sLen);
Function arguments
Table 82. SQLGetDescField arguments
Data type Argument Use Description
SQLHDESC hdesc Input Descriptor handle.
SQLSMALLINT irec Input Indicates the descriptor record from which
the application seeks information. Descriptor
records are numbered from 1, with the
record number 1 being the first item in the
descriptor. If the fDescType argument
indicates a field of the descriptor header
record ( SQL_DESC_ALLOC_TYPE or
SQL_DESC_COUNT), irec must be 0.
SQLSMALLINT fDescType Input Indicates the field of the descriptor whose
value is to be returned. See Table 83.
SQLPOINTER rgbDesc Output Pointer to buffer.
SQLINTEGER bLen Input Length of descriptor buffer (rgbDesc).
SQLINTEGER * sLen Output Actual number of bytes in the descriptor to
return. If this argument contains a value
equal to or higher than the length rgbDesc
buffer, truncation occurs.
Usage
The number of records in the descriptor corresponds to the number of columns in the result set, if the
descriptor is row descriptor, or the number of parameters, for a parameter descriptor.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Diagnostics
Table 84. SQLGetDescField SQLSTATEs
SQLSTATE Description Explanation
HY009 Argument value that is not The value specified for the argument fDescType or irec is
valid not valid.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLDescribeCol - Describe column attributes” on page 84
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLExecute - Execute a statement” on page 103
v “SQLPrepare - Prepare a statement” on page 199
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetDescRecW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetDescRec (SQLHDESC hdesc,
SQLSMALLINT irec,
SQLCHAR *rgbDesc,
SQLSMALLINT cbDescMax,
SQLSMALLINT *pcbDesc,
SQLSMALLINT *type,
SQLSMALLINT *subtype,
SQLINTEGER *length,
SQLSMALLINT *prec,
SQLSMALLINT *scale,
SQLSMALLINT *nullable);
Function arguments
Table 85. SQLGetDescRec arguments
Data type Argument Use Description
SQLHDESC hdesc Input Descriptor handle.
SQLSMALLINT irec Input Indicates the descriptor record from which
the application seeks information. Descriptor
records are numbered from 1, with the
record number 1 being the first item in the
descriptor. If the fDescType argument
indicates a field of the descriptor header
record ( SQL_DESC_ALLOC_TYPE or
SQL_DESC_COUNT), irec must be 0.
SQLCHAR * rgbDesc Output NAME field for the record.
SQLSMALLINT cbDescMax Input Maximum number of bytes to store in
rgbDesc.
SQLSMALLINT * pcbDesc Output Total length of the output data.
SQLSMALLINT * type Output TYPE field for the record.
SQLSMALLINT * subtype Output DATETIME_INTERVAL_CODE, for records
whose TYPE is SQL_DATETIME.
SQLINTEGER * length Output LENGTH field for the record.
SQLSMALLINT * prec Output PRECISION field for the record.
SQLSMALLINT * scale Output SCALE field for the record.
SQLSMALLINT * nullable Output NULLABLE field for the record.
Usage
Calling SQLGetDescRec() retrieves all the data from a descriptor record in one call. It might still be
necessary to call SQLGetDescField() with SQL_DESC_COUNT to determine the number of records in the
descriptor.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Diagnostics
Table 86. SQLGetDescRec SQLSTATEs
SQLSTATE Description Explanation
HY009 Argument value that is not The value specified for the argument irec is not valid.
valid
The argument rgbDesc, pcbDesc, type, subtype, length, prec,
scale or nullable is a null pointer.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
not valid or it contains a value that is not valid.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLDescribeCol - Describe column attributes” on page 84
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLExecute - Execute a statement” on page 103
v “SQLPrepare - Prepare a statement” on page 199
The information consists of a standardized SQLSTATE, an error code, and a text message. Refer to
“Diagnostics in a DB2 for i CLI application” on page 16 for more information.
Note: Some database servers might provide product-specific diagnostic information after returning
SQL_NO_DATA_FOUND from the processing of a statement.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetDiagFieldW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetDiagField (SQLSMALLINT htype,
SQLINTEGER handle,
SQLSMALLINT recNum,
SQLSMALLINT diagId,
SQLPOINTER diagInfo,
SQLSMALLINT bLen,
SQLSMALLINT *sLen);
Function arguments
Table 87. SQLGetDiagField arguments
Data type Argument Use Description
SQLSMALLINT hType Input Handle type.
SQLINTEGER handle Input Handle for which the diagnostic information
is wanted.
SQLSMALLINT recNum Input If there are multiple errors, this indicates
which one should be retrieved. If header
information is requested, this must be 0. The
first error record is number 1.
SQLSMALLINT diagId Input See Table 88.
SQLPOINTER diagInfo Output Buffer for diagnostic information.
SQLSMALLINT bLen Input Length of diagInfo, if requested data is a
character string; otherwise, unused.
SQLSMALLINT * sLen Output Length of complete diagnostic information, If
the requested data is a character string;
otherwise, unused.
Usage
The SQLSTATEs are those defined by the X/OPEN SQL CAE and the X/Open SQL CLI snapshot,
augmented with SQLSTATE values.
If diagnostic information generated by one DB2 for i CLI function is not retrieved before a function other
than SQLGetDiagField() is called with the same handle, the information for the previous function call is
lost. This is true whether diagnostic information is generated for the second DB2 for i CLI function call.
Multiple diagnostic messages might be available after a given DB2 for i CLI function call. These messages
can be retrieved one at a time by repeatedly calling SQLGetDiagField(). When there are no more
messages to retrieve, SQL_NO_DATA_FOUND is returned.
Diagnostic information stored under a given handle is cleared when a call is made to SQLGetDiagField()
with that handle, or when another DB2 for i CLI function call is made with that handle. However,
information associated with a given handle type is not cleared by a call to SQLGetDiagField() with an
associated but different handle type. For example, a call to SQLGetDiagField() with a connection handle
input does not clear errors associated with any statement handles under that connection.
SQL_SUCCESS is returned even if the buffer for the error message (szDiagFieldMsg) is too short. This is
because the application is not able to retrieve the same error message by calling SQLGetDiagField() again.
The actual length of the message text is returned in the pcbDiagFieldMsg.
To avoid truncation of the first level error message, declare a buffer length of
SQL_MAX_MESSAGE_LENGTH + 1. To avoid truncation of the second level error message, set the size
of the buffer to a value greater than SQL_MAX_MESSAGE_LENGTH.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Diagnostics
SQLSTATEs are not defined, because SQLGetDiagField() does not generate diagnostic information for
itself.
Restrictions
Although ODBC also returns X/Open SQL CAE SQLSTATEs, only DB2 for i CLI returns the additional
IBM defined SQLSTATEs. The ODBC Driver Manager also returns SQLSTATE values in addition to the
standard ones. For more information about ODBC specific SQLSTATEs refer to Microsoft ODBC
Programmer's Reference.
Because of this, you should only build dependencies on the standard SQLSTATEs. This means any
branching logic in the application should only rely on the standard SQLSTATEs. The augmented
SQLSTATEs are most useful for debugging purposes.
The information consists of a standardized SQLSTATE, the error code, and a text message. See
“Diagnostics in a DB2 for i CLI application” on page 16 for more information.
Note: Some database servers might provide product-specific diagnostic information after returning
SQL_NO_DATA_FOUND from the processing of a statement.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetDiagRecW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetDiagRec (SQLSMALLINT hType,
SQLINTEGER handle,
SQLSMALLINT recNum,
SQLCHAR *szSqlState,
SQLINTEGER *pfNativeError,
SQLCHAR *szErrorMsg,
SQLSMALLINT cbErrorMsgMax,
SQLSMALLINT *pcbErrorMsg);
Function arguments
Table 89. SQLGetDiagRec arguments
Data type Argument Use Description
SQLSMALLINT hType Input Handle type.
SQLINTEGER handle Input Handle for which the diagnostic information
is wanted.
SQLSMALLINT recNum Input If there are multiple errors, this indicates
which one should be retrieved. If header
information is requested, this must be 0. The
first error record is number 1.
SQLCHAR * szSqlState Output SQLSTATE as a string of 5 characters
terminated by a null character. The first 2
characters indicate error class; the next 3
indicate subclass. The values correspond
directly to SQLSTATE values defined in the
X/Open SQL CAE specification and the
ODBC specification, augmented with IBM
specific and product specific SQLSTATE
values.
SQLINTEGER * pfNativeError Output Error code. In DB2 for i CLI, the pfNativeError
argument contains the SQLCODE value
returned by the Database Management
System (DBMS). If the error is generated by
DB2 for i CLI and not the DBMS, then this
field is set to -99999.
Usage
The SQLSTATEs are those defined by the X/OPEN SQL CAE and the X/Open SQL CLI snapshot,
augmented with IBM specific and product specific SQLSTATE values.
If diagnostic information generated by one DB2 for i CLI function is not retrieved before a function other
than SQLGetDiagRec() is called with the same handle, the information for the previous function call is
lost. This is true whether diagnostic information is generated for the second DB2 for i CLI function call.
Multiple diagnostic messages might be available after a given DB2 for i CLI function call. These messages
can be retrieved one at a time by repeatedly calling SQLGetDiagRec(). When there are no more messages
to retrieve, SQL_NO_DATA_FOUND is returned, the SQLSTATE is set to "00000", pfNativeError is set to 0,
and pcbErrorMsg and szErrorMsg are undefined.
Diagnostic information stored under a given handle is cleared when a call is made to SQLGetDiagRec()
with that handle, or when another DB2 for i CLI function call is made with that handle. However,
information associated with a given handle type is not cleared by a call to SQLGetDiagRec() with an
associated but different handle type. For example, a call to SQLGetDiagRec() with a connection handle
input does not clear errors associated with any statement handles under that connection.
SQL_SUCCESS is returned even if the buffer for the error message (szErrorMsg) is too short, because the
application is not able to retrieve the same error message by calling SQLGetDiagRec() again. The actual
length of the message text is returned in the pcbErrorMsg.
To avoid truncation of the first level error message, declare a buffer length of
SQL_MAX_MESSAGE_LENGTH + 1. To avoid truncation of the second level error message, set the size
of the buffer to a value greater than SQL_MAX_MESSAGE_LENGTH.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Diagnostics
SQLSTATEs are not defined because SQLGetDiagRec() does not generate diagnostic information for itself.
Restrictions
Although ODBC also returns X/Open SQL CAE SQLSTATEs, only DB2 for i CLI returns the additional
IBM defined SQLSTATEs. The ODBC Driver Manager also returns SQLSTATE values in addition to the
standard ones. For more information about ODBC specific SQLSTATEs refer to Microsoft ODBC
Programmer's Reference.
Because of this, you should only build dependencies on the standard SQLSTATEs. This means any
branching logic in the application should only rely on the standard SQLSTATEs. The augmented
SQLSTATEs are most useful for debugging purposes.
References
Syntax
SQLRETURN SQLGetEnvAttr (SQLHENV henv,
SQLINTEGER Attribute,
SQLPOINTER Value,
SQLINTEGER BufferLength,
SQLINTEGER *StringLength);
Function arguments
Table 90. SQLGetEnvAttr arguments
Data type Argument Use Description
SQLHENV henv Input Environment handle.
SQLINTEGER Attribute Input Attribute to retrieve. Refer to Table 158 on
page 239 for more information.
SQLPOINTER Value Output Current value associated with Attribute. The
type of the value returned depends on
Attribute.
SQLINTEGER BufferLength Input Maximum size of buffer pointed to by Value,
if the attribute value is a character string;
otherwise, unused.
SQLINTEGER * StringLength Output Length in bytes of the output data if the
attribute value is a character string;
otherwise, unused.
If Attribute does not denote a string, then DB2 for i CLI ignores BufferLength and does not set
StringLength.
Usage
SQLGetEnvAttr() can be called at any time between the allocation and freeing of the environment handle.
It obtains the current value of the environment attribute.
Diagnostics
Table 91. SQLGetEnvAttr SQLSTATEs
SQLSTATE Description Explanation
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Attribute out of range An Attribute value that is not valid is specified.
SQLConnect() must be called, and a connection to the data source (database server) must exist before
calling this function.
Syntax
SQLRETURN SQLGetFunctions (SQLHDBC hdbc,
SQLSMALLINT fFunction,
SQLSMALLINT *pfSupported);
Function arguments
Table 92. SQLGetFunctions arguments
Data type Argument Use Description
SQLHDBC hdbc Input Database connection handle.
SQLSMALLINT fFunction Input Function being queried.
SQLSMALLINT * pfSupported Output Pointer to location where this function
returns SQL_TRUE or SQL_FALSE
depending on whether the function being
queried is supported.
Usage
The following list shows the valid value for the fFunction argument and whether the corresponding
function is supported.
SQL_API_ALLOCCONNECT = TRUE
SQL_API_ALLOCENV = TRUE
SQL_API_ALLOCHANDLE = TRUE
SQL_API_ALLOCSTMT = TRUE
SQL_API_BINDCOL = TRUE
SQL_API_BINDFILETOCOL = TRUE
SQL_API_BINDFILETOPARAM = TRUE
SQL_API_BINDPARAM = TRUE
SQL_API_BINDPARAMETER = TRUE
SQL_API_CANCEL = TRUE
SQL_API_CLOSECURSOR = TRUE
SQL_API_COLATTRIBUTE = TRUE
SQL_API_COLATTRIBUTEW = TRUE
SQL_API_COLATTRIBUTES = TRUE
SQL_API_COLATTRIBUTESW = TRUE
SQL_API_COLUMNS = TRUE
SQL_API_COLUMNSW = TRUE
SQL_API_CONNECT = TRUE
SQL_API_CONNECTW = TRUE
SQL_API_COPYDESC = TRUE
SQL_API_DATASOURCES = TRUE
SQL_API_DATASOURCESW = TRUE
SQL_API_DESCRIBECOL = TRUE
SQL_API_DESCRIBECOLW = TRUE
SQL_API_DESCRIBEPARAM = TRUE
SQL_API_DISCONNECT = TRUE
SQL_API_DRIVERCONNECT = TRUE
SQL_API_DRIVERCONNECTW = TRUE
SQL_API_ENDTRAN = TRUE
SQL_API_ERROR = TRUE
SQL_API_ERRORW = TRUE
SQL_API_EXECDIRECT = TRUE
SQL_API_EXECDIRECTW = TRUE
SQL_API_EXECUTE = TRUE
SQL_API_EXTENDEDFETCH = TRUE
SQL_API_FETCH = TRUE
SQL_API_FOREIGNKEYS = TRUE
SQL_API_FOREIGNKEYSW = TRUE
SQL_API_FREECONNECT = TRUE
SQL_API_FREEENV = TRUE
SQL_API_FREEHANDLE = TRUE
SQL_API_FREESTMT = TRUE
SQL_API_GETCOL = TRUE
SQL_API_GETCONNECTATTR = TRUE
SQL_API_GETCONNECTATTRW = TRUE
SQL_API_GETCONNECTOPTION = TRUE
SQL_API_GETCONNECTOPTIONW = TRUE
SQL_API_GETCURSORNAME = TRUE
SQL_API_GETCURSORNAMEW = TRUE
SQL_API_GETDATA = TRUE
SQL_API_GETDESCFIELD = TRUE
SQL_API_GETDESCFIELDW = TRUE
SQL_API_GETDESCREC = TRUE
SQL_API_GETDESCRECW = TRUE
SQL_API_GETDIAGFIELD = TRUE
SQL_API_GETDIAGFIELDW = TRUE
SQL_API_GETDIAGREC = TRUE
SQL_API_GETDIAGRECW = TRUE
SQL_API_GETENVATTR = TRUE
SQL_API_GETFUNCTIONS = TRUE
SQL_API_GETINFO = TRUE
SQL_API_GETINFOW = TRUE
SQL_API_GETLENGTH = TRUE
SQL_API_GETPOSITION = TRUE
SQL_API_GETPOSITIONW = TRUE
SQL_API_GETSTMTATTR = TRUE
SQL_API_GETSTMTATTRW = TRUE
SQL_API_GETSTMTOPTION = TRUE
SQL_API_GETSTMTOPTIONW = TRUE
SQL_API_GETSUBSTRING = TRUE
SQL_API_GETSUBSTRINGW = TRUE
SQL_API_GETTYPEINFO = TRUE
SQL_API_GETTYPEINFOW = TRUE
SQL_API_LANGUAGES = TRUE
SQL_API_MORERESULTS = TRUE
SQL_API_NATIVESQL = TRUE
SQL_API_NATIVESQLW = TRUE
SQL_API_NUMPARAMS = TRUE
SQL_API_NUMRESULTCOLS = TRUE
SQL_API_PARAMDATA = TRUE
SQL_API_PARAMOPTIONS = TRUE
SQL_API_PREPARE = TRUE
SQL_API_PREPAREW = TRUE
SQL_API_PRIMARYKEYS = TRUE
SQL_API_PRIMARYKEYSW = TRUE
SQL_API_PROCEDURECOLUMNS = TRUE
SQL_API_PROCEDURECOLUMNSW = TRUE
SQL_API_PROCEDURES = TRUE
SQL_API_PROCEDURESW = TRUE
SQL_API_PUTDATA = TRUE
SQL_API_RELEASEENV = TRUE
SQL_API_ROWCOUNT = TRUE
SQL_API_SETCONNECTATTR = TRUE
SQL_API_SETCONNECTATTRW = TRUE
SQL_API_SETCONNECTOPTION = TRUE
SQL_API_SETCONNECTOPTIONW = TRUE
SQL_API_SETCURSORNAME = TRUE
SQL_API_SETCURSORNAMEW = TRUE
SQL_API_SETDESCFIELD = TRUE
SQL_API_SETDESCFIELDW = TRUE
SQL_API_SETDESCREC = TRUE
SQL_API_SETENVATTR = TRUE
SQL_API_SETPARAM = TRUE
SQL_API_SETSTMTATTR = TRUE
SQL_API_SETSTMTATTRW = TRUE
SQL_API_SETSTMTOPTION = TRUE
SQL_API_SETSTMTOPTIONW = TRUE
SQL_API_SPECIALCOLUMNS = TRUE
SQL_API_SPECIALCOLUMNSW = TRUE
SQL_API_STATISTICS = TRUE
SQL_API_STATISTICSW = TRUE
SQL_API_TABLES = TRUE
SQL_API_TABLESW = TRUE
SQL_API_TRANSACT = TRUE
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 93. SQLGetFunctions SQLSTATEs
SQLSTATE Description Explanation
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not The argument pfSupported is a null pointer.
valid.
HY010 Function sequence error. SQLGetFunctions is called before SQLConnect.
Connection handles must
not be allocated yet.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetInfoW(). Refer to “Unicode in DB2 for iCLI” on page 305 for
more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetInfo (SQLHDBC hdbc,
SQLSMALLINT fInfoType,
SQLPOINTER rgbInfoValue,
SQLSMALLINT cbInfoValueMax,
SQLSMALLINT *pcbInfoValue);
Function arguments
Table 94. SQLGetInfo arguments
Data type Argument Use Description
SQLHDBC hdbc Input Database connection handle.
SQLSMALLINT fInfoType Input Type of the required information.
SQLPOINTER rgbInfoValue Output (also Pointer to buffer where this function stores
input) the required information. Depending on the
type of information being retrieved, four
types of information can be returned:
v 16-bit integer value
v 32-bit integer value
v 32-bit binary value
v Null-terminated character string
SQLSMALLINT cbInfoValueMax Input The maximum length of the buffer pointed
by rgbInfoValue pointer.
SQLSMALLINT * pcbInfoValue Output Pointer to location where this function
returns the total number of bytes available to
return the required information.
Usage
Table 95 on page 155 lists the possible values of fInfoType and a description of the information that
SQLGetInfo() returns for that value.
| For example:
| v AS for DB2 for i
| v DB2/xxx for DB2 for Linux, UNIX, and
| Windows
| v DB2 for DB2 for z/OS®
SQL_DBMS_VER String Version of the DBMS product accessed.
SQL_DEFAULT_TXN_ISOLATION 32-bit mask The default transaction-isolation level supported.
In IBM terminology,
v SQL_TXN_READ_UNCOMMITTED is
uncommitted read.
v SQL_TXN_READ_COMMITTED is cursor
stability.
v SQL_TXN_REPEATABLE_READ is read
stability.
v SQL_TXN_SERIALIZABLE is repeatable read.
SQL_DESCRIBE_PARAMETER String Y if parameters can be described; N if not.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 96. SQLGetInfo SQLSTATEs
SQLSTATE Description Explanation
01004 Data truncated The requested information is returned as a
null-terminated string and its length exceeded the length
of the application buffer as specified in cbInfoValueMax.
The argument pcbInfoValue contains the actual (not
truncated) length of the requested information.
08003 Connection not open The type of information requested in fInfoType requires
an open connection. Only SQL_ODBC_VER does not
require an open connection.
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not The argument rgbInfoValue is a null pointer
valid
An fInfoType that is not valid is specified.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
Syntax
SQLRETURN SQLGetLength (SQLHSTMT StatementHandle,
SQLSMALLINT LocatorCType,
SQLINTEGER Locator,
SQLINTEGER *StringLength,
SQLINTEGER *IndicatorValue);
Function arguments
Table 97. SQLGetLength arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle. This can be any statement handle
which has been allocated but which does not
currently have a prepared statement assigned to it.
SQLSMALLINT LocatorCType Input The C type of the source LOB locator.
v SQL_C_BLOB_LOCATOR
v SQL_C_CLOB_LOCATOR
v SQL_C_DBCLOB_LOCATOR
SQLINTEGER Locator Input Must be set to the LOB locator value.
SQLINTEGER * StringLength Output The length of the specified locator.1
Usage
SQLGetLength() can be used to determine the length of the data value represented by a LOB locator. It is
used by applications to determine the overall length of the referenced LOB value so that the appropriate
strategy to obtain some or all of the LOB value can be chosen.
The Locator argument can contain any valid LOB locator which has not been explicitly freed using a
FREE LOCATOR statement nor implicitly freed because the transaction during which it is created has
terminated.
The statement handle must not have been associated with any prepared statements or catalog function
calls.
DB2 for i restricts the use of LOB locators when running with no isolation level.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 98. SQLGetLength SQLSTATEs
SQLSTATE Description Explanation
07006 Conversion that is not valid The combination of the argumentLocatorCType and Locator is not
valid.
0F001 LOB variable that is not valid The value specified for the argument Locator has not been
associated with a LOB locator.
58004 Unexpected system failure Unrecoverable system error.
HY003 Program type out of range The argument LocatorCType is not one of
SQL_C_CLOB_LOCATOR, SQL_C_BLOB_LOCATOR, or
SQL_C_DBCLOB_LOCATOR.
HY009 Argument value that is not valid The argument StringLength or IndicatorValue is a null pointer.
HY010 Function sequence error The specified argument StatementHandle is not in an allocated state.
HY021 Internal descriptor that is not The internal descriptor cannot be addressed or allocated, or it
valid contains a value that is not valid.
HYC00 Driver not capable The application is currently connected to a data source that does
not support large objects.
Restrictions
This function is not available when connected to a DB2 server that does not support Large Objects.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLFetch - Fetch next row” on page 107
v “SQLGetPosition - Return starting position of string” on page 168
v “SQLGetSubString - Retrieve portion of a string value” on page 175
The source and search LOB locators can be any that have been returned from the database from a fetch
or an SQLGetSubString() call during the current transaction.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetPositionW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetPosition (SQLHSTMT StatementHandle,
SQLSMALLINT LocatorCType,
SQLINTEGER SourceLocator,
SQLINTEGER SearchLocator,
SQLCHAR *SearchLiteral,
SQLINTEGER SearchLiteralLength,
SQLINTEGER FromPosition,
SQLINTEGER *LocatedAt,
SQLINTEGER *IndicatorValue);
Function arguments
Table 99. SQLGetPosition arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle. This can be any statement
handle which has been allocated but which does
not currently have a prepared statement assigned
to it.
SQLSMALLINT LocatorCType Input The C type of the source LOB locator. This can be:
v SQL_C_BLOB_LOCATOR
v SQL_C_CLOB_LOCATOR
v SQL_C_DBCLOB_LOCATOR
SQLINTEGER SourceLocator Input SourceLocator must be set to the source LOB
locator.
SQLINTEGER SearchLocator Input If the SearchLiteral pointer is NULL and if
SearchLiteralLength is set to 0, then SearchLocator
must be set to the LOB locator associated with the
search string; otherwise, this argument is ignored.
The lob locator type for the SearchLocator must be
the same as the locator type used by the
SourceLocator. This locator type is set for
argument LocatorCType.
SQLCHAR * SearchLiteral Input This argument points to the area of storage that
contains the search string literal.
Usage
The Locator and SearchLocator (if used) arguments can contain any valid LOB locator which has not been
explicitly freed using a FREE LOCATOR statement or implicitly freed because the transaction during
which it is created has terminated.
The Locator and SearchLocator must have the same LOB locator type.
The statement handle must not have been associated with any prepared statements or catalog function
calls.
If a remote connection has been made, the CCSID of the CLOB data (SourceLocator) must be compatible
with the CCSID of the job executing the SQLGetSubString API, otherwise translation problems will occur.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 100. SQLGetPosition SQLSTATEs
SQLSTATE Description Explanation
07006 Conversion that is not valid The combination of the LocatorCType argument and either of the
LOB locator values is not valid.
Restrictions
This function is not available when connected to a DB2 server that does not support Large Objects.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLExtendedFetch - Fetch array of rows” on page 105
v “SQLFetch - Fetch next row” on page 107
v “SQLGetLength - Retrieve length of a string value” on page 166
v “SQLGetSubString - Retrieve portion of a string value” on page 175
These options are set using the SQLSetStmtAttr() function. This function is similar to
SQLGetStmtOption(). Both functions are supported for compatibility reasons.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetStmtAttrW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetStmtAttr( SQLHSTMT hstmt,
SQLINTEGER fAttr,
SQLPOINTER pvParam,
SQLINTEGER bLen,
SQLINTEGER *sLen);
Function arguments
Table 101. SQLGetStmtAttr arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLINTEGER fAttr Input Attribute to retrieve. Refer to Table 102 for more
information.
SQLPOINTER pvParam Output Pointer to buffer for requested attribute.
SQLINTEGER bLen Input Maximum number of bytes to store in pvParam, if
the attribute is a character string; otherwise,
unused.
SQLINTEGER * sLen Output Length of output data if the attribute is a
character string; otherwise, unused.
Usage
Table 102. Statement attributes
fAttr Data type Contents
SQL_ATTR_APP_PARAM_DESC Integer The descriptor handle used by the application to provide parameter values for this statement
handle.
SQL_ATTR_APP_ROW_DESC Integer The descriptor handle for the application to retrieve row data using the statement handle.
SQL_ATTR_CURSOR_SCROLLABLE Integer A 32-bit integer value that specifies if cursors opened for this statement handle should be
scrollable.
v SQL_FALSE – Cursors are not scrollable, and SQLFetchScroll() cannot be used against them.
This is the default.
v SQL_TRUE – Cursors are scrollable. SQLFetchScroll() can be used to retrieve data from
these cursors.
SQL_ATTR_CURSOR_TYPE Integer A 32-bit integer value that specifies the behavior of cursors opened for this statement handle.
v SQL_CURSOR_FORWARD_ONLY – Cursors are not scrollable, and SQLFetchScroll() cannot
be used against them. This is the default.
v SQL_DYNAMIC – Cursors are scrollable. SQLFetchScroll() can be used to retrieve data from
these cursors.
SQL_ATTR_FOR_FETCH_ONLY Integer This indicates if cursors opened for this statement handle should be read-only.
v SQL_FALSE - Cursors can be used for positioned updates and deletes. This is the default.
v SQL_TRUE - Cursors are read-only and cannot be used for positioned updates or deletes.
SQL_ATTR_IMP_PARAM_DESC Integer The descriptor handle used by the CLI implementation to provide parameter values for this
statement handle.
SQL_ATTR_IMP_ROW_DESC Integer The descriptor handle used by the CLI implementation to retrieve row data using this statement
handle.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 103. SQLGetStmtAttr SQLSTATEs
SQLSTATE Description Explanation
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not The argument pvParam is a null pointer.
valid
An fAttr that is not valid value is specified.
HYC00 Driver not capable DB2 for i CLI recognizes the option but does not support
it.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetStmtOptionW(). Refer to “Unicode in DB2 for iCLI” on page
305 for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetStmtOption( SQLHSTMT hstmt,
SQLSMALLINT fOption,
SQLPOINTER pvParam);
Function arguments
Table 104. SQLStmtOption arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Connection handle.
SQLSMALLINT fOption Input Option to retrieve. See Table 102 on page 171 for more
information.
SQLPOINTER pvParam Output Value of the option. Depending on the value of fOption
this can be a 32-bit integer value, or a pointer to a null
terminated character string.
Usage
SQLGetStmtOption() provides the same function as SQLGetStmtAttr(), both functions are supported for
compatibility reasons.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 105. SQLStmtOption SQLSTATEs
SQLSTATE Description Explanation
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not The argument pvParam is a null pointer.
valid
A fOption that is not valid value is specified.
References
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetSubStringW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetSubString (
SQLHSTMT StatementHandle,
SQLSMALLINT LocatorCType,
SQLINTEGER SourceLocator,
SQLINTEGER FromPosition,
SQLINTEGER ForLength,
SQLSMALLINT TargetCType,
SQLPOINTER DataPtr,
SQLINTEGER BufferLength,
SQLINTEGER *StringLength,
SQLINTEGER *IndicatorValue);
Function arguments
Table 106. SQLGetSubString arguments
Data type Argument Use Description
SQLHSTMT StatementHandle input Statement handle. This can be any statement
handle which has been allocated but which
does not currently have a prepared statement
assigned to it.
SQLSMALLINT LocatorCType input The C type of the source LOB locator. This can
be:
v SQL_C_BLOB_LOCATOR
v SQL_C_CLOB_LOCATOR
v SQL_C_DBCLOB_LOCATOR
SQLINTEGER SourceLocator input SourceLocator must be set to the source LOB
locator value.
SQLINTEGER FromPosition input For BLOBs and CLOBs, this is the position of
the first byte to be returned by the function.
For DBCLOBs, this is the first character. The
start byte or character is numbered 1.
SQLINTEGER ForLength input This is the length of the string to be returned
by the function. For BLOBs and CLOBs, this is
the length in bytes. For DBCLOBs, this is the
length in characters.
Usage
SQLGetSubString() is used to obtain any portion of the string that is represented by the LOB locator.
There are two choices for the target:
v The target can be an appropriate C string variable.
v A new LOB value can be created on the server and the LOB locator for that value can be assigned to a
target application variable on the client.
SQLGetSubString() can be used as an alternative to SQLGetData() for getting data in pieces. In this case a
column is first bound to a LOB locator, which is then used to fetch the LOB as a whole or in pieces.
The Locator argument can contain any valid LOB locator which has not been explicitly freed using a
FREE LOCATOR statement nor implicitly freed because the transaction during which it is created has
terminated.
The statement handle must not have been associated with any prepared statements or catalog function
calls.
If a locator entry exists in the locator table but has no data, SQLGetSubString() will return an
SQL_NO_DATA return code.
If a remote connection has been made, the CCSID of the CLOB data (SourceLocator) must be compatible
with the CCSID of the job executing the SQLGetSubString API, otherwise translation problems will occur.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA
Error conditions
Table 107. SQLGetSubString SQLSTATEs
SQLSTATE Description Explanation
01004 Data truncated The amount of data to be returned is longer than BufferLength.
Actual length available for return is stored in StringLength.
07006 Conversion that is not valid The value specified for TargetCType is not SQL_C_CHAR,
SQL_C_BINARY, SQL_C_DBCHAR, or a LOB locator.
Restrictions
This function is not available when connected to a DB2 server that does not support Large Objects.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLFetch - Fetch next row” on page 107
v “SQLGetData - Get data from a column” on page 138
v “SQLGetLength - Retrieve length of a string value” on page 166
v “SQLGetPosition - Return starting position of string” on page 168
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLGetTypeInfoW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLGetTypeInfo (SQLHSTMT StatementHandle,
SQLSMALLINT DataType);
Function arguments
Table 108. SQLGetTypeInfo arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle
SQLSMALLINT DataType Input The SQL data type being queried. The supported
types are:
v SQL_ALL_TYPES
v SQL_BIGINT
v SQL_BINARY
v SQL_BLOB
v SQL_CHAR
v SQL_CLOB
v SQL_DATE
v SQL_DBCLOB
v SQL_DECFLOAT
v SQL_DECIMAL
v SQL_DOUBLE
v SQL_FLOAT
v SQL_GRAPHIC
v SQL_INTEGER
v SQL_NUMERIC
v SQL_REAL
v SQL_SMALLINT
v SQL_TIME
v SQL_TIMESTAMP
v SQL_VARBINARY
v SQL_VARCHAR
v SQL_VARGRAPHIC
Usage
Because SQLGetTypeInfo() generates a result set and is equivalent to executing a query, it generates a
cursor and begins a transaction. To prepare and process another statement on this statement handle, the
cursor must be closed.
If SQLGetTypeInfo() is called with a DataType that is not valid, an empty result set is returned.
The columns of the result set that is generated by this function are described below.
Although new columns might be added and the names of the existing columns might be changed in
future releases, the position of the current columns does not change. The data types that are returned are
those that can be used in a CREATE TABLE, ALTER TABLE, DDL statement. Nonpersistent data types
are not part of the returned result set. User-defined data types are not returned either.
Table 109. Columns returned by SQLGetTypeInfo
Column number/name Data type Description
1 TYPE_NAME VARCHAR(128) NOT NULL Character representation of the SQL data type name
(for example, VARCHAR, DATE, INTEGER)
2 DATA_TYPE SMALLINT NOT NULL SQL data type define values (for example,
SQL_VARCHAR, SQL_DATE, SQL_INTEGER)
3 COLUMN_SIZE INTEGER If the data type is a character or binary string, then
this column contains the maximum length in bytes; if
it is a graphic (DBCS) string, this is the number of
double byte characters for the column.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 110. SQLGetTypeInfo SQLSTATEs
SQLSTATE Description Explanation
24000 Cursor state that is not valid A cursor is already opened on the statement handle.
StatementHandle has not been closed.
40003 08S01 Communication link failure The communication link between the application and data source
fails before the function is completed.
HY001 Memory allocation failure DB2 for i CLI is unable to allocate memory required to support
the processing or completion of the function.
HY004 SQL data type out of range A DataType that is not valid is specified.
HY010 Function sequence error The function is called while in a data-at-processing
(SQLParamData(), SQLPutData()) operation.
HY021 Internal descriptor that is not The internal descriptor cannot be addressed or allocated, or it
valid contains a value that is not valid.
HYT00 Timeout expired
Restrictions
The following ODBC specified SQL data types (and their corresponding DataType define values) are not
supported by any IBM RDBMS.
Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/* From CLI sample typeinfo.c */
/* ... */
rc = SQLGetTypeInfo(hstmt, SQL_ALL_TYPES);
CHECK_HANDLE( SQL_HANDLE_STMT, hstmt, rc ) ;
if ( rc != SQL_NO_DATA_FOUND )
CHECK_HANDLE( SQL_HANDLE_STMT, hstmt, rc ) ;
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLGetInfo - Get general information” on page 154
Syntax
SQLRETURN SQLLanguages (SQLHSTMT hstmt);
Function arguments
Table 111. SQLLanguages arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle
Usage
The function returns dialect and conformance information, in the form of a result set on StatementHandle.
This contains a row for every conformance claim the SQL product makes (including subsets defined for
ISO and vendor-specific versions). For a product that claims to comply with this specification, the result
set thus contains at least one row.
Rows defining ISO standard and vendor-specific languages can exist in the same table. Each row has at
least these columns and, if it makes an X/Open SQL conformance claim, the columns contains these
values.
Table 112. Columns returned by SQLLanguages
Column number/name Data type Description
1 SOURCE VARCHAR(254), NOT NULL The organization that defined this
SQL version.
2 SOURCE_YEAR VARCHAR(254) The year the relevant source
document is approved.
3 CONFORMANCE VARCHAR(254) The conformance level to the relevant
document that the implementation
claims.
4 INTEGRITY VARCHAR(254) An indication of whether the
implementation supports the Integrity
Enhancement Feature (IEF).
5 IMPLEMENTATION VARCHAR(254) A character string, defined by the
vendor, that uniquely identifies the
vendor's SQL product.
6 BINDING_SYTLE VARCHAR(254) Either 'EMBEDDED', 'DIRECT', OR
'CLI'.
7 PROGRAMMING_LANG VARCHAR(254) The host language for which the
binding style is supported.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 113. SQLLanguages SQLSTATEs
SQLSTATE Description Explanation
24000 Cursor state that is not valid Cursor related information is requested, but no cursor is
open.
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 String or buffer length that The value of one of the name length arguments is less
is not valid than 0, but not equal SQL_NTS.
HYC00 Driver not capable DB2 for i CLI does not support catalog as a qualifier for
table name.
Syntax
SQLRETURN SQLMoreResults (SQLHSTMT StatementHandle);
Function arguments
Table 114. SQLMoreResults arguments
Data type Argument Use Description
SQLHSTMT StatementHandle input Statement handle
Usage
This function is used to return multiple results that are set in a sequential manner upon the processing of
a stored procedure that contains SQL queries. The cursors have been left open so that the result sets
remain accessible when the stored procedure has finished processing.
After completely processing the first result set, the application can call SQLMoreResults() to determine if
another result set is available. If the current result set has unfetched rows, SQLMoreResults() discards
them by closing the cursor and, if another result set is available, returns SQL_SUCCESS.
If all the result sets have been processed, SQLMoreResults() returns SQL_NO_DATA_FOUND.
If SQLFreeStmt() is called with the SQL_CLOSE or SQL_DROP option, all pending result sets on this
statement handle are discarded.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Error conditions
Table 115. SQLMoreResults SQLSTATEs
SQLSTATE Description Explanation
40003 08S01 Communication link failure The communication link between the application and data source
fails before the function is completed.
58004 Unexpected system failure Unrecoverable system error.
HY001 Memory allocation failure DB2 for i CLI is unable to allocate memory required to support
the processing or completion of the function.
HY010 Function sequence error The function is called while in a data-at-processing
(SQLParamData(), SQLPutData()) operation.
HY013 Unexpected memory handling DB2 for i CLI is unable to access memory required to support the
error processing or completion of the function.
HY021 Internal descriptor that is not The internal descriptor cannot be addressed or allocated, or it
valid contains a value that is not valid.
HYT00 Timeout expired
Restrictions
The ODBC specification of SQLMoreResults() also allow counts associated with the processing of
parameterized INSERT, UPDATE, and DELETE statements with arrays of input parameter values to be
returned. However, DB2 for i CLI does not support the return of such count information.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLBindParameter - Bind a parameter marker to a buffer” on page 51
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLNativeSqlW(). Refer to “Unicode in DB2 for iCLI” on page 305 for
more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLNativeSql (SQLHDBC ConnectionHandle,
SQLCHAR *InStatementText,
SQLINTEGER TextLength1,
SQLCHAR *OutStatementText,
SQLINTEGER BufferLength,
SQLINTEGER *TextLength2Ptr);
Function arguments
Table 116. SQLNativeSql arguments
Data type Argument Use Description
SQLHDBC ConnectionHandle Input Connection handle.
SQLCHAR * InStatementText Input Input SQL string.
SQLINTEGER TextLength1 Input Length of InStatementText.
SQLCHAR * OutStatementText Output Pointer to buffer for the transformed output
string.
SQLINTEGER BufferLength Input Size of buffer pointed by OutStatementText.
SQLINTEGER * TextLength2Ptr Output The total number of bytes available to return
in OutStatementText. If the number of bytes
available to return is greater than or equal to
BufferLength, the output SQL string in
OutStatementText is truncated to BufferLength -
1 bytes. The value SQL_NULL_DATA is
returned if no output string is generated.
Usage
This function is called when the application wants to examine or display the transformed SQL string that
is passed to the data source by DB2 for i CLI. Translation (mapping) only occurs if the input SQL
statement string contains vendor escape clause sequences.
There are no vendor escape sequences on the IBM i operating system; this function is provided for
compatibility purposes. Also, note that this function can be used to evaluate an SQL string for syntax
errors.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 117. SQLNativeSql SQLSTATEs
SQLSTATE Description Explanation
01004 Data truncated The buffer OutStatementText is not large enough to contain the
entire SQL string, so truncation occurred. The argument
TextLength2Ptr contains the total length of the untruncated SQL
string. (Function returns with SQL_SUCCESS_WITH_INFO.)
08003 Connection is closed The ConnectionHandle does not reference an open database
connection.
37000 SQL syntax that is not valid The input SQL string in InStatementText contained a syntax error.
HY001 Memory allocation failure DB2 for i CLI is unable to allocate memory required to support
the processing or completion of the function.
HY009 Argument value that is not valid The argument InStatementText, OutStatementText, or TextLength2Ptr
is a null pointer.
HY090 String or buffer length that is not The argument TextLength1 is less than 0, but not equal to
valid SQL_NTS.
Restrictions
None.
Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/* From CLI sample native.c */
/* ... */
SQLCHAR in_stmt[1024], out_stmt[1024] ;
SQLSMALLINT pcPar ;
SQLINTEGER indicator ;
/* ... */
/* Prompt for a statement to prepare */
printf("Enter an SQL statement: \n");
gets((char *)in_stmt);
SQLNumParams(hstmt, &pcPar);
CHECK_HANDLE( SQL_HANDLE_STMT, hstmt, rc ) ;
Syntax
SQLRETURN SQLNextResult (SQLHSTMT StatementHandle,
SQLHSTMT NextResultHandle);
Function arguments
Table 118. SQLNextResult arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLHSTMT NextResultHandle Input Statement handle for next result set.
Usage
This function is used to associate the next result set from StatementHandle with NextResultHandle. This
differs from SQLMoreResults() because it allows both statement handles to process their result sets
simultaneously.
If all the result sets have been processed, SQLNextResult() returns SQL_NO_DATA_FOUND.
If SQLFreeStmt() is called with the SQL_CLOSE or SQL_DROP option, all pending result sets on this
statement handle are discarded.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NO_DATA_FOUND
Error conditions
Table 119. SQLNextResult SQLSTATEs
SQLSTATE Description Explanation
40003 08S01 Communication link failure The communication link between the application and data source
fails before the function is completed.
58004 Unexpected system failure Unrecoverable system error.
HY001 Memory allocation failure DB2 for i CLI is unable to allocate memory required to support
the processing or completion of the function.
HY010 Function sequence error The function is called while in a data-at-processing
(SQLParamData(), SQLPutData()) operation.
HY013 Unexpected memory handling DB2 for i CLI is unable to access memory required to support the
error processing or completion of the function.
HY021 Internal descriptor that is not The internal descriptor cannot be addressed or allocated, or it
valid contains a value that is not valid.
HYT00 Timeout expired
References
“SQLMoreResults - Determine whether there are more result sets” on page 185
Syntax
SQLRETURN SQLNumParams (SQLHSTMT StatementHandle,
SQLSMALLINT *ParameterCountPtr);
Function arguments
Table 120. SQLNumParams arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLSMALLINT * ParameterCountPtr Output Number of parameters in the statement.
Usage
This function can only be called after the statement that is associated with StatementHandle has been
prepared. If the statement does not contain any parameter markers, ParameterCountPtr is set to 0.
An application can call this function to determine how many SQLBindParameter() calls are necessary for
the SQL statement associated with the statement handle.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 121. SQLNumParams SQLSTATEs
SQLSTATE Description Explanation
40003 08S01 Communication link failure The communication link between the application and data source
fails before the function is completed.
HY001 Memory allocation failure DB2 for i CLI is unable to allocate memory required to support
the processing or completion of the function.
HY008 Operation canceled
HY009 Argument value that is not valid ParameterCountPtr is null.
HY010 Function sequence error This function is called before SQLPrepare() is called for the
specified StatementHandle
Restrictions
None.
Example
Refer to the example in “SQLNativeSql - Get native SQL text” on page 187.
References
v “SQLBindParam - Bind a buffer to a parameter marker” on page 46
v “SQLPrepare - Prepare a statement” on page 199
After calling this function, you can call SQLDescribeCol(), SQLColAttribute(), SQLBindCol(), or
SQLGetData().
Syntax
SQLRETURN SQLNumResultCols (SQLHSTMT hstmt,
SQLSMALLINT *pccol);
Function arguments
Table 122. SQLNumResultCols arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLSMALLINT * pccol Output Number of columns in the result set.
Usage
The function sets the output argument to zero if the last statement processed on the input statement
handle is not a SELECT.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 123. SQLNumResultCols SQLSTATEs
SQLSTATE Description Explanation
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not pcbCol is a null pointer.
valid
HY010 Function sequence error The function is called before calling SQLPrepare or
SQLExecDirect for the hstmt.
S1013 * Memory management The driver is unable to access memory required to
problem. support the processing or completion of the function.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLColAttributes - Obtain column attributes” on page 68
v “SQLDescribeCol - Describe column attributes” on page 84
Syntax
SQLRETURN SQLParamData (SQLHSTMT hstmt,
SQLPOINTER *prgbValue);
Function arguments
Table 124. SQLParamData arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLPOINTER * prgbValue Output Pointer to the value of the rgbValue
argument specified on the SQLSetParam
call.
Usage
SQLParamData() returns SQL_NEED_DATA if there is at least one SQL_DATA_AT_EXEC parameter for
which data still has not been assigned. This function returns an application defined value in prgbValue
supplied by the application during the previous SQLBindParam() call. SQLPutData() is called one or more
times to send the parameter data. SQLParamData() is called to signal that all the data has been sent for the
current parameter and to advance to the next SQL_DATA_AT_EXEC parameter. SQL_SUCCESS is
returned when all the parameters have been assigned data values and the associated statement has been
processed successfully. If any errors occur during or before actual statement processing, SQL_ERROR is
returned.
If SQLParamData() returns SQL_NEED_DATA, then only SQLPutData() or SQLCancel() calls can be made.
All other function calls using this statement handle fail. In addition, all function calls referencing the
parent hdbc of hstmt fail if they involve changing any attribute or state of that connection. Those
following function calls on the parent hdbc are also not permitted:
v SQLAllocConnect()
v SQLAllocHandle()
v SQLAllocStmt()
v SQLSetConnectOption()
Should they be called during an SQL_NEED_DATA sequence, these functions return SQL_ERROR with
SQLSTATE of HY010 and the processing of the SQL_DATA_AT_EXEC parameters is not affected.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_NEED_DATA
Diagnostics
SQLParamData() can return any SQLSTATE returned by the SQLExecDirect() and SQLExecute() functions.
In addition, the following diagnostics can also be generated:
Syntax
SQLRETURN SQLParamOptions (SQLHSTMT StatementHandle,
SQLINTEGER Crow,
SQLINTEGER *FetchOffsetPtr);
Function arguments
Table 126. SQLParamOptions arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLINTEGER Crow Input Number of values for each parameter. If this is
greater than 1, then the rgbValue argument in
SQLBindParameter() points to an array of
parameter values, and pcbValue points to an
array of lengths.
SQLINTEGER * FetchOffsetPtr Output Not currently used.
(deferred)
Usage
| This function can be used with SQLBindParameter() to set up a multiple-row INSERT statement, or to
| process UPDATE, DELETE, and MERGE statements with multiple sets of parameter values. It is assumed
| that the storage containing the data which represents the parameters is allocated and available to CLI.
| This data can be organized in a either a row-wise or a column-wise fashion. Row-wise binding is the
| term used for the case where all the data for the first row is contiguous, followed by all the data for the
| next row, and so on. Column-wise binding is used to describe the case where the data for each individual
| parameter marker is contiguous. For this case, each parameter marker's data can be provided in an array
| that does not need to be contiguous with data for the other parameter markers. The SQLBindParameter()
| function should be used to bind all of the input parameter types and lengths.
| Here is an example of the set up necessary for a multiple-row statement with row-wise binding. In this
| case, the addresses provided on SQLBindParameter() are used to reference the first row of data. All
| subsequent rows of data are referenced by incrementing those addresses by the length of the entire
| row.For instance, the application intends to insert 100 rows of data into a table, and each row contains a
| 4-byte integer value, followed by a 10-byte character value. To do this, the application allocates 1400 bytes
| of storage, and fills each 14-byte piece of storage with the appropriate data for the row.
Also, the indicator pointer passed on the SQLBindParameter() must reference an 800-byte piece of storage
(100 rows x 2 columns x 4 bytes for each indicator). The indicator array is used to pass in NULL values
for the corresponding parameter marker and row. This storage is also row-wise, so the first 8 bytes are
the 2 indicators for the first row, followed by the 2 indicators for the next row, and so on. The
SQLParamOptions() function is used by the application to specify how many rows of pararmeter values
are provided.
| The maximum number of database rows that can be specified in a multiple-row insert operation is 32,000.
| Therefore, SQLParamOptions allows only 32,767 rows to be specified at a time. Any additional rows need
| to be rebound and re-executed.
| SQLSetStmtAttr () provides an alternative means of setting the number of rows for a multiple-row
| statement using the SQL_ATTR_PARAMSET_SIZE option.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 127. SQLParamOptions SQLSTATEs
SQLSTATE Description Explanation
HY009 Argument value that is not valid The value in the argument Crow is less than 1.
HY010 Function sequence error The function is called while in a data-at-processing
(SQLParamData(), SQLPutData()) operation.
Restrictions
None.
References
v “SQLBindParam - Bind a buffer to a parameter marker” on page 46
v “SQLMoreResults - Determine whether there are more result sets” on page 185
If the statement handle has been used with a SELECT statement, SQLFreeStmt() must be called to close
the cursor, before calling SQLPrepare().
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLPrepareW() . Refer to “Unicode in DB2 for iCLI” on page 305 for
| more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLPrepare (SQLHSTMT hstmt,
SQLCHAR *szSqlStr,
SQLINTEGER cbSqlStr);
Function arguments
Table 128. SQLPrepare arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle. There must not be an
open cursor associated with hstmt.
SQLCHAR * szSqlStr Input SQL statement string.
SQLINTEGER cbSqlStr Input Length of contents of szSqlStr argument.
Usage
As soon as a statement has been prepared using SQLPrepare(), the application can request information
about the format of the result set (if it is a SELECT statement) by calling:
v SQLNumResultCols()
v SQLDescribeCol()
v SQLColAttribute()
A prepared statement can be processed once, or multiple times by calling SQLExecute(). The SQL
statement remains associated with the statement handle until the handle is used with another
SQLPrepare(), SQLExecDirect(), SQLColumns(), SQLSpecialColumns(), SQLStatistics(), or SQLTables().
The SQL statement string might contain parameter markers. A parameter marker is represented by a "?"
character, and indicates a position in the statement where the value of an application variable is to be
substituted, when SQLExecute() is called. SQLBindParam() is used to bind (or associate) an application
variable to each parameter marker, and to indicate if any data conversion should be performed at the
time the data is transferred.
The SQL statement cannot be a COMMIT or ROLLBACK. SQLTransact() must be called to issue
COMMIT or ROLLBACK.
If the SQL statement is a positioned DELETE or a Positioned UPDATE, the cursor referenced by the
statement must be defined on a separate statement handle under the same connection handle.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 129. SQLPrepare SQLSTATEs
SQLSTATE Description Explanation
24000 Cursor state that is not valid There is an open cursor on the specified hstmt.
37xxx Syntax error or access szSqlStr contained one or more of the following
violation statements:
v A COMMIT
v A ROLLBACK
v An SQL statement that the connected database server
cannot prepare
v A statement containing a syntax error
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not szSqlStr is a null pointer.
valid
The argument cbSqlStr is less than 1, but not equal to
SQL_NTS.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
not valid or it contains a value that is not valid.
Note: Not all Database Management Systems (DBMSs) report all of the above diagnostic messages at
prepare time. Therefore an application must also be able to handle these conditions when calling
SQLExecute().
Example
Refer to “Example: Interactive SQL and the equivalent DB2 for i CLI function calls” on page 313 for a
listing of the check_error, initialize, and terminate functions used in the following example.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*************************************************************************
** file = prepare.c
**
** Example of preparing then repeatedly executing an SQL statement.
**
** Functions used:
**
** SQLAllocConnect SQLFreeConnect
** SQLAllocEnv SQLFreeEnv
** SQLAllocStmt SQLFreeStmt
** SQLConnect SQLDisconnect
**
** SQLBindCol SQLFetch
** SQLTransact SQLError
** SQLPrepare SQLSetParam
** SQLExecute
**************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "sqlcli.h"
/*******************************************************************
** main
** - initialize
** - terminate
*******************************************************************/
int main()
{
SQLHENV henv;
SQLHDBC hdbc;
SQLCHAR sqlstmt[MAX_STMT_LEN + 1]="";
SQLRETURN rc;
rc = initialize(&henv, &hdbc);
if (rc == SQL_ERROR) return(terminate(henv, hdbc));
{SQLHSTMT hstmt;
SQLCHAR sqlstmt[]="SELECT deptname, location from org where division = ?";
SQLCHAR deptname[15],
location[14],
division[11];
SQLINTEGER rlength,
plength;
rc = SQLAllocStmt(hdbc, &hstmt);
if (rc != SQL_SUCCESS )
check_error (henv, hdbc, SQL_NULL_HSTMT, rc);
&rlength);
if (rc != SQL_SUCCESS )
check_error (henv, hdbc, hstmt, rc);
rc = SQLBindCol(hstmt, 2, SQL_CHAR, (SQLPOINTER) location, 14,
&rlength);
if (rc != SQL_SUCCESS )
check_error (henv, hdbc, hstmt, rc);
while(division[0] != ’q’)
{
rc = SQLExecute(hstmt);
if (rc != SQL_SUCCESS )
check_error (henv, hdbc, hstmt, rc);
terminate(henv, hdbc);
return (0);
}/* end main */
References
v “SQLColAttributes - Obtain column attributes” on page 68
v “SQLDescribeCol - Describe column attributes” on page 84
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLExecute - Execute a statement” on page 103
v “SQLNumResultCols - Get number of result columns” on page 193
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLPrimaryKeysW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLPrimaryKeys (SQLHSTMT StatementHandle,
SQLCHAR *CatalogName,
SQLSMALLINT NameLength1,
SQLCHAR *SchemaName,
SQLSMALLINT NameLength2,
SQLCHAR *TableName,
SQLSMALLINT NameLength3);
Function arguments
Table 130. SQLPrimaryKeys arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLCHAR * CatalogName Input Catalog qualifier of a 3 part table name.
Usage
SQLPrimaryKeys() returns the primary key columns from a single table. Search patterns cannot be used to
specify the schema qualifier or the table name.
The result set contains the columns that are listed in Table 131, ordered by TABLE_CAT, TABLE_SCHEM,
TABLE_NAME, and ORDINAL_POSITION.
Because calls to SQLPrimaryKeys() in many cases map to a complex and, thus, expensive query against
the system catalog, they should be used sparingly, and the results saved rather than repeating calls.
Although new columns might be added and the names of the existing columns might be changed in
future releases, the position of the current columns does not change.
Table 131. Columns returned by SQLPrimaryKeys
Column number/name Data type Description
1 TABLE_CAT VARCHAR (128) The current server.
2 TABLE_SCHEM VARCHAR (128) The name of the schema containing TABLE_NAME.
If the specified table does not contain a primary key, an empty result set is returned.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 132. SQLPrimaryKeys SQLSTATEs
SQLSTATE Description Explanation
24000 Cursor state that is not valid A cursor is already opened on the statement handle.
40003 08S01 Communication link failure The communication link between the application and data source
fails before the function is completed.
HY001 Memory allocation failure DB2 for i CLI is unable to allocate memory required to support
the processing or completion of the function.
HY008 Operation canceled
HY010 Function sequence error The function is called while in a data-at-processing
(SQLParamData(), SQLPutData()) operation.
HY014 No more handles DB2 for i CLI is unable to allocate a handle due to internal
resources.
HY021 Internal descriptor that is not The internal descriptor cannot be addressed or allocated, or it
valid contains a value that is not valid .
HY090 String or buffer length that is not The value of one of the name length arguments is less than 0, but
valid not equal to SQL_NTS.
HYC00 Driver not capable DB2 for i CLI does not support catalog as a qualifier for table
name.
HYT00 Timeout expired
Restrictions
None.
References
v “SQLForeignKeys - Get the list of foreign key columns” on page 115
v “SQLStatistics - Get index and statistics information for a base table” on page 257
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLProcedureColumnsW(). Refer to “Unicode in DB2 for iCLI” on
page 305 for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLProcedureColumns(SQLHSTMT StatementHandle,
SQLCHAR *CatalogName,
SQLSMALLINT NameLength1,
SQLCHAR *SchemaName,
SQLSMALLINT NameLength2,
SQLCHAR *ProcName,
SQLSMALLINT NameLength3,
SQLCHAR *ColumnName,
SQLSMALLINT NameLength4);
Function arguments
Table 133. SQLProcedureColumns arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLCHAR * CatalogName Input Catalog qualifier of a 3 part procedure name.
Usage
DB2 for i CLI returns information about the input, input and output, and output parameters associated
with the stored procedure, but cannot return information about the descriptor for any result sets
returned.
Because calls to SQLProcedureColumns() in many cases map to a complex and thus expensive query
against the system catalog, they should be used sparingly, and the results saved rather than repeating
calls.
Special support was added to handle a keyword "*LIBL" in the SchemaName argument. Specifying this
keyword will tell SQLStatistics to use the schema's on the library list to qualify the search criteria for
retrieving index information for tables. The highest library on the library list hierarchy that matches the
search criteria will be used. Also, system naming must be in effect for this support to be honored. The
following behavior will occur when different connections are used:
v When SQL Server Mode is used, the SQLProcedureColumns() API will use the library list of the initial
thread within the associated QSQSRVR job when processing the '*LIBL' request.
v When SQL Server Mode is not used, the SQLProcedureColumns() API will use the library list of the
current thread when processing the '*LIBL' request.
Table 134. Columns returned by SQLProcedureColumns
Column number/name Data type Description
1 PROCEDURE_CAT VARCHAR(128) The current server.
2 PROCEDURE_SCHEM VARCHAR(128) The name of the schema containing
PROCEDURE_NAME.
3 PROCEDURE_NAME VARCHAR(128) Name of the procedure.
4 COLUMN_NAME VARCHAR(128) Name of the parameter.
5 COLUMN_TYPE SMALLINT not NULL This identifies the type information associated with
this row. The values can be:
v SQL_PARAM_TYPE_UNKNOWN – the parameter
type is unknown.
Note: This is not returned.
v SQL_PARAM_INPUT – this parameter is an input
parameter.
v SQL_PARAM_INPUT_OUTPUT – this parameter is
an input / output parameter.
v SQL_PARAM_OUTPUT – this parameter is an
output parameter.
v SQL_RETURN_VALUE – the procedure column is
the return value of the procedure.
Note: This is not returned.
v SQL_RESULT_COL – this parameter is actually a
column in the result set.
Note: This is not returned.
6 DATA_TYPE SMALLINT not NULL SQL data type.
7 TYPE_NAME VARCHAR(128) not NULL Character string representing the name of the data
type corresponding to DATA_TYPE.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 135. SQLProcedureColumns SQLSTATEs
SQLSTATE Description Explanation
24000 Cursor state that is not valid A cursor is already opened on the statement handle.
40003 08S01 Communication link failure The communication link between the application and data source
fails before the function is completed.
42601 PARMLIST syntax error The PARMLIST value in the stored procedures catalog table
contains a syntax error.
HY001 Memory allocation failure DB2 for i CLI is unable to allocate memory required to support
the processing or completion of the function.
HY008 Operation canceled
HY010 Function sequence error
HY014 No more handles DB2 for i CLI is unable to allocate a handle due to internal
resources.
HY021 Internal descriptor that is not The internal descriptor cannot be addressed or allocated, or it
valid contains a value that is not valid.
HY090 String or buffer length that is not The value of one of the name length arguments is less than 0, but
valid not equal SQL_NTS.
HYC00 Driver not capable DB2 for i CLI does not support catalog as a qualifier for procedure
name.
Restrictions
SQLProcedureColumns() does not return information about the attributes of result sets that can be
returned from stored procedures.
If an application is connected to a DB2 server that does not provide support for a stored procedure
catalog, or does not provide support for stored procedures, SQLProcedureColumns() returns an empty
result set.
Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/* From CLI sample proccols.c */
/* ... */
References
The information is returned in an SQL result set, which can be retrieved using the same functions that are
used to process a result set that is generated by a query.
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLProceduresW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLProcedures (SQLHSTMT StatementHandle,
SQLCHAR *CatalogName,
SQLSMALLINT NameLength1,
SQLCHAR *SchemaName,
SQLSMALLINT NameLength2,
SQLCHAR *ProcName,
SQLSMALLINT NameLength3);
Function arguments
Table 136. SQLProcedures arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLCHAR * CatalogName Input Catalog qualifier of a 3 part procedure name.
For DB2 for z/OS and OS/390 V 4.1, all the stored
procedures are in one schema; the only acceptable
value for the SchemaName argument is a null pointer.
For DB2, SchemaName can contain a valid pattern
value.
SQLSMALLINT NameLength2 Input Length of SchemaName.
SQLCHAR * ProcName Input Buffer that might contain a pattern-value to qualify
the result set by procedure name.
SQLSMALLINT NameLength3 Input Length of ProcName.
Usage
The result set returned by SQLProcedures() contains the columns listed in Table 137 on page 212 in the
order given. The rows are ordered by PROCEDURE_CAT, PROCEDURE_SCHEMA, and
PROCEDURE_NAME.
Because calls to SQLProcedures() in many cases map to a complex and thus expensive query against the
system catalog, use them sparingly, and save the results rather than repeating calls.
Although new columns might be added and the names of the existing columns might be changed in
future releases, the position of the current columns does not change.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Error conditions
Table 138. SQLProcedures SQLSTATEs
SQLSTATE Description Explanation
24000 Cursor state that is not valid A cursor is already opened on the statement handle.
40003 08S01 Communication link failure The communication link between the application and data source
fails before the function is completed.
HY001 Memory allocation failure DB2 for i CLI is unable to allocate memory required to support
the processing or completion of the function.
HY008 Operation canceled
HY010 Function sequence error
HY014 No more handles DB2 for i CLI is unable to allocate a handle due to internal
resources.
HY021 Internal descriptor that is not The internal descriptor cannot be addressed or allocated, or it
valid contains a value that is not valid.
HY090 String or buffer length that is not The value of one of the name length arguments is less than 0, but
valid not equal to SQL_NTS.
Restrictions
If an application is connected to a DB2 server that does not provide support for a stored procedure
catalog, or does not provide support for stored procedures, SQLProcedureColumns() returns an empty
result set.
Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/* From CLI sample procs.c */
/* ... */
References
Syntax
SQLRETURN SQLPutData (SQLHSTMT hstmt,
SQLPOINTER rgbValue,
SQLINTEGER cbValue);
Function arguments
Table 139. SQLPutData arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLPOINTER rgbValue Input Pointer to the actual data, or portion of data,
for a parameter. The data must be in the
form specified in the SQLBindParam() call
that the application used when specifying
the parameter.
SQLINTEGER cbValue Input Length of rgbValue. This specifies the amount
of data sent in a call to SQLPutData().
Usage
The application calls SQLPutData() after calling SQLParamData() on a statement in the SQL_NEED_DATA
state to supply the data values for an SQL_DATA_AT_EXEC parameter. Long data can be sent in pieces
through repeated calls to SQLPutData(). After all the pieces of data for the parameter have been sent, the
application again calls SQLParamData(). SQLParamData(). proceeds to the next SQL_DATA_AT_EXEC
parameter, or, if all parameters have data values, executes the statement.
SQLPutData() cannot be called more than once for a fixed length parameter.
After an SQLPutData() call, the only legal function calls are SQLParamData(), SQLCancel(), or another
SQLPutData() if the input data is character or binary data. As with SQLParamData(), all other function calls
using this statement handle fail. In addition, all function calls referencing the parent hdbc of hstmt fail if
they involve changing any attribute or state of that connection. For a list of these functions, see the Usage
section for “SQLParamData - Get next parameter for which a data value is needed” on page 195.
If one or more calls to SQLPutData() for a single parameter result in SQL_SUCCESS, attempting to call
SQLPutData() with cbValue set to SQL_NULL_DATA for the same parameter results in an error with
SQLSTATE of HY011. This error does not result in a change of state; the statement handle is still in a Need
Data state and the application can continue sending parameter data.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Some of the following diagnostics conditions might be reported on the final SQLParamData() call rather
than at the time the SQLPutData() is called.
Table 140. SQLPutData SQLSTATEs
SQLSTATE Description Explanation
22001 Too much data The size of the data supplied to the current parameter by
SQLPutData() exceeds the size of the parameter. The data
supplied by the last call to SQLPutData() is ignored.
01004 Data truncated The data sent for a numeric parameter is truncated
without the loss of significant digits.
This function is the last DB2 for i CLI step that an application needs to do before it ends.
Syntax
SQLRETURN SQLReleaseEnv (SQLHENV henv);
Function arguments
Table 141. SQLReleaseEnv arguments
Data type Argument Use Description
SQLHENV henv Input Environment handle.
Usage
If this function is called when there is still a valid connection handle, SQL_ERROR is returned, and the
environment handle remains valid.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 142. SQLReleaseEnv SQLSTATEs
SQLSTATE Description Explanation
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY010 Function sequence error There is an hdbc which is in allocated or connected state.
Call SQLDisconnect and SQLFreeConnect for the hdbc
before calling SQLReleaseEnv.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
Example
Refer to the example in the “SQLAllocEnv - Allocate environment handle” on page 29.
References
Syntax
SQLRETURN SQLRowCount (SQLHSTMT hstmt,
SQLINTEGER *pcrow);
Function arguments
Table 143. SQLRowCount arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLINTEGER * pcrow Output Pointer to location where the number of
rows affected is stored.
Usage
If the last processed statement referenced by the input statement handle is not an SELECT from INSERT,
UPDATE, INSERT, MERGE, or DELETE statement, or if it is not processed successfully, then the function
sets the contents of pcrow to 0.
Any rows in other tables that might have been affected by the statement (for example, cascading deletes)
are not included in the count.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 144. SQLRowCount SQLSTATEs
SQLSTATE Description Explanation
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not pcrow is a null pointer.
valid
HY010 Function sequence error The function is called before calling SQLExecute or
SQLExecDirect for the hstmt.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
References
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLExecute - Execute a statement” on page 103
v “SQLNumResultCols - Get number of result columns” on page 193
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLSetConnectAttrW(). Refer to “Unicode in DB2 for iCLI” on page
| 305 for more information about Unicode support for DB2 for iCLI.
Syntax
SQLRETURN SQLSetConnectAttr (SQLHDBC hdbc,
SQLINTEGER fAttr,
SQLPOINTER vParam,
SQLINTEGER sLen);
Function arguments
Table 145. SQLSetConnectAttr arguments
Data type Argument Use Description
SQLHDBC hdbc Input Connection handle.
SQLINTEGER fAttr Input Connect attribute to set, refer to Table 146 for
more information.
SQLPOINTER vParam Input Value associated with fAttr. Depending on
the option, this can be a pointer to a 32-bit
integer value, or a character string.
SQLINTEGER sLen Input Length of input value, if it is a character
string; otherwise, unused.
Usage
All connection and statement options set through the SQLSetConnectAttr() persist until SQLFreeConnect()
is called or the next SQLSetConnectAttr() call.
The format of information set through vParam depends on the specified fAttr. The option information can
be either a 32-bit integer or a pointer to a null-terminated character string.
| Table 146. Connect options
| fAttr Contents
| SQL_ATTR_2ND_LEVEL_TEXT A 32-bit integer value:
| v SQL_TRUE – Error text obtained by calling SQLError()
| contains the complete text description of the error.
| v SQL_FALSE – Error text obtained by calling SQLError()
| contains the first-level description of the error only.
| This is the default.
| SQL_ATTR_AUTOCOMMIT A 32-bit value that sets the commit behavior for the
| connection. These are the possible values:
| v SQL_TRUE – Each SQL statement is automatically
| committed as it is processed.
| v SQL_FALSE – The SQL statements are not
| automatically committed. If running with commitment
| control, changes must be explicitly committed or rolled
| back using either SQLEndTran() or SQLTransact(). This
| is the default.
| In IBM terminology,
| v SQL_TXN_READ_UNCOMMITTED is uncommitted
| read
| v SQL_TXN_READ_COMMITTED is cursor stability
| v SQL_TXN_REPEATABLE_READ is read stability
| v SQL_TXN_SERIALIZABLE is repeatable read
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 147. SQLSetConnectAttr SQLSTATEs
SQLSTATE Description Explanation
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
References
v “SQLSetConnectOption - Set connection option” on page 231
v “SQLSetStmtOption - Set statement option” on page 251
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLSetConnectOptionW(). Refer to “Unicode in DB2 for iCLI” on
page 305 for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLSetConnectOption (SQLHDBC hdbc,
SQLSMALLINT fOption,
SQLPOINTER vParam);
Function arguments
Table 148. SQLSetConnectOption arguments
Data type Argument Use Description
SQLHDBC hdbc Input Connection handle.
SQLSMALLINT fOption Input Connect option to set, refer to Table 146 on
page 219 for more information.
SQLPOINTER vParam Input Value associated with fOption. Depending on
the option, this can be a pointer to a 32-bit
integer value, or a character string.
Usage
The SQLSetConnectOption() provides many of the same attribute functions as SQLSetConnectAttr() before
V5R3. However, SQLSetConnectOption() has since been deprecated, and support for all new attribute
functions has gone into SQLSetConnectAttr(). Users should migrate to the nondeprecated interface.
All connection and statement options set through the SQLSetConnectOption() persist until
SQLFreeConnect() is called or the next SQLSetConnectOption() call.
The format of information set through vParam depends on the specified fOption. The option information
can be either a 32-bit integer or a pointer to a null-terminated character string.
Refer to Table 146 on page 219 for the appropriate connect options.
Note: Because SQLSetConnectOption() has been deprecated, not all the options listed in the table are
supported.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 149. SQLSetConnectOption SQLSTATEs
SQLSTATE Description Explanation
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not Given the fOption value, a value that is not valid is
valid specified for the argument vParam.
References
Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
corresponding Unicode function is SQLSetCursorNameW(). Refer to “Unicode in DB2 for iCLI” on page 305
for more information about Unicode support for DB2 for i CLI.
Syntax
SQLRETURN SQLSetCursorName (SQLHSTMT hstmt,
SQLCHAR *szCursor,
SQLSMALLINT cbCursor);
Function arguments
Table 150. SQLSetCursorName arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLCHAR * szCursor Input Cursor name.
SQLSMALLINT cbCursor Input Length of contents of szCursor argument.
Usage
DB2 for i CLI always generates and uses an internally generated cursor name when a SELECT statement
is prepared or executed directly. SQLSetCursorName() allows an application-defined cursor name to be
used in an SQL statement (a Positioned UPDATE or DELETE). DB2 for i CLI maps this name to an
internal name. SQLSetCursorName() must be called before an internal name is generated. The name
remains associated with the statement handle, until the handle is dropped. The name also remains after
the transaction has ended, but at this point SQLSetCursorName() can be called to set a different name for
this statement handle.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 151. SQLSetCursorName SQLSTATEs
SQLSTATE Description Explanation
34000 Cursor name that is not The cursor name specified by the argument szCursor is
valid not valid. The cursor name either begins with "SQLCUR"
or "SQL_CUR" or violates either the driver or the data
source cursor naming rules (Must begin with a-z or A-Z
followed by any combination of English letters, digits, or
the '_' character.
References
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLSetDescFieldW(). Refer to “Unicode in DB2 for iCLI” on page 305
| for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLSetDescField (SQLHDESC hdesc,
SQLSMALLINT irec,
SQLSMALLINT fDescType,
SQLPOINTER rgbDesc,
SQLINTEGER bLen);
Function arguments
Table 152. SQLSetDescField arguments
Data type Argument Use Description
SQLHDESC hdesc Input Descriptor handle.
SQLSMALLINT irec Input Record number from which the specified
field is to be retrieved.
SQLSMALLINT fDescType Input See Table 153.
SQLPOINTER rgbDesc Input Pointer to buffer.
SQLINTEGER bLen Input Length of descriptor buffer (rgbDesc).
Usage
Instead of requiring an entire set of arguments like SQLSetDescRec(), SQLSetDescField() specifies which
attribute you want to set for a specific descriptor record.
Although SQLSetDescField() allows for future extensions, it requires more calls to set the same
information than SQLSetDescRec() for each descriptor record.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 154. SQLGetDescField SQLSTATEs
SQLSTATE Description Explanation
HY009 Argument value that is not The value specified for the argument fDescType or irec is
valid not valid.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLDescribeCol - Describe column attributes” on page 84
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLExecute - Execute a statement” on page 103
v “SQLPrepare - Prepare a statement” on page 199
Syntax
SQLRETURN SQLSetDescRec (SQLHDESC hdesc,
SQLSMALLINT irec,
SQLSMALLINT type,
SQLSMALLINT subtype,
SQLINTEGER length,
SQLSMALLINT prec,
SQLSMALLINT scale,
SQLPOINTER data,
SQLINTEGER *sLen,
SQLINTEGER *indic);
Function arguments
Table 155. SQLSetDescRec arguments
Data type Argument Use Description
SQLDESC hdesc Input Descriptor handle.
SQLSMALLINT irec Input Record number within the descriptor.
SQLSMALLINT type Input TYPE field for the record.
SQLSMALLINT subtype Input DATETIME_INTERVAL_CODE field for
records whose TYPE is SQL_DATETIME.
SQLINTEGER length Input LENGTH field for the record.
SQLSMALLINT prec Input PRECISION field for the record.
SQLSMALLINT scale Input SCALE field for the record.
SQLPOINTER data Input (deferred) DATA_PTR field for the record.
SQLINTEGER * sLen Input (deferred) LENGTH_PTR field for the record.
SQLINTEGER * indic Input (deferred) INDICATOR_PTR field for the record.
Usage
Calling SQLSetDescRec() sets all the fields in a descriptor record in one call.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 156. SQLSetDescRec SQLSTATEs
SQLSTATE Description Explanation
HY009 Argument value that is not The value specified for the argument irec is less than 1.
valid
A value that is not valid for another argument is
specified.
References
v “SQLBindCol - Bind a column to an application variable” on page 35
v “SQLDescribeCol - Describe column attributes” on page 84
v “SQLExecDirect - Execute a statement directly” on page 101
v “SQLExecute - Execute a statement” on page 103
v “SQLPrepare - Prepare a statement” on page 199
Syntax
An environment attribute cannot be set if a connection handle has been allocated. In order for the
attribute to apply to the entire CLI environment, the environment attributes must be in place before this
initial connection is made. An HY010 error code is returned otherwise.
SQLRETURN SQLSetEnvAttr (SQLHENV henv,
SQLINTEGER Attribute,
SQLPOINTER Value,
SQLINTEGER StringLength);
Function arguments
Table 157. SQLSetEnvAttr arguments
Data type Argument Use Description
SQLHEN henv Input Environment handle.
SQLINTEGER Attribute Input Environment attribute to set. Refer to
Table 158 for more information.
SQLPOINTER Value Input Appropriate value for Attribute.
SQLINTEGER StringLength Input Length of Value in bytes if the attribute value
is a character string; if Attribute does not
denote a string, then DB2 for i CLI ignores
StringLength.
Usage
In environments where the current application may exist in the same job as other applications using CLI,
connections attributes should be used instead of environment attributes. Otherwise, setting environment
attributes may cause the other application to behave unexpectedly. Ideally, the only environment
attributes that should be used are SQL_ATTR_ENVHNDL_COUNTER and SQL_ATTR_SERVER_MODE.
| Table 158. Environment attributes
| Attribute Contents
| SQL_ATTR_DATE_FMT A 32-bit integer value:
| v SQL_FMT_ISO – The International Organization for
| Standardization (ISO) date format yyyy-mm-dd is used.
| This is the default.
| v SQL_FMT_USA – The United States date format
| mm/dd/yyyy is used.
| v SQL_FMT_EUR – The European date format
| dd.mm.yyyy is used.
| v SQL_FMT_JIS – The Japanese Industrial Standard date
| format yyyy-mm-dd is used.
| v SQL_FMT_MDY – The date format mm/dd/yy is used.
| v SQL_FMT_DMY – The date format dd/mm/yy is used.
| v SQL_FMT_YMD – The date format yy/mm/dd is used.
| v SQL_FMT_JUL – The Julian date format yy/ddd is
| used.
| v SQL_FMT_JOB – The job default is used.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 159. SQLSetEnvAttr SQLSTATEs
SQLSTATE Description Explanation
HY009 Parameter value that is not The specified Attribute is not supported by DB2 for i CLI.
valid
Given specified Attributevalue, the value specified for the
argument Value is not supported.
Syntax
SQLRETURN SQLSetParam (SQLHSTMT hstmt,
SQLSMALLINT ipar,
SQLSMALLINT fCType,
SQLSMALLINT fSqlType,
SQLINTEGER cbParamDef,
SQLSMALLINT ibScale,
SQLPOINTER rgbValue,
SQLINTEGER *pcbValue);
References
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLSetStmtAttrW(). Refer to “Unicode in DB2 for iCLI” on page 305
| for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLSetStmtAttr (SQLHSTMT hstmt,
SQLINTEGER fAttr,
SQLPOINTER vParam,
SQLINTEGER sLen);
Function arguments
Table 160. SQLSetStmtAttr arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLINTEGER fAttr Input Attribute to set. Refer to Table 161 for the list
of settable statement attributes.
SQLPOINTER vParam Input Value associated with fAttr. vParam can be a
32-bit integer value or a character string.
SQLINTEGER sLen Input Length of data if data is a character string;
otherwise, unused.
Usage
Statement options for an hstmt remain in effect until they are changed by another call to
SQLSetStmtAttr() or the hstmt is dropped by calling SQLFreeStmt() with the SQL_DROP option. Calling
SQLFreeStmt() with the SQL_CLOSE, SQL_UNBIND, or SQL_RESET_PARAMS options does not reset the
statement options.
The format of information set through vParam depends on the specified fOption. The format of each is
noted in Table 161.
Table 161. Statement attributes
fAttr Contents
SQL_ATTR_APP_PARAM_DESC VParam must be a descriptor handle. The specified
descriptor serves as the application parameter descriptor
for later calls to SQLExecute() and SQLExecDirect() on
the statement handle.
SQL_ATTR_APP_ROW_DESC VParam must be a descriptor handle. The specified
descriptor serves as the application row descriptor for
later calls to SQLFetch() on the statement handle.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 162. SQLStmtAttr SQLSTATEs
SQLSTATE Description Explanation
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
HY000 General error An error occurred for which there is no specific
SQLSTATE and for which no implementation defined
SQLSTATE is defined. The error message returned by
SQLError in the argument szErrorMsg describes the error
and its cause.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument value that is not Given the specified fAttr value, a value that is not valid
valid is specified for the argument vParam.
References
v “SQLFetchScroll - Fetch from a scrollable cursor” on page 113
v “SQLSetStmtOption - Set statement option” on page 251
SQLSetStmtOption() sets an attribute of a specific statement handle. To set an option for all statement
handles associated with a connection handle, the application can call SQLSetConnectAttr(). See
“SQLSetConnectAttr - Set a connection attribute” on page 219 for additional details.
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLSetStmtOptionW(). Refer to “Unicode in DB2 for iCLI” on page 305
| for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLSetStmtOption (SQLHSTMT hstmt,
SQLSMALLINT fOption,
SQLPOINTER vParam);
Function arguments
Table 163. SQLSetStmtOption arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLSMALLINT fOption Input Option to set. Refer to Table 161 on page 245 for the list
of settable statement options.
SQLPOINTER vParam Input Value associated with fOption. vParam can be a pointer
to a 32-bit integer value or a character string.
Usage
The SQLSetStmtOption() provides many of the same attribute functions as SQLSetStmtAttr() before V5R3.
However, it has since been deprecated, and support for all new attribute functions has gone into
SQLSetStmtAttr(). Users should migrate to the nondeprecated interface.
Statement options for an hstmt remain in effect until they are changed by another call to
SQLSetStmtOption() or the hstmt is dropped by calling SQLFreeStmt() with the SQL_DROP option.
Calling SQLFreeStmt() with the SQL_CLOSE, SQL_UNBIND, or SQL_RESET_PARAMS options does not
reset statement options.
The format of information set through vParam depends on the specified fOption. The format of each is
noted in Table 161 on page 245.
Refer to Table 161 on page 245 for the proper statement options.
Note: Because the SQLSetStmtOption() function has been deprecated, not all the options listed in the
table are supported."
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 164. SQLStmtOption SQLSTATEs
SQLSTATE Description Explanation
40003 * Statement The communication link between the CLI and the data source fails before the function
completion completes processing.
unknown
HY000 General error An error occurred for which there is no specific SQLSTATE and for which no
implementation defined SQLSTATE is defined. The error message returned by SQLError
in the argument szErrorMsg describes the error and its cause.
HY001 Memory allocation The driver is unable to allocate memory required to support the processing or
failure completion of the function.
HY009 Argument value Given the specified fOption value, a value that is not valid is specified for the argument
that is not valid vParam.
References
v “SQLSetConnectAttr - Set a connection attribute” on page 219
v “SQLSetStmtAttr - Set a statement attribute” on page 245
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLSpecialColumnsW(). Refer to “Unicode in DB2 for iCLI” on page
| 305 for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLSpecialColumns (SQLHSTMT hstmt,
SQLSMALLINT fColType,
SQLCHAR *szCatalogName,
SQLSMALLINT cbCatalogName,
SQLCHAR *szSchemaName,
SQLSMALLINT cbSchemaName,
SQLCHAR *szTableName,
SQLSMALLINT cbTableName,
SQLSMALLINT fScope,
SQLSMALLINT fNullable);
Function arguments
Table 165. SQLSpecialColumns arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLSMALLINT fColType Input Reserved for future use to support additional
types of special columns.
Usage
If multiple ways exist to uniquely identify any row in a table (for example, if there are multiple unique
indexes on the specified table), then DB2 for i CLI returns the best set of row identifier columns based on
its internal criterion.
If there is no column set that allows any row in the table to be uniquely identified, an empty result set is
returned.
The unique row identifier information is returned in the form of a result set where each column of the
row identifier is represented by one row in the result set. The result set returned by SQLSpecialColumns()
has the following columns in the following order:
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 167. SQLSpecialColumns SQLSTATEs
SQLSTATE Description Explanation
24000 Cursor state that is not valid Cursor related information is requested, but no cursor is
open.
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument length that is not The value of one of the length arguments is less than 0,
valid but not equal to SQL_NTS.
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLStatisticsW(). Refer to “Unicode in DB2 for iCLI” on page 305 for
| more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLStatistics (SQLHSTMT hstmt,
SQLCHAR *szCatalogName,
SQLSMALLINT cbCatalogName,
SQLCHAR *szSchemaName,
SQLSMALLINT cbSchemaName,
SQLCHAR *szTableName,
SQLSMALLINT cbTableName,
SQLSMALLINT fUnique,
SQLSMALLINT fAccuracy);
Function arguments
Table 168. SQLStatistics arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLCHAR * szCatalogName Input Catalog qualifier of a three-part table name. This
must be a null pointer or a zero length string.
SQLSMALLINT cbCatalogName Input Length of cbCatalogName. This must be set to 0.
SQLCHAR * szSchemaName Input Schema qualifier of the specified table.
SQLSMALLINT cbSchemaName Input Length of szSchemaName.
SQLCHAR * szTableName Input Table name.
SQLSMALLINT cbTableName Input Length of cbTableName.
SQLSMALLINT fUnique Input Type of index information to return:
v SQL_INDEX_UNIQUE
Only unique indexes are returned.
v SQL_INDEX_ALL
All indexes are returned.
SQLSMALLINT fAccuracy Input Not currently used, must be set to 0.
Usage
– Information about each index, where each index column is represented by one row of the result set.
The result set columns are given in the following table in the order shown; the rows in the result set
are ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_QUALIFIER, INDEX_NAME
and ORDINAL_POSITION.
Table 169. Columns returned by SQLStatistics
Column number/name Data type Description
1 TABLE_CAT VARCHAR(128) The name of the catalog containing
TABLE_SCHEM. This is set to NULL.
2 TABLE_SCHEM VARCHAR(128) The name of the schema containing
TABLE_NAME.
3 TABLE_NAME VARCHAR(128) not NULL Name of the table.
4 NON_UNIQUE SMALLINT This indicates whether the index
prohibits duplicate values:
v TRUE if the index allows duplicate
values.
v FALSE if the index values must be
unique.
v NULL is returned if the TYPE
column indicates that this row is
SQL_TABLE_STAT (statistics
information about the table itself).
5 INDEX_QUALIFIER VARCHAR(128) The identifier used to qualify the
index name. This is NULL if the
TYPE column indicates
SQL_TABLE_STAT.
6 INDEX_NAME VARCHAR(128) The name of the index. If the TYPE
column has the value
SQL_TABLE_STAT, this column has
the value NULL.
7 TYPE SMALLINT not NULL This indicates the type of information
contained in this row of the result set:
v SQL_TABLE_STAT
This indicates this row contains
statistics information about the
table itself.
v SQL_INDEX_CLUSTERED
This indicates this row contains
information about an index, and
the index type is a clustered index.
v SQL_INDEX_HASHED
This indicates this row contains
information about an index, and
the index type is a hashed index.
v SQL_INDEX_OTHER
This indicates this row contains
information about an index, and
the index type is other than
clustered or hashed.
Note: Currently,
SQL_INDEX_OTHER is the only
possible type.
For the row in the result set that contains table statistics (TYPE is set to SQL_TABLE_STAT), the columns
values of NON_UNIQUE, INDEX_QUALIFIER, INDEX_NAME, ORDINAL_POSITION,
COLUMN_NAME, and COLLATION are set to NULL. If the CARDINALITY or PAGES information
cannot be determined, then NULL is returned for those columns.
If argument szSchemaName is not specified, the schema name qualifier defaults to the one currently in
effect for the current connection.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 170. SQLStatistics SQLSTATEs
SQLSTATE Description Explanation
24000 Cursor state that is not valid Cursor related information is requested, but no cursor is
open.
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument or buffer length The value of one of the name length arguments is less
that is not valid than 0, but not equal to SQL_NTS.
HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
not valid or it contains a value that is not valid.
HYC00 Driver not capable The catalog part (the first part) of a three-part table name
is not supported by the data source.
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLTablePrivilegesW(). Refer to “Unicode in DB2 for iCLI” on page
| 305 for more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLTablePrivileges (SQLHSTMT StatementHandle,
SQLCHAR *CatalogName,
SQLSMALLINT NameLength1,
SQLCHAR *SchemaName,
SQLSMALLINT NameLength2,
SQLCHAR *TableName,
SQLSMALLINT NameLength3);
Function arguments
Table 171. SQLTablePrivileges arguments
Data type Argument Use Description
SQLHSTMT StatementHandle Input Statement handle.
SQLCHAR * szTableQualifier Input Catalog qualifier of a 3 part table name. This
must be a null pointer or a zero length
string.
SQLSMALLINT cbTableQualifier Input Length of CatalogName. This must be set to 0.
SQLCHAR * SchemaName Input Buffer that might contain a pattern-value to
qualify the result set by schema name.
SQLSMALLINT NameLength2 Input Length of SchemaName.
SQLCHAR * TableName Input Buffer that might contain a pattern-value to
qualify the result set by table name.
SQLSMALLINT NameLength3 Input Length of TableName.
Usage
The results are returned as a standard result set containing the columns listed in the following table. The
result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and PRIVILEGE. If multiple
privileges are associated with any given table, each privilege is returned as a separate row.
The granularity of each privilege reported here might or might not apply at the column level; for
example, for some data sources, if a table can be updated, every column in that table can also be
updated. For other data sources, the application must call SQLColumnPrivileges() to discover if the
individual columns have the same table privileges.
Because calls to SQLColumnPrivileges() in many cases map to a complex and thus expensive query
against the system catalog, they should be used sparingly, and the results saved rather than repeating
calls.
The VARCHAR columns of the catalog functions result set have been declared with a maximum length
attribute of 128 to be consistent with SQL92 limits. Because DB2 names are always 128 characters or less ,
the application may choose to always set aside 128 characters (plus the null-terminator) for the output
buffer, or alternatively, call SQLGetInfo() with SQL_MAX_CATALOG_NAME_LEN,
Although new columns can be added and the names of the existing columns changed in future releases,
the position of the current columns does not change.
Table 172. Columns returned by SQLTablePrivileges
Column number/name Data type Description
1 TABLE_CAT VARCHAR(128) This is always null.
2 TABLE_SCHEM VARCHAR(128) The name of the schema containing
TABLE_NAME.
3 TABLE_NAME VARCHAR(128) not NULL The name of the table.
4 GRANTOR VARCHAR(128) Authorization ID of the user who
granted the privilege.
5 GRANTEE VARCHAR(128) Authorization ID of the user to whom
the privilege is granted.
6 PRIVILEGE VARCHAR(128) The table privilege. This can be one of
the following strings:
v ALTER
v CONTROL
v INDEX
v DELETE
v INSERT
v REFERENCES
v SELECT
v UPDATE
7 IS_GRANTABLE VARCHAR(3) This indicates whether the grantee is
permitted to grant the privilege to
other users.
Note: The column names used by DB2 for i CLI follow the X/Open CLI CAE specification style. The
column types, contents and order are identical to those defined for the SQLProcedures() result set
in ODBC.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 173. SQLTablePrivileges SQLSTATEs
SQLSTATE Description Explanation
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 String or buffer length that The value of one of the name length arguments is less
is not valid than 0, but not equal SQL_NTS.
HY010 Function sequence error There is an open cursor for this statement handle, or
there is no connection for this statement handle.
HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
not valid or it contains a value that is not valid.
Restrictions
None.
Example
/* From the CLI sample TBINFO.C */
/* ... */
/* call SQLTablePrivileges */
printf("\n Call SQLTablePrivileges for:\n");
printf(" tbSchemaPattern = %s\n", tbSchemaPattern);
printf(" tbNamePattern = %s\n", tbNamePattern);
sqlrc = SQLTablePrivileges( hstmt, NULL, 0,
tbSchemaPattern, SQL_NTS,
tbNamePattern, SQL_NTS);
STMT_HANDLE_CHECK( hstmt, sqlrc);
| Unicode (UTF-16) equivalent: This function can also be used with the Unicode (UTF-16) character set. The
| corresponding Unicode function is SQLTablesW(). Refer to “Unicode in DB2 for iCLI” on page 305 for
| more information about Unicode support for DB2 CLI.
Syntax
SQLRETURN SQLTables (SQLHSTMT hstmt,
SQLCHAR *szCatalogName,
SQLSMALLINT cbCatalogName,
SQLCHAR *szSchemaName,
SQLSMALLINT cbSchemaName,
SQLCHAR *szTableName,
SQLSMALLINT cbTableName,
SQLCHAR *szTableType,
SQLSMALLINT cbTableType);
Function arguments
Table 174. SQLTables arguments
Data type Argument Use Description
SQLHSTMT hstmt Input Statement handle.
SQLCHAR * szCatalogName Input Buffer that might contain a pattern-value to
qualify the result set. Catalog is the first part
of a three-part table name.
Note: The szCatalogName, szSchemaName, and szTableName arguments accept search patterns.
An escape character can be specified in conjunction with a wildcard character to allow that actual
character to be used in the search pattern. The escape character is specified on the
SQL_ATTR_ESCAPE_CHAR environment attribute. Use of SQL_ATTR_ESCAPE_CHAR will be
deprecated in a future release. Support for the SQL_ATTR_ESCAPE_CHAR value is only honored if the
connection attribute SQL_ATTR_OLD_MTADTA_BEHAVIOR is set to SQL_TRUE.
Usage
Table information is returned in a result set where each table is represented by one row of the result set.
To support obtaining just a list of schemas, the following special semantics for the szSchemaName
argument can be applied: if szSchemaName is a string containing a single percent (%) character, and
cbCatalogName, szTableName, and szTableType are empty strings, then the result set contains a list of
non-duplicate schemas in the data source.
The result set returned by SQLTables() contains the columns listed in the following table in the order
given.
Table 175. Columns returned by SQLTables
Column number/name Data type Description
1 TABLE_CAT VARCHAR(128) The current server.
2 TABLE_SCHEM VARCHAR(128) The name of the schema containing TABLE_NAME.
3 TABLE_NAME VARCHAR(128) The name of the table, view, alias, or synonym.
4 TABLE_TYPE VARCHAR(128) This identifies the type given by the name in the
TABLE_NAME column. It can have the string values
ALIAS, BASE TABLE, MATERIALIZED QUERY TABLE,
SYSTEM TABLE, TABLE, or VIEW.
5 REMARKS VARCHAR(254) This contains the descriptive information about the table.
Return codes
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 176. SQLTables SQLSTATEs
SQLSTATE Description Explanation
24000 Cursor state that is not valid Cursor-related information is requested, but no cursor is
open.
40003 * Statement completion The communication link between the CLI and the data
unknown source fails before the function completes processing.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY009 Argument or buffer length The value of one of the name length arguments is less
that is not valid than 0, but not equal to SQL_NTS.
HY021 Internal descriptor that is The internal descriptor cannot be addressed or allocated,
not valid or it contains a value that is not valid.
HYC00 Driver not capable The catalog part (the first part) of a three-part table name
is not supported by the data source.
All changes to the database that have been made on the connection since connect time or the previous
call to SQLTransact() (whichever is the most recent) are committed or rolled back.
If a transaction is active on a connection, the application must call SQLTransact() before it can be
disconnected from the database.
Syntax
SQLRETURN SQLTransact (SQLHENV henv,
SQLHDBC hdbc,
SQLSMALLINT fType);
Function arguments
Table 177. SQLTransact arguments
Data type Argument Use Description
SQLHENV henv Input Environment handle.
Usage
If no transaction is currently active on the connection, calling SQLTransact() has no effect on the database
server and returns SQL_SUCCESS.
SQLTransact() might fail while executing the COMMIT or ROLLBACK due to a loss of connection. In
this case the application might be unable to determine whether the COMMIT or ROLLBACK has been
processed, and a database administrator's help might be required. Refer to the DBMS product information
for more information about transaction logs and other transaction management tasks.
Return codes
v SQL_SUCCESS
v SQL_ERROR
v SQL_INVALID_HANDLE
Diagnostics
Table 178. SQLTransact SQLSTATEs
SQLSTATE Description Explanation
08003 Connection not open The hdbc is not in a connected state.
08007 Connection failure during The connection associated with the hdbc fails during the
transaction processing of the function during the processing of the
function and it cannot be determined whether the
requested COMMIT or ROLLBACK occurs before the
failure.
58004 System error Unrecoverable system error.
HY001 Memory allocation failure The driver is unable to allocate memory required to
support the processing or completion of the function.
HY012 Transaction operation state The value specified for the argument fType is neither
that is not valid SQL_COMMIT nor SQL_ROLLBACK.
HY013 * Memory management The driver is unable to access memory required to
problem support the processing or completion of the function.
Example
/* */
/* Function Prototype List: SQLAllocConnect */
/* SQLAllocEnv */
/* SQLAllocHandle */
/* SQLAllocStmt */
/* SQLBindCol */
/* SQLBindFileToCol */
/* SQLBindFileToParam */
/* SQLBindParam */
/* SQLBindParameter */
/* SQLCancel */
/* SQLCloseCursor */
/* SQLColAttribute */
/* SQLColAttributeW */
/* SQLColAttributes */
/* SQLColAttributesW */
/* SQLColumnPrivileges */
/* SQLColumnPrivilegesW */
/* SQLColumns */
/* SQLColumnsW */
/* SQLConnect */
/* SQLConnectW */
/* SQLCopyDesc */
/* SQLDataSources */
/* SQLDataSourcesW */
/* SQLDescribeCol */
/* SQLDescribeColW */
/* SQLDescribeParam */
/* SQLDisconnect */
/* SQLDriverConnect */
/* SQLDriverConnectW */
/* SQLEndTran */
/* SQLError */
/* SQLErrorW */
/* SQLExecDirect */
/* SQLExecDirectW */
/* SQLExecute */
/* SQLExtendedFetch */
/* SQLFetch */
/* SQLFetchScroll */
/* SQLForeignKeys */
/* SQLForeignKeysW */
/* SQLFreeConnect */
/* SQLFreeEnv */
/* SQLFreeHandle */
/* SQLFreeStmt */
/* SQLGetCol */
/* SQLGetConnectOption */
/* SQLGetConnectOptionW */
/* SQLGetCursorName */
/* SQLGetCursorNameW */
/* SQLGetConnectAttr */
/* SQLGetConnectAttrW */
/* SQLGetData */
/* SQLGetDescField */
/* SQLGetDescFieldW */
/* SQLGetDescRec */
/* SQLGetDescRecW */
/* SQLGetDiagField */
/* SQLGetDiagFieldW */
/* SQLGetDiagRec */
/* SQLGetDiagRecW */
/* SQLGetEnvAttr */
/* SQLGetFunctions */
/* SQLGetInfo */
/* SQLGetInfoW */
/* SQLGetLength */
/* SQLGetPosition */
/* SQLGetPositionW */
/* SQLGetStmtAttr */
/* SQLGetStmtAttrW */
/* SQLGetStmtOption */
/* SQLGetStmtOptionW */
/* SQLGetSubString */
/* SQLGetSubStringW */
/* SQLGetTypeInfo */
/* SQLGetTypeInfoW */
/* SQLLanguages */
/* SQLMoreResults */
/* SQLNativeSql */
/* SQLNativeSqlW */
/* SQLNextResult */
/* SQLNumParams */
/* SQLNumResultCols */
/* SQLParamData */
/* SQLParamOptions */
/* SQLPrepare */
/* SQLPrepareW */
/* SQLPrimaryKeys */
/* SQLPrimaryKeysW */
/* SQLProcedureColumns */
/* SQLProcedureColumnsW */
/* SQLProcedures */
/* SQLProceduresW */
/* SQLPutData */
/* SQLReleaseEnv */
/* SQLRowCount */
/* SQLSetConnectAttr */
/* SQLSetConnectAttrW */
/* SQLSetConnectOption */
/* SQLSetConnectOptionW */
/* SQLSetCursorName */
/* SQLSetCursorNameW */
/* SQLSetDescField */
/* SQLSetDescFieldW */
/* SQLSetDescRec */
/* SQLSetEnvAttr */
/* SQLSetParam */
/* SQLSetStmtAttr */
/* SQLSetStmtAttrW */
/* SQLSetStmtOption */
/* SQLSetStmtOptionW */
/* SQLSpecialColumns */
/* SQLSpecialColumnsW */
/* SQLStartTran */
/* SQLStatistics */
/* SQLStatisticsW */
/* SQLTablePrivileges */
/* SQLTablePrivilegesW */
/* SQLTables */
/* SQLTablesW */
/* SQLTransact */
/* */
/* Change Activity: */
/* */
/* CFD List: */
/* */
/* FLAG REASON LEVEL DATE PGMR CHANGE DESCRIPTION */
/* ---- ------------ ----- ------ --------- ----------------------*/
/* $A0= D91823 3D60 941206 MEGERIAN New Include */
/* $A1= D94881 4D20 960816 MEGERIAN V4R2M0 enhancements */
/* $A2= D95600 4D30 970910 MEGERIAN V4R3M0 enhancements */
/* $A3= P3682850 4D40 981030 MEGERIAN V4R4M0 enhancements */
/* $A4= D97596 4D50 990326 LJAMESON V4R5M0 enhancements */
#ifndef SQL_H_SQLCLI
#define SQL_H_SQLCLI /* Permit duplicate Includes */
#ifdef __ILEC400__
#pragma checkout(suspend)
#pragma nomargins nosequence
#else
#pragma info(none)
#endif
#ifndef __SQL_EXTERN
#ifdef __ILEC400__
#define SQL_EXTERN extern
#else
#ifdef __cplusplus
#ifdef __TOS_OS400__
#define SQL_EXTERN extern "C nowiden"
#else
#define SQL_EXTERN extern "C"
#endif
#else
#define SQL_EXTERN extern
#endif /* __cplusplus */
#endif /* __ILEC_400__ */
#define __SQL_EXTERN
#endif
#ifdef __ILEC400__
#pragma argument (SQLAllocConnect , nowiden)
#pragma argument (SQLAllocEnv , nowiden)
#pragma argument (SQLAllocHandle , nowiden)
#pragma argument (SQLAllocStmt , nowiden)
#pragma argument (SQLBindCol , nowiden)
#pragma argument (SQLBindFileToCol , nowiden)
#pragma argument (SQLBindFileToParam , nowiden)
#pragma argument (SQLBindParam , nowiden)
#pragma argument (SQLBindParameter , nowiden)
#pragma argument (SQLCancel , nowiden)
#pragma argument (SQLCloseCursor , nowiden)
#pragma argument (SQLColAttribute , nowiden)
#pragma argument (SQLColAttributeW , nowiden)
#pragma argument (SQLColAttributes , nowiden)
#pragma argument (SQLColAttributesW , nowiden)
/* RETCODE values */
/* Note: The return codes will reflect the XA return code specifications,
when using CLI to execute XA transactions (use of the
SQLSetConnectAttr - SQL_ATTR_TXN_INFO attribute).
The XA return codes can be found in the XA.h include file. @D3A*/
#define SQL_SUCCESS 0
#define SQL_SUCCESS_WITH_INFO 1
#define SQL_NO_DATA_FOUND 100
#define SQL_NEED_DATA 99
#define SQL_NO_DATA SQL_NO_DATA_FOUND
#define SQL_ERROR -1
#define SQL_INVALID_HANDLE -2
#define SQL_STILL_EXECUTING 2
#define SQL_CLOSE 0
#define SQL_DROP 1
#define SQL_UNBIND 2
#define SQL_RESET_PARAMS 3
/* SQLSetParam defines */
#define SQL_C_DEFAULT 99
#define SQL_LOCK_TYPES -1
#define SQL_POS_OPERATIONS -1
#define SQL_CB_DELETE 1
#define SQL_CB_CLOSE 2
#define SQL_CB_PRESERVE 3
/*
* Output values for SQL_ODBC_API_CONFORMANCE
* info type in SQLGetInfo
*/
#define SQL_OAC_NONE 0 /* @C1A*/
#define SQL_OAC_LEVEL1 1 /* @C1A*/
#define SQL_OAC_LEVEL2 2 /* @C1A*/
/*
* Output values for SQL_ODBC_SQL_CONFORMANCE
* info type in SQLGetInfo
*/
#define SQL_OSC_MINIMUM 0 /* @C1A*/
#define SQL_OSC_CORE 1 /* @C1A*/
#define SQL_OSC_EXTENDED 2 /* @C1A*/
/*
* Output values for SQL_QUALIFIER_USAGE
* info type in SQLGetInfo
*/
#define SQL_QU_NOT_SUPPORTED 0x00000000 /* @C1A*/
#define SQL_QU_DML_STATEMENTS 0x00000001 /* @C1A*/
#define SQL_QU_PROCEDURE_INVOCATION 0x00000002 /* @C1A*/
#define SQL_QU_TABLE_DEFINITION 0x00000004 /* @C1A*/
#define SQL_QU_INDEX_DEFINITION 0x00000008 /* @C1A*/
#define SQL_QU_PRIVILEGE_DEFINITION 0x00000010 /* @C1A*/
/*
* Output values for SQL_QUALIFIER_LOCATION
* info type in SQLGetInfo
*/
#define SQL_QL_START 1 /* @C1A*/
#define SQL_QL_END 2 /* @C1A*/
/*
* Output values for SQL_OWNER_USAGE
* info type in SQLGetInfo
*/
#define SQL_OU_DML_STATEMENTS 0x00000001 /* @C1A*/
#define SQL_OU_PROCEDURE_INVOCATION 0x00000002 /* @C1A*/
#define SQL_OU_TABLE_DEFINITION 0x00000004 /* @C1A*/
#define SQL_OU_INDEX_DEFINITION 0x00000008 /* @C1A*/
#define SQL_OU_PRIVILEGE_DEFINITION 0x00000010 /* @C1A*/
/*
* Output values for SQL_TXN_CAPABLE
* info type in SQLGetInfo
*/
#define SQL_TC_NONE 0 /* @C1A*/
#define SQL_TC_DML 1 /* @C1A*/
#define SQL_TC_ALL 2 /* @C1A*/
#define SQL_TC_DDL_COMMIT 3 /* @C1A*/
#define SQL_TC_DDL_IGNORE 4 /* @C1A*/
/*
* Output values for SQL_DEFAULT_TXN_ISOLATION
* info type in SQLGetInfo
*/
/*
* Output values for SQL_STRING_FUNCTIONS
* info type in SQLGetInfo
*/
#define SQL_FN_STR_CONCAT 0x00000001
#define SQL_FN_STR_UCASE 0x00000002
#define SQL_FN_STR_LCASE 0x00000004
#define SQL_FN_STR_SUBSTRING 0x00000008
#define SQL_FN_STR_LENGTH 0x00000010
#define SQL_FN_STR_POSITION 0x00000020
#define SQL_FN_STR_LTRIM 0x00000040
#define SQL_FN_STR_RTRIM 0x00000080
/*
* Output values for SQL_POS_OPERATIONS
* info type in SQLGetInfo (not currently supported)
*/
#define SQL_POS_POSITION 0x00000001
#define SQL_POS_REFRESH 0x00000002
#define SQL_POS_UPDATE 0x00000004
#define SQL_POS_DELETE 0x00000008
#define SQL_POS_ADD 0x00000010
/*
* Output values for SQL_NUMERIC_FUNCTIONS
* info type in SQLGetInfo
*/
#define SQL_FN_NUM_ABS 0x00000001
#define SQL_FN_NUM_ACOS 0x00000002
#define SQL_FN_NUM_ASIN 0x00000004
#define SQL_FN_NUM_ATAN 0x00000008
#define SQL_FN_NUM_ATAN2 0x00000010
#define SQL_FN_NUM_CEILING 0x00000020
#define SQL_FN_NUM_COS 0x00000040
#define SQL_FN_NUM_COT 0x00000080
#define SQL_FN_NUM_EXP 0x00000100
#define SQL_FN_NUM_FLOOR 0x00000200
#define SQL_FN_NUM_LOG 0x00000400
#define SQL_FN_NUM_MOD 0x00000800
#define SQL_FN_NUM_SIGN 0x00001000
#define SQL_FN_NUM_SIN 0x00002000
#define SQL_FN_NUM_SQRT 0x00004000
#define SQL_FN_NUM_TAN 0x00008000
#define SQL_FN_NUM_PI 0x00010000
#define SQL_FN_NUM_RAND 0x00020000
#define SQL_FN_NUM_DEGREES 0x00040000
#define SQL_FN_NUM_LOG10 0x00080000
#define SQL_FN_NUM_POWER 0x00100000
#define SQL_FN_NUM_RADIANS 0x00200000
#define SQL_FN_NUM_ROUND 0x00400000
#define SQL_FN_NUM_TRUNCATE 0x00800000
/* SQL_SQL92_VALUE_EXPRESSIONS bitmasks */
#define SQL_SVE_CASE 0x00000001
#define SQL_SVE_CAST 0x00000002
#define SQL_SVE_COALESCE 0x00000004
#define SQL_SVE_NULLIF 0x00000008
/* SQL_SQL92_PREDICATES bitmasks */
#define SQL_SP_EXISTS 0x00000001
/* SQL_AGGREGATE_FUNCTIONS bitmasks */
#define SQL_AF_AVG 0x00000001
#define SQL_AF_COUNT 0x00000002
#define SQL_AF_MAX 0x00000004
#define SQL_AF_MIN 0x00000008
#define SQL_AF_SUM 0x00000010
#define SQL_AF_DISTINCT 0x00000020
#define SQL_AF_ALL 0x00000040
/* SQL_SQL_CONFORMANCE bitmasks */
#define SQL_SC_SQL92_ENTRY 0x00000001
#define SQL_SC_FIPS127_2_TRANSITIONAL 0x00000002
#define SQL_SC_SQL92_INTERMEDIATE 0x00000004
#define SQL_SC_SQL92_FULL 0x00000008
/* SQL_CONVERT_FUNCTIONS functions */
#define SQL_FN_CVT_CONVERT 0x00000001
#define SQL_FN_CVT_CAST 0x00000002
/* SQL_POSITIONED_STATEMENTS bitmasks */
#define SQL_PS_POSITIONED_DELETE 0x00000001
#define SQL_PS_POSITIONED_UPDATE 0x00000002
#define SQL_PS_SELECT_FOR_UPDATE 0x00000004
/* SQL_TIMEDATE_FUNCTIONS bitmasks */
#define SQL_FN_TD_NOW 0x00000001
#define SQL_FN_TD_CURDATE 0x00000002
#define SQL_FN_TD_DAYOFMONTH 0x00000004
#define SQL_FN_TD_DAYOFWEEK 0x00000008
#define SQL_FN_TD_DAYOFYEAR 0x00000010
#define SQL_FN_TD_MONTH 0x00000020
#define SQL_FN_TD_QUARTER 0x00000040
#define SQL_FN_TD_WEEK 0x00000080
#define SQL_FN_TD_YEAR 0x00000100
#define SQL_FN_TD_CURTIME 0x00000200
#define SQL_FN_TD_HOUR 0x00000400
#define SQL_FN_TD_MINUTE 0x00000800
#define SQL_FN_TD_SECOND 0x00001000
#define SQL_FN_TD_TIMESTAMPADD 0x00002000
#define SQL_FN_TD_TIMESTAMPDIFF 0x00004000
#define SQL_FN_TD_DAYNAME 0x00008000
#define SQL_FN_TD_MONTHNAME 0x00010000
#define SQL_FN_TD_CURRENT_DATE 0x00020000
#define SQL_FN_TD_CURRENT_TIME 0x00040000
#define SQL_FN_TD_CURRENT_TIMESTAMP 0x00080000
#define SQL_FN_TD_EXTRACT 0x00100000
/*
* Output values for SQL_CORRELATION_NAME
* info type in SQLGetInfo
*/
#define SQL_CN_NONE 0 /* @C1A*/
#define SQL_CN_DIFFERENT 1 /* @C1A*/
#define SQL_CN_ANY 2 /* @C1A*/
/*
* Output values for SQL_IDENTIFIER_CASE
* info type in SQLGetInfo
*/
#define SQL_IC_UPPER 1 /* @C1A*/
#define SQL_IC_LOWER 2 /* @C1A*/
#define SQL_IC_SENSITIVE 3 /* @C1A*/
#define SQL_IC_MIXED 4 /* @C1A*/
/*
* Output values for SQL_NON_NULLABLE_COLUMNS
* info type in SQLGetInfo
*/
#define SQL_NNC_NULL 0 /* @C1A*/
#define SQL_NNC_NON_NULL 1 /* @C1A*/
/*
* Output values for SQL_GROUP_BY
* info type in SQLGetInfo
*/
#define SQL_GB_NO_RELATION 0 /* @C1A*/
#define SQL_GB_NOT_SUPPORTED 1 /* @C1A*/
#define SQL_GB_GROUP_BY_EQUALS_SELECT 2 /* @C1A*/
#define SQL_GB_GROUP_BY_CONTAINS_SELECT 3 /* @C1A*/
#define SQL_DOUBLE 8
#define SQL_DATETIME 9
#define SQL_VARCHAR 12
#define SQL_BLOB 13
#define SQL_CLOB 14
#define SQL_DBCLOB 15
#define SQL_DATALINK 16
#define SQL_WCHAR 17
#define SQL_WVARCHAR 18
#define SQL_BIGINT 19
#define SQL_BLOB_LOCATOR 20
#define SQL_CLOB_LOCATOR 21
#define SQL_DBCLOB_LOCATOR 22
#define SQL_UTF8_CHAR 23 /* @D1A*/
#define SQL_WLONGVARCHAR SQL_WVARCHAR
#define SQL_LONGVARCHAR SQL_VARCHAR
#define SQL_GRAPHIC 95
#define SQL_VARGRAPHIC 96
#define SQL_LONGVARGRAPHIC SQL_VARGRAPHIC
#define SQL_BINARY -2
#define SQL_VARBINARY -3
#define SQL_LONGVARBINARY SQL_VARBINARY
#define SQL_DATE 91
#define SQL_TYPE_DATE 91
#define SQL_TIME 92
#define SQL_TYPE_TIME 92
#define SQL_TIMESTAMP 93
#define SQL_TYPE_TIMESTAMP 93
#define SQL_CODE_DATE 1
#define SQL_CODE_TIME 2
#define SQL_CODE_TIMESTAMP 3
#define SQL_ALL_TYPES 0
#define SQL_DECFLOAT -360 /* @E2A*/
#define SQL_XML -370 /* @F1A*/
/* Handle types */
#define SQL_UNUSED 0
#define SQL_HANDLE_ENV 1
#define SQL_HANDLE_DBC 2
#define SQL_HANDLE_STMT 3
#define SQL_HANDLE_DESC 4
#define SQL_NULL_HANDLE 0
/*
* NULL status defines; these are used in SQLColAttributes, SQLDescribeCol,
* to describe the nullability of a column in a table.
*/
#define SQL_NO_NULLS 0
#define SQL_NULLABLE 1
#define SQL_NULLABLE_UNKNOWN 2
/* SQLColAttributes defines */
#define SQL_ATTR_READONLY 0
#define SQL_ATTR_WRITE 1
#define SQL_ATTR_READWRITE_UNKNOWN 2
/* End Options */
#define SQL_TXN_CLEAR 3 /* TMSUSPEND */
#define SQL_TXN_END 4 /* TMSUCCESS */
/* w/o HOLD */
#define SQL_TXN_HOLD 5 /* TMSUCCESS */
/* w/HOLD @D1A*/
#define SQL_TXN_END_FAIL 6 /* TMFAIL @D5A*/
/*
* Options for Rounding Modes. These numeric values can
* be set with SQLSetConnectAttr() API for the attribute
* SQL_ATTR_DECFLOAT_ROUNDING_MODE. The SQLGetConnectAttr()
* API will return these values for the
* SQL_ATTR_DECFLOAT_ROUNDING_MODE attribute. @E2A*/
#define ROUND_HALF_EVEN 0 /* @E2A*/
#define ROUND_HALF_UP 1 /* @E2A*/
#define ROUND_DOWN 2 /* @E2A*/
#define ROUND_CEILING 3 /* @E2A*/
#define ROUND_FLOOR 4 /* @E2A*/
#define ROUND_HALF_DOWN 5 /* @E2A*/
#define ROUND_UP 6 /* @E2A*/
/* statement attributes */
#define SQL_ATTR_APP_ROW_DESC 10010
#define SQL_ATTR_APP_PARAM_DESC 10011
#define SQL_ATTR_IMP_ROW_DESC 10012
#define SQL_ATTR_IMP_PARAM_DESC 10013
#define SQL_ATTR_FOR_FETCH_ONLY 10014
#define SQL_ATTR_CONCURRENCY 10014
#define SQL_CONCURRENCY 10014
#define SQL_ATTR_CURSOR_SCROLLABLE 10015
#define SQL_ATTR_ROWSET_SIZE 10016
#define SQL_ROWSET_SIZE 10016
#define SQL_ATTR_ROW_ARRAY_SIZE 10016
#define SQL_ATTR_CURSOR_HOLD 10017
#define SQL_ATTR_FULL_OPEN 10018
#define SQL_ATTR_BIND_TYPE 10049
#define SQL_BIND_TYPE 10049
#define SQL_ATTR_CURSOR_TYPE 10050
#define SQL_CURSOR_TYPE 10050
#define SQL_ATTR_CURSOR_SENSITIVITY 10051 /* @D1A*/
#define SQL_CURSOR_SENSITIVE 10051 /* @D1A*/
#define SQL_ATTR_ROW_STATUS_PTR 10052 /* @D3A*/
#define SQL_ATTR_ROWS_FETCHED_PTR 10053 /* @D3A*/
#define SQL_ATTR_ROW_BIND_TYPE 10056 /* @E2A*/
#define SQL_ATTR_PARAM_BIND_TYPE 10057 /* @E2A*/
#define SQL_ATTR_PARAMSET_SIZE 10058 /* @E2A*/
#define SQL_ATTR_PARAM_STATUS_PTR 10059 /* @E2A*/
#define SQL_ATTR_PARAMS_PROCESSED_PTR 10060 /* @E2A*/
#define SQL_ATTR_NUMBER_RESULTSET_ROWS_PTR 10061 /* @E2A*/
/* SQLColAttributes defines */
#define SQL_DESC_COUNT 1
#define SQL_DESC_TYPE 2
#define SQL_DESC_LENGTH 3
#define SQL_DESC_LENGTH_PTR 4
#define SQL_DESC_PRECISION 5
#define SQL_DESC_SCALE 6
#define SQL_DESC_DATETIME_INTERVAL_CODE 7
#define SQL_DESC_NULLABLE 8
#define SQL_DESC_INDICATOR_PTR 9
#define SQL_DESC_DATA_PTR 10
#define SQL_DESC_NAME 11
#define SQL_DESC_UNNAMED 12
#define SQL_DESC_DISPLAY_SIZE 13
#define SQL_DESC_AUTO_INCREMENT 14
#define SQL_DESC_SEARCHABLE 15
#define SQL_DESC_UPDATABLE 16
#define SQL_DESC_BASE_COLUMN 17
#define SQL_DESC_BASE_TABLE 18
#define SQL_DESC_BASE_SCHEMA 19
#define SQL_DESC_LABEL 20
#define SQL_DESC_MONEY 21
#define SQL_DESC_TYPE_NAME 23 /* @D3A*/
#define SQL_DESC_ALLOC_TYPE 99
#define SQL_DESC_ALLOC_AUTO 1
#define SQL_DESC_ALLOC_USER 2
#define SQL_COLUMN_COUNT 1
#define SQL_COLUMN_TYPE 2
#define SQL_COLUMN_LENGTH 3
#define SQL_COLUMN_LENGTH_PTR 4
#define SQL_COLUMN_PRECISION 5
#define SQL_COLUMN_SCALE 6
#define SQL_COLUMN_DATETIME_INTERVAL_CODE 7
#define SQL_COLUMN_NULLABLE 8
#define SQL_COLUMN_INDICATOR_PTR 9
#define SQL_COLUMN_DATA_PTR 10
#define SQL_COLUMN_NAME 11
#define SQL_COLUMN_UNNAMED 12
#define SQL_COLUMN_DISPLAY_SIZE 13
#define SQL_COLUMN_AUTO_INCREMENT 14
#define SQL_COLUMN_SEARCHABLE 15
#define SQL_COLUMN_UPDATABLE 16
#define SQL_COLUMN_BASE_COLUMN 17
#define SQL_COLUMN_BASE_TABLE 18
#define SQL_COLUMN_BASE_SCHEMA 19
#define SQL_COLUMN_LABEL 20
#define SQL_COLUMN_MONEY 21
#define SQL_COLUMN_ALLOC_TYPE 99
#define SQL_COLUMN_ALLOC_AUTO 1
#define SQL_COLUMN_ALLOC_USER 2
#define SQL_TXN_NO_COMMIT 1
#define SQL_TXN_NOCOMMIT 1
#define SQL_COMMIT_CHG 2
#define SQL_COMMIT_UR 2
#define SQL_TXN_READ_UNCOMMITTED 2
#define SQL_COMMIT_CS 3
#define SQL_TXN_READ_COMMITTED 3
#define SQL_COMMIT_ALL 4
#define SQL_COMMIT_RS 4
#define SQL_TXN_REPEATABLE_READ 4
#define SQL_COMMIT_RR 5
#define SQL_TXN_SERIALIZABLE 5
/*
* SQLColAttributes defines
* These are also used by SQLGetInfo
*/
#define SQL_UNSEARCHABLE 0
#define SQL_LIKE_ONLY 1
#define SQL_ALL_EXCEPT_LIKE 2
#define SQL_SEARCHABLE 3
/* unsupported APIs */
#define SQL_API_SQLSETPOS -1
#ifdef __64BIT__
#if !defined(SDWORD)
typedef int SDWORD;
#endif
#if !defined(UDWORD)
typedef unsigned int UDWORD;
#endif
#else
#if !defined(SDWORD)
typedef long int SDWORD;
#endif
#if !defined(UDWORD)
typedef unsigned long int UDWORD;
#endif
#endif
#if !defined(UWORD)
typedef unsigned short int UWORD;
#endif
#if !defined(SWORD)
typedef signed short int SWORD;
#endif
/* This should be temporary until math.h makes the typedef’s below permanent,
without the need of STDC_WANT_DEC_FP or IBM_DFP declaration. Without this
fix QCPIMPRT.c fails b/c it includes math.h w/out these declares
set. @E2A*/
#ifdef __64BIT__
typedef int SQLINTEGER;
typedef int HENV;
typedef int HDBC;
typedef int HSTMT;
typedef int HDESC;
typedef int SQLHANDLE;
#else
typedef long int SQLINTEGER;
typedef long HENV;
typedef long HDBC;
typedef long HSTMT;
typedef long HDESC;
typedef long SQLHANDLE;
#endif
/*
* DATE, TIME, and TIMESTAMP structures. These are for compatibility
SQLSMALLINT icol,
SQLCHAR *fName,
SQLSMALLINT *fNameLen,
SQLINTEGER *fOptions,
SQLSMALLINT fValueMax,
SQLINTEGER *sLen,
SQLINTEGER *pcbValue);
SQLHENV henv,
SQLSMALLINT ctype);
SQLWCHAR *szFkTableOwner,
SQLSMALLINT cbFkTableOwner,
SQLWCHAR *szFkTableName,
SQLSMALLINT cbFkTableName);
SQLSMALLINT rcdNum,
SQLSMALLINT fieldID,
SQLPOINTER fValue,
SQLINTEGER fLength,
SQLINTEGER *stLength);
SQLWCHAR *msgText,
SQLSMALLINT bLength,
SQLSMALLINT *SLength);
SQLINTEGER *pcrow);
SQLPOINTER pParam,
SQLINTEGER vParam);
SQLSMALLINT cbTableOwner,
SQLCHAR *szTableName,
SQLSMALLINT cbTableName);
#define FAR
#define SQL_SQLSTATE_SIZE 5 /* size of SQLSTATE, not including
null terminating byte */
#define SQL_MAX_DSN_LENGTH 18 /* maximum data source name size */
#define SQL_MAX_ID_LENGTH 18 /* maximum identifier name size,
e.g. cursor names */
#define SQL_MAXLSTR 255 /* Maximum length of an LSTRING */
#define SQL_LVCHAROH 26 /* Overhead for LONG VARCHAR in */
/* record */
#define SQL_LOBCHAROH 312 /* Overhead for LOB in record */
#ifndef __ILEC400__
#pragma info(restore)
#endif
#endif /* SQL_H_SQLCLI */
Without using SQL server mode, applications might encounter one or more of the following limitations:
v A single job can have only one commit transaction per activation group.
v A single job can be connected to a relational database (RDB) only once.
v All SQL statements run under the user profile of the job, regardless of the user ID passed on the
connection.
| SQL server mode circumvents these limitations by routing all SQL statements to separate jobs. Each
| connection runs in its own job. The system uses prestart jobs named QSQSRVR in the QSYSWRK
| subsystem or a selected subsystem to minimize the startup time for each connection. Because each call to
| SQLConnect() can accept a different user profile, each job also has its own commit transaction. As soon as
| the SQLDisconnect() has been performed, the job is reset and put back in the pool of available jobs.
EXAMPLE.
.
SQLAllocEnv(&henv);
long attr;
attr = SQL_TRUE
SQLSetEnvAttr(henv,SQL_ATTR_SERVER_MODE,&attr,0);
SQLAllocConnect(henv,&hdbc);
.
.
v The second way to set the server mode is using the Change Job (QWTCHGJB) API.
As soon as SQL server mode has been set, all SQL connections and SQL statements run in server mode.
There is no switching back and forth. The job, when in server mode, cannot start commitment control,
and cannot use Interactive SQL.
Related information:
Application programming interfaces
Related reference:
“SQLDataSources - Get list of data sources” on page 80
SQLDataSources() returns a list of target databases available, one at a time. A database must be cataloged
to be available.
This support is available for two different Unicode encodings, UTF-8 and UTF-16. Additional support
exists for specifying a UCS-2 encoded character string only when preparing an SQL statement.
Support for UTF-16 encoded character data is provided through a set of API's called the "Wide" API's.
These API's accept as input and return as output UTF-16 data. This allows applications to run with a
Unicode coded character set identifier (CCSID) of 1200, instead of being dependent upon the default
CCSID of the job running the DB2 for i CLI work. In most cases the default CCSID of the job is an
EBCDIC CCSID. Since the UTF-16 encoded character set is a superset of the UCS-2 encoded character set
(CCSID 13488), applications can encode their character data in UCS-2 as well. CLI API functions have
suffixes to indicate the format of their string arguments: those that accept Unicode end in W, and those
that accept EBCDIC have no suffix. The following is a list of functions that are available in DB2 for i CLI
which have both EBCDIC and Unicode versions:
Table 179. List of functions with both EBCIDIC and Unicode versions
SQLColAttributeW SQLColAttributesW SQLColumnPrivilegesW
SQLColumnsW SQLConnectW SQLDataSourcesW
SQLDescribeColW SQLDriverConnectW SQLErrorW
SQLExecDirectW SQLForeignKeysW SQLGetConnectAttrW
SQLGetConnectOptionW SQLGetCursorNameW SQLGetDescFieldW
SQLGetDescRecW SQLGetDiagFieldW SQLGetDiagRecW
SQLGetInfoW SQLGetPositionW SQLGetStmtAttrW
SQLGetStmtOptionW SQLGetSubStringW SQLGetTypeInfoW
SQLNativeSQLW SQLPrepareW SQLPrimaryKeysW
SQLProcedureColumnsW SQLProceduresW SQLSetConnectAttrW
SQLSetConnectOptionW SQLSetCursorNameW SQLSetDescFieldW
SQLSetStmtAttrW SQLSetStmtOptionW SQLSpecialColumnsW
SQLStatisticsW SQLTablePrivilegesW SQLTablesW
| The syntax for a DB2 for i CLI Wide function is the same as the syntax for its corresponding EBCDIC
| function, except that SQLCHAR parameters are defined as SQLWCHAR. Character buffers defined as
| SQLPOINTER in the EBCDIC syntax can be defined as either SQLCHAR or SQLWCHAR in the Unicode
| function. Refer to the EBCDIC version of the CLI Unicode functions for EBCDIC syntax details.
The SQL type's SQL_WCHAR and SQL_WVARCHAR can be used to specify a buffer that contains
Unicode data. So, to specify a particular column or parameter marker containing Unicode data the
application can bind as SQL_WCHAR for fixed length character data or bind as SQL_WVARCHAR for
varying length character data. Since UTF-16 data is double byte character data the input and output
lengths must take this into account. Unicode functions that have arguments which are always character
strings interpret these arguments as the number of double byte characters. When the length might refer
to string or non-string data, the length will be interpreted as the number of bytes needed to store the
data. For example, the SQLGetInfoW()SQLGetInfoW() API accepts the input length as the number of bytes,
while SQLPrepareW() accepts the number of double byte character's.
| DB2 for i CLI allows for the mixing of the Wide character API's and non-Wide character API's.
| Applications must take into account that Unicode data can only be specified for the Wide API calls, and
| not the non-Wide API calls. Most applications will probably want to commit to either running with
| Unicode encoding or will choose to run with a non-Unicode character encoding since most data will be in
| a consistent encoding. However, support does exist for mixing Unicode and non-Unicode calls in the
| same CLI environment. DB2 for i CLI does restrict the mixing of Wide character API's and an
| environment with UTF-8 support enabled. Enabling UTF-8 support is discussed in the next section.
| Support for UTF-8 encoded character data is provided through the setting of an environment or
| connection attribute, SQL_ATTR_UTF8. Setting the attribute to SQL_TRUE will indicate that all input and
| output data is to be treated as Unicode character data. This support allows applications to run with a
| Unicode coded character set identifier (CCSID) of 1208, instead of being dependent upon the default
| CCSID of the job running theDB2 for i CLI work. The UTF-8 support does not require any new data type
| bindings by the application. When binding, applications can continue to use SQL_CHAR for fixed length
| character data and SQL_VARCHAR can be used for varying length character data. When an application
| binds as any character SQL type, DB2 for i CLI will take care of tagging the data with the UTF-8 CCSID,
| so DB2 for i will translate the data properly. UTF-8 data is handled on every DB2 for i CLI API that takes
| character data as input and returns character data as output. Each of the API's which has a matching
| wide character version also supports UTF-8 character data. See the list of API's in the previous section to
| identify which functions support both UTF-16 and UTF-8 Unicode character data. Functions that accept
| both a UTF-8 string and a length expect the length to be in bytes, not in characters. This is in contrast to
| the Wide API's which expect the length to be in the number of double byte characters in most cases. As
| was discussed in the previous section, mixing a UTF-8 environment with calls to the Wide character API's
| is restricted. Additionally, unlike the Wide character API's, which allow alternating calls between Unicode
| and non-Unicode supported API's, once the UTF-8 environment is setup, all input and output character
| data is expected to be in the UTF-8 encoding by DB2 for i CLI.
| DB2 for i CLI provides some specific support for UCS-2 encoded character strings. This support was
| added before the Wide API support, and therefore is not a complete solution for applications wanting to
| enable full Unicode support in DB2 for i CLI. Since the UTF-16 encoded character set is a superset of the
| UCS-2 character set, applications can get full UCS-2 support through the use of the Wide API's discussed
| earlier in the "Unicode in DB2 for i CLI" section. To enable this limited UCS-2 support, set the connection
| attribute SQL_ATTR_UCS2 to SQL_TRUE. This will tell DB2 for i CLI to treat input strings as UCS-2
| character data at prepare time. SQL statements can be prepared using either the SQLPrepare() or
| SQLExecDirect() API's. This support does not allow for UCS-2 character strings on input or output for
| any other DB2 for i CLI API's.
Example: Embedded SQL and the equivalent DB2 for i CLI function
calls
| This example shows embedded statements in comments and the equivalent DB2 for i CLI function calls.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*************************************************************************
** file = embedded.c
**
** Example of executing an SQL statement using CLI.
** The equivalent embedded SQL statements are shown in comments.
**
** Functions used:
**
** SQLAllocConnect SQLFreeConnect
** SQLAllocEnv SQLFreeEnv
** SQLAllocStmt SQLFreeStmt
** SQLConnect SQLDisconnect
**
** SQLBindCol SQLFetch
** SQLSetParam SQLTransact
** SQLError SQLExecDirect
**
**************************************************************************/
#include <stdio.h>
#include <string.h>
#include "sqlcli.h"
#ifndef NULL
#define NULL 0
#endif
int main ()
{
SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstmt;
SQLINTEGER id;
SQLCHAR name[51];
SQLINTEGER namelen, intlen;
SQLSMALLINT scale;
scale = 0;
namelen = SQL_NTS;
/* Set up the second input parameter "name" */
SQLSetParam (hstmt, 2,
SQL_C_CHAR, SQL_VARCHAR,
50,
scale, (SQLPOINTER) name,
(SQLINTEGER *) &namelen);
/* EXEC SQL DECLARE c1 CURSOR FOR SELECT ID, NAME FROM NAMEID; */
/* EXEC SQL OPEN c1; */
/* The application doesn’t specify "declare c1 cursor for" */
{
SQLCHAR select[] = "select ID, NAME from NAMEID";
if (SQLExecDirect (hstmt, select, SQL_NTS) != SQL_SUCCESS)
return (print_err (hdbc, hstmt));
}
return (0);
}
return(SQL_ERROR);
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*************************************************************************
** file = CLIXAEXMP1.c
**
** Example of a typical flow of work in an XA transaction using the CLI.
**
** XA Functions used:
**
** xa_open() -- Open an XA resource for use in a transaction
** xa_prepare() -- Prepare for commitment of work in the transaction
** xa_commit() -- Commit work done in the transaction
**
** CLI Functions used:
**
** SQLAllocHanle SQLBindParameter SQLDisconnect
** SQLError SQLExecute SQLFreeHandle
** SQLPrepare SQLSetConnectAttr SQLSetEnvAttr
**
** This example will:
** - Open the XA transaction manager
** - Open a CLI connection and start a transaction for it using SQL_TXN_CREATE
** - Do some commitable CLI work under this transaction
** - End the transaction on the first connection using SQL_TXN_END
** - Close the first CLI connection and open a second connection
** - Use the SQL_TXN_FIND option to find the previous transaction
** - Do more commitable work on this transaction and end the transaction
** - Use the XA APIs to prepare and commit the work
************************************************************************************/
#define _XA_PROTOTYPES
#define _MULTI_THREADED
#include <xa.h>
#include <stdio.h>
#include <string.h>
#include <sqlcli.h>
#include <time.h>
#include <stdlib.h>
SQLCHAR s[80];
SQLCHAR state[10];
SQLCHAR buffer[600];
SQLCHAR sqlstr[600];
SQLINTEGER natErr;
SQLSMALLINT len;
rtnc=SQLSetConnectAttr(hdbc,SQL_ATTR_TXN_INFO,&new,0);
/* Commit */
if (xaRc != XA_RDONLY) {
xaRc = xa_commit(&xid, mainRmid, TMNOFLAGS);
printf("xa_commit(xid, %d, TMNOFLAGS) = %d\n", mainRmid, xaRc);
}
else {
printf("xa_commit() skipped for read only TX\n");
}
Example: Interactive SQL and the equivalent DB2 for i CLI function
calls
This example shows the processing of interactive SQL statements.
This example follows the flow described in “Writing a DB2 for i CLI application” on page 6.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 319.
/*************************************************************************
** file = typical.c
**
** Example of executing interactive SQL statements, displaying result sets
** and simple transaction management.
**
** Functions used:
**
** SQLAllocConnect SQLFreeConnect
** SQLAllocEnv SQLFreeEnv
** SQLAllocStmt SQLFreeStmt
** SQLConnect SQLDisconnect
**
** SQLBindCol SQLFetch
** SQLDescribeCol SQLNumResultCols
** SQLError SQLRowCount
** SQLExecDirect SQLTransact
**
**************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "sqlcli.h"
/*******************************************************************
** main
** - initialize
** - start a transaction
** - get statement
** - another statement?
** - COMMIT or ROLLBACK
** - another transaction?
** - terminate
*******************************************************************/
int main()
{
SQLHENV henv;
SQLHDBC hdbc;
SQLCHAR sqlstmt[MAX_STMT_LEN + 1]="";
SQLCHAR sqltrans[sizeof("ROLLBACK")];
SQLRETURN rc;
rc = initialize(&henv, &hdbc);
if (rc == SQL_ERROR) return(terminate(henv, hdbc));
if (sqltrans[0] == ’c’)
{
rc = SQLTransact (henv, hdbc, SQL_COMMIT);
if (rc == SQL_SUCCESS)
printf ("Transaction commit was successful\n");
else
check_error (henv, hdbc, SQL_NULL_HSTMT, rc);
}
if (sqltrans[0] == ’r’)
{
rc = SQLTransact (henv, hdbc, SQL_ROLLBACK);
if (rc == SQL_SUCCESS)
printf ("Transaction roll back was successful\n");
else
check_error (henv, hdbc, SQL_NULL_HSTMT, rc);
}
terminate(henv, hdbc);
return (SQL_SUCCESS);
}/* end main */
/*******************************************************************
** process_stmt
** - allocates a statement handle
** - executes the statement
** - determines the type of statement
** - if there are no result columns, therefore non-select statement
** - if rowcount > 0, assume statement was UPDATE, INSERT, DELETE
** else
return (0);
}/* end process_stmt */
/*******************************************************************
** initialize
** - allocate environment handle
** - allocate connection handle
** - prompt for server, user id, & password
** - connect to server
*******************************************************************/
SQLHDBC *hdbc)
{
SQLCHAR server[18],
uid[10],
pwd[10];
SQLRETURN rc;
if (uid[0] == ’\0’)
{ rc = SQLConnect (*hdbc, server, SQL_NTS, NULL, SQL_NTS, NULL, SQL_NTS);
if (rc != SQL_SUCCESS )
check_error (*henv, *hdbc, SQL_NULL_HSTMT, rc);
}
else
{ rc = SQLConnect (*hdbc, server, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);
if (rc != SQL_SUCCESS )
check_error (*henv, *hdbc, SQL_NULL_HSTMT, rc);
}
}/* end initialize */
/*******************************************************************
** terminate
** - disconnect
** - free connection handle
** - free environment handle
*******************************************************************/
int terminate(SQLHENV henv,
SQLHDBC hdbc)
{
SQLRETURN rc;
/*******************************************************************
** display_results - displays the selected character fields
**
** - for each column
** - get column name
** - bind column
** - display column headings
** - fetch each row
** - if value truncated, build error message
** - if column null, set value to "NULL"
** - display row
** - print truncation message
** - free local storage
**
*******************************************************************/
void display_results(SQLHSTMT hstmt,
SQLSMALLINT nresultcols)
{
SQLCHAR colname[32];
SQLSMALLINT coltype[MAXCOLS];
SQLSMALLINT colnamelen;
SQLSMALLINT nullable;
SQLINTEGER collen[MAXCOLS];
SQLSMALLINT scale;
SQLINTEGER outlen[MAXCOLS];
SQLCHAR * data[MAXCOLS];
SQLCHAR errmsg[256];
SQLRETURN rc;
SQLINTEGER i;
SQLINTEGER displaysize;
/*******************************************************************
** SUPPORT FUNCTIONS
** - print_error - call SQLError(), display SQLSTATE and message
** - check_error - call print_error
** - check severity of Return Code
** - rollback & exit if error, continue if warning
*******************************************************************/
/*******************************************************************/
int print_error (SQLHENV henv,
SQLHDBC hdbc,
SQLHSTMT hstmt)
{
SQLCHAR buffer[SQL_MAX_MESSAGE_LENGTH + 1];
SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1];
SQLINTEGER sqlcode;
SQLSMALLINT length;
/*******************************************************************/
int check_error (SQLHENV henv,
SQLHDBC hdbc,
SQLHSTMT hstmt,
SQLRETURN frc)
{
SQLRETURN rc;
switch (frc){
case SQL_SUCCESS : break;
case SQL_ERROR :
case SQL_INVALID_HANDLE:
printf("\n ** FATAL ERROR, Attempting to rollback transaction **\n");
rc = SQLTransact(henv, hdbc, SQL_ROLLBACK);
if (rc != SQL_SUCCESS)
printf("Rollback Failed, Exiting application\n");
else
printf("Rollback Successful, Exiting application\n");
terminate(henv, hdbc);
exit(frc);
break;
case SQL_SUCCESS_WITH_INFO :
printf("\n ** Warning Message, application continuing\n");
break;
case SQL_NO_DATA_FOUND :
printf("\n ** No Data Found ** \n");
break;
default :
printf("\n ** Invalid Return Code ** \n");
IBM may not offer the products, services, or features discussed in this document in other countries.
Consult your local IBM representative for information on the products and services currently available in
your area. Any reference to an IBM product, program, or service is not intended to state or imply that
only that IBM product, program, or service may be used. Any functionally equivalent product, program,
or service that does not infringe any IBM intellectual property right may be used instead. However, it is
the user's responsibility to evaluate and verify the operation of any non-IBM product, program, or
service.
IBM may have patents or pending patent applications covering subject matter described in this
document. The furnishing of this document does not grant 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 or send inquiries, in writing, to:
Intellectual Property Licensing
Legal and Intellectual Property Law
IBM Japan, Ltd.
3-2-12, Roppongi, Minato-ku, Tokyo 106-8711
The following paragraph does not apply to the United Kingdom or any other country where such
provisions are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION
PROVIDES THIS PUBLICATION “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Some
states do not allow disclaimer of express or implied warranties in certain transactions, therefore, this
statement may not apply to you.
This information could include technical inaccuracies or typographical errors. Changes are periodically
made to the information herein; these changes will be incorporated in new editions of the publication.
IBM may make improvements and/or changes in the product(s) and/or the program(s) described in this
publication at any time without notice.
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.
Licensees of this program who wish to have information about it for the purpose of enabling: (i) the
exchange of information between independently created programs and other programs (including this
one) and (ii) the mutual use of the information which has been exchanged, should contact:
IBM Corporation
Such information may be available, subject to appropriate terms and conditions, including in some cases,
payment of a fee.
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,
IBM License Agreement for Machine Code, or any equivalent agreement between us.
Any performance data contained herein was determined in a controlled environment. Therefore, the
results obtained in other operating environments may vary significantly. Some measurements may have
been made on development-level systems and there is no guarantee that these measurements will be the
same on generally available systems. Furthermore, some measurements may have been estimated through
extrapolation. Actual results may vary. Users of this document should verify the applicable data for their
specific environment.
Information concerning non-IBM products was obtained from the suppliers of those products, their
published announcements or other publicly available sources. IBM has not tested those products and
cannot confirm the accuracy of performance, compatibility or any other claims related to non-IBM
products. Questions on the capabilities of non-IBM products should be addressed to the suppliers of
those products.
All statements regarding IBM's future direction or intent are subject to change or withdrawal without
notice, and represent goals and objectives only.
All IBM prices shown are IBM's suggested retail prices, are current and are subject to change without
notice. Dealer prices may vary.
This information is for planning purposes only. The information herein is subject to change before the
products described become available.
This information contains 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:
This information contains sample application programs in source language, which illustrate programming
techniques on various operating platforms. You may copy, modify, and distribute these sample programs
in any form without payment to IBM, for the purposes of developing, using, marketing or distributing
application programs conforming to the application programming interface for the operating platform for
which the sample programs are written. These examples have not been thoroughly tested under all
conditions. IBM, therefore, cannot guarantee or imply reliability, serviceability, or function of these
programs. The sample programs are provided "AS IS", without warranty of any kind. IBM shall not be
liable for any damages arising out of your use of the sample programs.
Each copy or any portion of these sample programs or any derivative work, must include a copyright
notice as follows:
© (your company name) (year). Portions of this code are derived from IBM Corp. Sample Programs. ©
Copyright IBM Corp. _enter the year or years_.
Trademarks
IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of International Business
Machines Corp., registered in many jurisdictions worldwide. Other product and service names might be
trademarks of IBM or other companies. A current list of IBM trademarks is available on the Web at
Copyright and trademark information at www.ibm.com/legal/copytrade.shtml.
Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered trademarks or trademarks
of Adobe Systems Incorporated in the United States, and/or other countries.
Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the
United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other countries.
Other company, product, or service names may be trademarks or service marks of others.
Personal Use: You may reproduce these publications for your personal, noncommercial use provided that
all proprietary notices are preserved. You may not distribute, display or make derivative works 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.
Except as expressly granted in this permission, no other permissions, licenses or rights are granted, either
express or implied, to the publications or any information, data, software or other intellectual property
contained therein.
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.
Index 327
328 IBM i: Database SQL call level interface
Printed in USA