Db2 Dev Embed SQL 115
Db2 Dev Embed SQL 115
IBM
Notices
This information was developed for products and services offered in the US. This material might be
available from IBM in other languages. However, you may be required to own a copy of the product or
product version in that language in order to access it.
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:
For license inquiries regarding double-byte character set (DBCS) information, contact the IBM Intellectual
Property Department in your country or send inquiries, in writing, to:
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.
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.
Java and all Java-based trademarks and logos are trademarks or registered trademarks of Oracle and/or
its affiliates.
Applicability
These terms and conditions are in addition to any terms of use for the IBM website.
ii Notices
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 work of these publications, or
any portion thereof, without the express consent of IBM.
Commercial use
You may reproduce, distribute and display these publications solely within your enterprise provided
that all proprietary notices are preserved. You may not make derivative works of these publications, or
reproduce, distribute or display these publications or any portion thereof outside your enterprise, without
the express consent of IBM.
Rights
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.
IBM MAKES NO GUARANTEE ABOUT THE CONTENT OF THESE PUBLICATIONS. THE PUBLICATIONS
ARE PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT,
AND FITNESS FOR A PARTICULAR PURPOSE.
Notices iii
iv IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Contents
Notices...................................................................................................................i
Trademarks...................................................................................................................................................ii
Terms and conditions for product documentation...................................................................................... ii
Figures................................................................................................................. ix
Tables.................................................................................................................. xi
Chapter 2. Designing............................................................................................. 9
Authorization considerations.......................................................................................................................9
Static and dynamic SQL statement execution in embedded SQL applications....................................... 10
Embedded SQL dynamic statements...................................................................................................10
Determining when to execute SQL statements statically or dynamically in embedded SQL
applications..................................................................................................................................... 11
Performance...............................................................................................................................................13
32-bit and 64-bit support..........................................................................................................................13
Restrictions................................................................................................................................................ 14
Restrictions on using C and C++.......................................................................................................... 14
Restrictions on using COBOL............................................................................................................... 15
Restrictions on using FORTRAN...........................................................................................................15
Restrictions on using REXX.................................................................................................................. 15
Recommendations for developing embedded SQL applications with XML and XQuery.................... 16
Concurrent transactions and multi-threaded database access............................................................... 16
Recommendations for using multiple threads.................................................................................... 18
Code page and country or region code considerations for multi-threaded UNIX applications......... 19
Troubleshooting multi-threaded applications.....................................................................................19
Chapter 3. Programming...................................................................................... 21
Source files.................................................................................................................................................21
Application template in C.......................................................................................................................... 22
Include files and definitions...................................................................................................................... 24
Include files for C and C++...................................................................................................................24
Include files for COBOL........................................................................................................................ 26
Include files for FORTRAN................................................................................................................... 28
Declaring the SQLCA for error handling.................................................................................................... 30
Connecting to Db2 databases................................................................................................................... 31
Data types that map to SQL data types.....................................................................................................32
Supported SQL data types in C and C++..............................................................................................33
Supported SQL data types in COBOL................................................................................................... 41
Supported SQL data types in FORTRAN.............................................................................................. 45
v
Supported SQL data types in REXX......................................................................................................47
Host variables............................................................................................................................................ 49
Declaring host variables....................................................................................................................... 50
Declaring host variables with the db2dclgn declaration generator.................................................... 51
Column data types and host variables.................................................................................................52
Declaring XML host variables............................................................................................................... 52
Identifying XML values in an SQLDA.................................................................................................... 53
Identifying null SQL values with null indicator variables.................................................................... 54
Including SQLSTATE and SQLCODE host variables............................................................................. 55
Referencing host variables...................................................................................................................56
Example: Referencing XML host variables...........................................................................................57
Host variables in C and C++................................................................................................................. 58
Host variables in COBOL...................................................................................................................... 88
Host variables in FORTRAN..................................................................................................................99
Host variables in REXX....................................................................................................................... 105
Considerations for using buffered inserts...............................................................................................110
Buffered inserts in partitioned database environments................................................................... 112
Restrictions on using buffered inserts...............................................................................................114
Executing XQuery expressions................................................................................................................ 114
Executing SQL statements...................................................................................................................... 116
Comments.......................................................................................................................................... 116
Executing static SQL statements....................................................................................................... 117
Retrieving host variable information from the SQLDA structure...................................................... 117
Providing variable input to dynamically executed SQL statements by using parameter markers.. 127
Calling procedures............................................................................................................................. 128
Reading and scrolling through results............................................................................................... 130
Error message retrieval......................................................................................................................134
Disconnecting.....................................................................................................................................137
Embedded SQL/COBOL Support for MRI and MRF........................................................................... 138
vi
Building embedded SQL applications in C or C++ (Windows).......................................................... 187
Index................................................................................................................ 205
vii
viii
Figures
1. Syntax Diagram........................................................................................................................................... 72
ix
x
Tables
18. How DYNAMICRULES and the Runtime Environment Determine Dynamic SQL Statement Behavior.152
xi
24. Settings to control automatic client reroute behavior........................................................................... 189
xii
Chapter 1. Introduction to embedded SQL
Embedded SQL applications connect to databases and execute embedded SQL statements. The
embedded SQL statements are contained in a package that must be bound to the target database server.
You can develop embedded SQL applications for the Db2® database in the following host programming
languages: C, C++, and COBOL.
Building embedded SQL applications involves two prerequisite steps before application compilation and
linking.
• Preparing the source files containing embedded SQL statements using the Db2 precompiler.
The PREP (PRECOMPILE) command is used to invoke the Db2 precompiler, which reads your source
code, parses and converts the embedded SQL statements to Db2 run-time services API calls, and finally
writes the output to a new modified source file. The precompiler produces access plans for the SQL
statements, which are stored together as a package within the database.
• Binding the statements in the application to the target database.
Binding is done by default during precompilation (the PREP command). If binding is to be deferred (for
example, running the BIND command later), then the BINDFILE option needs to be specified at PREP
time in order for a bind file to be generated.
Once you have precompiled and bound your embedded SQL application, it is ready to be compiled and
linked using the host language-specific development tools.
To aid in the development of embedded SQL applications, you can refer to the embedded SQL template
in C. Examples of working embedded SQL sample applications can also be found in the %DB2PATH%
\SQLLIB\samples directory.
Note: %DB2PATH% refers to the Db2 installation directory
The following example demonstrates how to issue an SQL statement dynamically using the host variable
stmt1:
The following guidelines and rules apply to the execution of embedded SQL statements in C and C++
applications:
• You can begin the SQL statement string on the same line as the EXEC SQL statement initializer.
• Do not split the EXEC SQL between lines.
• You must use the SQL statement terminator. If you do not use it, the precompiler will continue to the
next terminator in the application. This can cause indeterminate errors.
• C and C++ comments can be placed before the statement initializer or after the statement terminator.
• Multiple SQL statements and C or C++ statements may be placed on the same line. For example:
EXEC SQL OPEN c1; if (SQLCODE >= 0) EXEC SQL FETCH c1 INTO :hv;
• Carriage returns, line feeds, and TABs can be included within quoted strings. The SQL precompiler will
leave these as is.
• Do not use the #include statement to include files containing SQL statements. SQL statements are
precompiled before the module is compiled. The precompiler will ignore the #include statement.
Instead, use the SQL INCLUDE statement to import the include files.
2 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
• SQL comments are allowed on any line that is part of an embedded SQL statement, with the exception
of dynamically issued statements.
– The format for an SQL comment is a double dash (--), followed by a string of zero or more characters,
and terminated by a line end.
– Do not place SQL comments after the SQL statement terminator. These SQL comments cause
compilation errors because compilers interpret them as C or C++ syntax.
– You can use SQL comments in a static statement string wherever blanks are allowed.
– The use of C and C++ comment delimiters /* */ are allowed in both static and dynamic embedded
SQL statements.
– The use of //-style C++ comments are not permitted within static SQL statements
• SQL string literals and delimited identifiers can be continued over line breaks in C and C++ applications.
To do this, use a back slash (\) at the end of the line where the break is desired. For example, to select
data from the NAME column in the staff table where the NAME column equals 'Sanders' you could do
something similar to the following sample code:
Any new line characters (such as carriage return and line feed) are not included in the string that is
passed to the database manager as an SQL statement.
• Substitution of white space characters, such as end-of-line and TAB characters, occurs as follows:
– When they occur outside quotation marks (but inside SQL statements), end-of-lines and TABs are
substituted by a single space.
– When they occur inside quotation marks, the end-of-line characters disappear, provided the string is
continued properly for a C program. TABs are not modified.
Note that the actual characters used for end-of-line and TAB vary from platform to platform. For
example, UNIX and Linux® based systems use a line feed.
4 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
• Executable SQL statements must be placed in the PROCEDURE DIVISION section. The SQL statements
can be preceded by a paragraph name, just as a COBOL statement.
• SQL statements can begin in either Area A (columns 8 through 11) or Area B (columns 12 through
72).
• Start each SQL statement with the statement initializer EXEC SQL and end it with the statement
terminator END-EXEC. The SQL precompiler includes each SQL statement as a comment in the modified
source file.
• You must use the SQL statement terminator. If you do not use it, the precompiler will continue to the
next terminator in the application. This may cause indeterminate errors.
• SQL comments are allowed on any line that is part of an embedded SQL statement. These comments
are not allowed in dynamically executed statements. The format for an SQL comment is a double dash
(--), followed by a string of zero or more characters and terminated by a line end. Do not place SQL
comments after the SQL statement terminator as they will cause compilation errors because they seem
to be part of the COBOL language.
• COBOL comments are allowed in most places. The exceptions are:
– Comments are not allowed between EXEC and SQL.
– Comments are not allowed in dynamically executed statements.
• SQL statements follow the same line continuation rules as the COBOL language. However, do not split
the EXEC SQL statement initializer between lines.
• Do not use the COBOL COPY statement to include files containing SQL statements. SQL statements are
precompiled before the module is compiled. The precompiler will ignore the COBOL COPY statement.
Instead, use the SQL INCLUDE statement to import the include files.
• To continue a string constant to the next line, column 7 of the continuing line must contain a '-' and
column 12 or beyond must contain a string delimiter.
• SQL arithmetic operators must be delimited by blanks.
• Substitution of white space characters, such as end-of-line and TAB characters, occurs as follows:
– When they occur outside quotation marks (but inside SQL statements), end-of-lines and TABs are
substituted by a single space.
– When they occur inside quotation marks, the end-of-line characters disappear, provided the string is
continued properly for a COBOL program. TABs are not modified.
Note that the actual characters used for end-of-line and TAB vary from platform to platform. For
example, Windows-based platforms use Carriage Return/Line Feed for end-of-line, whereas UNIX and
Linux based systems use just a Line Feed.
SQL statements can be continued onto more than one line. Each part of the statement should be enclosed
in single quotation marks, and a comma must delimit additional statement text as follows:
In this example, the SQLCODE field of the SQLCA structure is checked to determine whether the update
was successful.
The following rules apply to embedded SQL statements: in REXX applications
• The following SQL statements can be passed directly to the SQLEXEC routine:
– CALL
– CLOSE
– COMMIT
– CONNECT
– CONNECT TO
– CONNECT RESET
– DECLARE
– DESCRIBE
– DISCONNECT
– EXECUTE
– EXECUTE IMMEDIATE
– FETCH
– FREE LOCATOR
– OPEN
– PREPARE
– RELEASE
– ROLLBACK
– SET CONNECTION
Other SQL statements must be processed dynamically using the EXECUTE IMMEDIATE, or PREPARE and
EXECUTE statements in conjunction with the SQLEXEC routine.
• You cannot use host variables in the CONNECT and SET CONNECTION statements in REXX.
• Cursor names and statement names are predefined as follows:
6 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
c1 to c100
Cursor names, which range from c1 to c50 for cursors declared without the WITH HOLD option, and
c51 to c100 for cursors declared using the WITH HOLD option.
The cursor name identifier is used for DECLARE, OPEN, FETCH, and CLOSE statements. It identifies
the cursor used in the SQL request.
s1 to s100
Statement names, which range from s1 to s100.
The statement name identifier is used with the DECLARE, DESCRIBE, PREPARE, and EXECUTE
statements.
The pre-declared identifiers must be used for cursor and statement names. Other names are not
allowed.
• When declaring cursors, the cursor name and the statement name should correspond in the DECLARE
statement. For example, if c1 is used as a cursor name, s1 must be used for the statement name.
• Do not use comments within an SQL statement.
Note: REXX does not support multi-threaded database access.
8 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Chapter 2. Designing embedded SQL applications
When designing embedded SQL applications you must use static or dynamic executed SQL statements.
There are two types of static SQL statements: statements that contain no host variables (used mainly for
initialization and simple SQL examples), and statements that make use of host variables. Dynamic SQL
statements also come in two flavors: they can either contain no parameter markers (typical of interfaces
such as CLP) or contain parameter markers, which allows for greater flexibility within applications.
The choice of whether to use statically or dynamically executed statements depend on a number of
factors, including: portability, performance and restrictions of embedded SQL applications.
/* select values from table into host variables using STATIC SQL and print them*/
EXEC SQL SELECT id, name, dept, salary INTO :id, :name, :dept, :salary
FROM staff WHERE id = 310;
PREPARE
Turns the character string form of the SQL statement into an executable form of the statement,
assigns a statement name, and optionally places information about the statement in an SQLDA
structure.
10 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
EXECUTE
Executes a previously prepared SQL statement. The statement can be executed repeatedly within a
connection.
DESCRIBE
Places information about a prepared statement into an SQLDA.
For example consider the following statement in C;
Note: The content of dynamic SQL statements follows the same syntax as static SQL statements, with the
following exceptions:
• The statement cannot begin with EXEC SQL.
• The statement cannot end with the statement terminator. An exception to this is the CREATE TRIGGER
statement which can contain a semicolon (;).
Nature of Query
• Random • Dynamic
• Permanent • Either
12 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
This is typical of interfaces such as the CLP, which is often used for executing on-demand queries.
From the CLP, SQL statements can only be issued dynamically.
4. Dynamic SQL containing parameter markers
The key benefit of dynamic SQL statements is that the presence of parameter markers allows the cost
of the statement preparation to be amortized over the repeated executions of the statement, typically
a select, or insert. This amortization is true for all repetitive dynamic SQL applications. Unfortunately,
just like static SQL with host variables, parts of the Db2 optimizer will not work because complete
information is unavailable.
14 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
??/
Back slash '\'
??'
Caret '^'
??!
Vertical Bar '|'
??-
Tilde '~'
16 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
For each executable SQL statement in a context, the first run-time services call always tries to obtain a
latch. If it is successful, it continues processing. If not (because an SQL statement in another thread of the
same context already has the latch), the call is blocked on a signaling semaphore until that semaphore
is posted, at which point the call gets the latch and continues processing. The latch is held until the SQL
statement has completed processing, at which time it is released by the last run-time services call that
was generated for that particular SQL statement.
The net result is that each SQL statement within a context is executed as an atomic unit, even though
other threads may also be trying to execute SQL statements at the same time. This action ensures that
internal data structures are not altered by different threads at the same time. APIs also use the latch used
by run-time services; therefore, APIs have the same restrictions as run-time services routines within each
context.
Contexts may be exchanged between threads in a process, but not exchanged between processes. One
use of multiple contexts is to provide support for concurrent transactions.
In the default implementation of threaded applications against a Db2 database, serialization of access to
the database is enforced by the database APIs. If one thread performs a database call, calls made by
other threads will be blocked until the first call completes, even if the subsequent calls access database
objects that are unrelated to the first call. In addition, all threads within a process share a commit scope.
True concurrent access to a database can only be achieved through separate processes, or by using the
APIs that are described in this topic.
Db2 database systems provide APIs that can be used to allocate and manipulate separate environments
(contexts) for the use of database APIs and embedded SQL. Each context is a separate entity, and any
connection or attachment using one context is independent of all other contexts (and thus all other
connections or attachments within a process). In order for work to be done on a context, it must first be
associated with a thread. A thread must always have a context when making database API calls or when
using embedded SQL.
All Db2 database system applications are multithreaded by default, and are capable of using multiple
contexts. You can use the following Db2 APIs to use multiple contexts. Specifically, your application can
create a context for a thread, attach to or detach from a separate context for each thread, and pass
contexts between threads. If your application does not call any of these APIs, Db2 will automatically
manage the multiple contexts for your application:
• sqleAttachToCtx - Attach to context
• sqleBeginCtx - Create and attach to an application context
• sqleDetachFromCtx - Detach from context
• sqleEndCtx - Detach and destory application context
• sqleGetCurrentCtx - Get current context
• sqleInterruptCtx - Interrupt context
These APIs have no effect (that is, they are no-ops) on platforms that do not support application
threading.
Contexts need not be associated with a given thread for the duration of a connection or attachment.
One thread can attach to a context, connect to a database, detach from the context, and then a second
thread can attach to the context and continue doing work using the already existing database connection.
Contexts can be passed around among threads in a process, but not among processes.
Even if the new APIs are used, the following APIs continue to be serialized:
• sqlabndx - Bind
• sqlaprep - Precompile Program
• sqluexpr - Export
• db2Import and sqluimpr - Import
Note:
export EXTSHM=ON
export EXTSHM=ON
db2set DB2ENVLIST=EXTSHM
db2start
On partitioned database environment, also add the following lines to your userprofile or
usercshrc files:
EXTSHM=ON
export EXTSHM
An alternative is to move the local database or Db2 Connect into another machine and to access it
remotely, or to access the local database or the Db2 Connect database with TCP/IP loop-back by
cataloging it as a remote node that has the TCP/IP address of the local machine.
18 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Code page and country or region code considerations for multi-threaded
UNIX applications
Code page and country or region codes are specific to C and C++ embedded SQL applications. On AIX the
functions that are used for runtime querying of the code page and country or region code that you use for
a database connection are now thread safe.
However, these functions can create some lock contention (and resulting performance degradation) in a
multi-threaded application that uses a large number of concurrent database connections.
You can use the DB2_FORCE_NLS_CACHE environment variable to eliminate the chance of lock contention
in multi-threaded applications. When DB2_FORCE_NLS_CACHE is set to TRUE, the code page and country
or region code information is saved the first time a thread accesses it. From that point on, the cached
information will be used for any other thread that requests this information. By saving this information,
lock contention is eliminated, and in certain situations a performance benefit will be realized.
You should not set DB2_FORCE_NLS_CACHE to TRUE if the application changes locale settings between
connections. If this situation occurs, the original locale information will be returned even after the locale
settings have been changed. In general, multi-threaded applications will not change locale settings,
which, ensures that the application remains thread safe.
context 1
SELECT * FROM TAB1 FOR UPDATE....
UPDATE TAB1 SET....
get semaphore
access data structure
release semaphore
COMMIT
context 2
get semaphore
access data structure
SELECT * FROM TAB1...
release semaphore
COMMIT
20 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Chapter 3. Programming embedded SQL applications
Programming embedded SQL applications involves the same steps required to assemble an application in
your host programming language.
Once you determine that embedded SQL is the appropriate API to meet your programming needs,
and after you design your embedded SQL application, you will be ready to program an embedded SQL
application.
Prerequisites:
• Choose whether to use static or dynamic SQL statements
• Design of an embedded SQL application
Programming embedded SQL applications consists of the following sub-tasks:
• Including the required header files
• Choosing a supported embedded SQL programming language
• Declaring host variables for representing values to be included in SQL statements
• Connecting to a data source
• Executing SQL statements
• Handling SQL errors and warnings related to SQL statement execution
• Disconnecting from the data source
Once you have a complete embedded SQL application you'll be ready to compile and run your application:
Building embedded SQL applications.
22 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
double salary;
char hostVarStmtDyn[50];
EXEC SQL END DECLARE SECTION;
int main()
{
int rc = 0; 3
EXEC SQL INCLUDE SQLCA; 4
/* execute an SQL statement (a query) using static SQL; copy the single row
of result values into host variables*/
EXEC SQL SELECT id, name, dept, salary 7
INTO :id, :name, :dept, :salary
FROM staff WHERE id = 310;
if (SQLCODE <0) 6
{
printf("Select Error: SQLCODE = %d. \n", SQLCODE);
}
else
{
/* print the host variable values to standard output */
printf("\n Executing a static SQL query statement, searching for
\n the id value equal to 310\n");
printf("\nID Name DEPT Salary\n");
printf(" %d %s %d %f\n",
id, name, dept, salary);
}
Note Description
1 Include files: This directive includes a file into your source application.
2 Declaration section: Declaration of host variables that will be used to hold values
referenced in the SQL statements of the C application.
3 Local variable declaration: This block declares the local variables to be used in the
application. These are not host variables.
4 Including the SQLCA structure: The SQLCA structure is updated after the execution of each
SQL statement. This template application uses certain SQLCA fields for error handling.
5 Connection to a database: The initial step in working with the database is to establish a
connection to the database. Here, a connection is made by executing the CONNECT SQL
statement.
6 Error handling: Checks to see if an error occurred.
7 Executing a query: The execution of this SQL statement assigns data returned from a table
to host variables. The C code used after the SQL statement execution prints the values in
the host variables to standard output.
8 Executing an operation: The execution of this SQL statement updates a set of rows in a
table identified by their department number. Preparation (EXEC SQL PREPARE StmtDyn
FROM :hostVarStmtDyn;) is a step in which host variable values, such as the one
referenced in this statement, are bound to the SQL statement to be executed.
9 Executing an operation: In this line and the previous line, this application uses cursors in
static SQL to select information in a table and print the data. After the cursor is declared
and opened, the data is fetched, and finally the cursor is closed.
10 Commit the transaction: The COMMIT statement finalizes the database changes that were
made within a unit of work.
11 And finally, the database connection must be dropped.
24 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
current directory first, then the directories specified by the DB2INCLUDE environment variable. Consider
the following examples:
• EXEC SQL INCLUDE payroll;
If the file specified in the INCLUDE statement is not enclosed in quotation marks, as shown
previously, the C precompiler searches for payroll.sqc, then payroll.h, in each directory in which
it looks. On UNIX and Linux operating systems, the C++ precompiler searches for payroll.sqC,
then payroll.sqx, then payroll.hpp, then payroll.h in each directory it looks. On Windows-32
bit operating systems, the C++ precompiler searches for payroll.sqx, then payroll.hpp, then
payroll.h in each directory it looks.
• EXEC SQL INCLUDE 'pay/payroll.h';
If the file name is enclosed in quotation marks, as shown previously, no extension is added to the name.
If the file name in quotation marks does not contain an absolute path, then the contents of
DB2INCLUDE are used to search for the file, prepended to whatever path is specified in the
INCLUDE file name. For example, on UNIX and Linux operating systems, if DB2INCLUDE is set to '/
disk2:myfiles/c', the C or C++ precompiler searches for './pay/payroll.h', then '/disk2/pay/
payroll.h', and finally './myfiles/c/pay/payroll.h'. The path where the file is actually found is
displayed in the precompiler messages. On Windows operating systems, substitute back slashes (\) for
the forward slashes in the previous example.
Note that if the precompiler option COMPATIBILITY_MODE is set to ORA, you can use double quotation
marks to specify include file names, for example, EXEC SQL INCLUDE "abc.h";. The Db2 database
manager provides this feature to facilitate the migration of embedded SQL C applications from other
database systems.
Note: The setting of DB2INCLUDE is cached by the command line processor. To change the setting
of DB2INCLUDE after any CLP commands have been issued, enter the TERMINATE command, then
reconnect to the database and precompile.
To help relate compiler errors back to the original source, the precompiler generates #line macros in the
output file. This allows the compiler to report errors using the file name and line number of the source or
included source file, rather than the line number in the precompiled output source file.
However, if you specify the PREPROCESSOR option, all the #line macros generated by the precompiler
reference the preprocessed file from the external C preprocessor. Some debuggers and other tools that
relate source code to object code do not always work well with the #line macro. If the tool you want to
use behaves unexpectedly, use the NOLINEMACRO option (used with Db2 PREP) when precompiling. This
option prevents the #line macros from being generated.
The include files that are intended to be used in your applications are described in the following section.
SQLADEF (sqladef.h)
This file contains function prototypes used by precompiled C and C++ applications.
SQLCA (sqlca.h)
This file defines the SQL Communication Area (SQLCA) structure. The SQLCA contains variables
that are used by the database manager to provide an application with error information about the
execution of SQL statements and API calls.
SQLCODES (sqlcodes.h)
This file defines constants for the SQLCODE field of the SQLCA structure.
SQLDA (sqlda.h)
This file defines the SQL Descriptor Area (SQLDA) structure. The SQLDA is used to pass data between
an application and the database manager.
SQLEXT (sqlext.h)
This file contains the function prototypes and constants of those ODBC Level 1 and Level 2 APIs that
are not part of the X/Open Call Level Interface specification and is therefore used with the permission
of Microsoft Corporation.
$HOME/sqllib/include/cobol_a
To locate INCLUDE files, the Db2 COBOL precompiler searches the current directory first, then the
directories specified by the DB2INCLUDE environment variable. Consider the following examples:
• EXEC SQL INCLUDE payroll END-EXEC.
26 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
If the file specified in the INCLUDE statement is not enclosed in quotation marks, as shown previously,
the precompiler searches for payroll.sqb, then payroll.cpy, then payroll.cbl, in each directory
in which it looks.
• EXEC SQL INCLUDE 'pay/payroll.cbl' END-EXEC.
If the file name is enclosed in quotation marks, as shown previously, no extension is added to the name.
If the file name in quotation marks does not contain an absolute path, the contents of DB2INCLUDE
are used to search for the file, prepended to whatever path is specified in the INCLUDE file name.
For example, with Db2 database systems for AIX, if DB2INCLUDE is set to '/disk2:myfiles/cobol',
the precompiler searches for './pay/payroll.cbl', then '/disk2/pay/payroll.cbl', and finally
'./myfiles/cobol/pay/payroll.cbl'. The path where the file is actually found is displayed in the
precompiler messages. On Windows platforms, substitute back slashes (\) for the forward slashes in the
previously shown example.
Note: The setting of DB2INCLUDE is cached by the Db2 command line processor. To change the setting
of DB2INCLUDE after any CLP commands have been issued, enter the TERMINATE command, then
reconnect to the database and precompile.
The include files that are intended to be used in your applications are described here:
SQLCA (sqlca.cbl)
This file defines the SQL Communication Area (SQLCA) structure. The SQLCA contains variables
that are used by the database manager to provide an application with error information about the
execution of SQL statements and API calls.
SQLCA_92 (sqlca_92.cbl)
This file contains a FIPS SQL92 Entry Level compliant version of the SQL Communications Area
(SQLCA) structure. This file should be included in place of the sqlca.cbl file when writing Db2
applications that conform to the FIPS SQL92 Entry Level standard. The sqlca_92.cbl file is
automatically included by the Db2 precompiler when the LANGLEVEL precompiler option is set to
SQL92E.
SQLCODES (sqlcodes.cbl)
This file defines constants for the SQLCODE field of the SQLCA structure.
SQLDA (sqlda.cbl)
This file defines the SQL Descriptor Area (SQLDA) structure. The SQLDA is used to pass data between
an application and the database manager.
SQLEAU (sqleau.cbl)
This file contains constant and structure definitions required for the Db2 security audit APIs. If you
use these APIs, you need to include this file in your program. This file also contains constant and
keyword value definitions for fields in the audit trail record. These definitions can be used by external
or vendor audit trail extract programs.
SQLETSD (sqletsd.cbl)
This file defines the Table Space Descriptor structure, SQLETSDESC, which is passed to the Create
Database API, sqlgcrea.
SQLE819A (sqle819a.cbl)
If the code page of the database is 819 (ISO Latin-1), this sequence sorts character strings that are
not FOR BIT DATA according to the host CCSID 500 (EBCDIC International) binary collation. This file is
used by the CREATE DATABASE API.
SQLE819B (sqle819b.cbl)
If the code page of the database is 819 (ISO Latin-1), this sequence sorts character strings that are
not FOR BIT DATA according to the host CCSID 037 (EBCDIC US English) binary collation. This file is
used by the CREATE DATABASE API.
SQLE850A (sqle850a.cbl)
If the code page of the database is 850 (ASCII Latin-1), this sequence sorts character strings that are
not FOR BIT DATA according to the host CCSID 500 (EBCDIC International) binary collation. This file is
used by the CREATE DATABASE API.
28 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
found is displayed in the precompiler messages. On Windows operating systems, substitute back
slashes (\) for the forward slashes, and substitute 'for' for the 'f' extension in the previously shown
example.
Note: The setting of DB2INCLUDE is cached by the Db2 command line processor. To change the setting
of DB2INCLUDE after any CLP commands have been issued, enter the TERMINATE command, then
reconnect to the database and precompile.
32-bit FORTRAN header files required for Db2 database application development, previously found in
$INSTHOME/sqllib/include are now found in $INSTHOME/sqllib/include32.
In Version 8.1, these files were found in the $INSTDIR/sqllib/include directory which was a
symbolic link to one of the following directories: $DB2DIR/include or $DB2DIR/include64 depending
on whether or not it was a 32-bit instance or a 64-bit instance.
In Version 9.1, $DB2DIR/include will contain all the include files (32-bit and 64-bit), and $DB2DIR/
include32 will contain 32-bit FORTRAN files only and a README file to indicate that 32-bit include files
are the same as the 64-bit ones with the exception of FORTRAN.
The $DB2DIR/include32 directory will only exist on AIX, HP-PA, and HP-IPF.
You can use the following FORTRAN include files in your applications.
SQLCA (sqlca_cn.f, sqlca_cs.f)
This file defines the SQL Communication Area (SQLCA) structure. The SQLCA contains variables
that are used by the database manager to provide an application with error information about the
execution of SQL statements and API calls.
Two SQLCA files are provided for FORTRAN applications. The default, sqlca_cs.f, defines the
SQLCA structure in an IBM SQL compatible format. The sqlca_cn.f file, precompiled with the
SQLCA NONE option, defines the SQLCA structure for better performance.
SQLCA_92 (sqlca_92.f)
This file contains a FIPS SQL92 Entry Level compliant version of the SQL Communications Area
(SQLCA) structure. This file should be included in place of either the sqlca_cn.f or the sqlca_cs.f
files when writing Db2 applications that conform to the FIPS SQL92 Entry Level standard. The
sqlca_92.f file is automatically included by the Db2 precompiler when the LANGLEVEL precompiler
option is set to SQL92E.
SQLCODES (sqlcodes.f)
This file defines constants for the SQLCODE field of the SQLCA structure.
SQLDA (sqldact.f)
This file defines the SQL Descriptor Area (SQLDA) structure. The SQLDA is used to pass data between
an application and the database manager.
SQLEAU (sqleau.f)
This file contains constant and structure definitions required for the Db2 security audit APIs. If you
use these APIs, you need to include this file in your program. This file also contains constant and
keyword value definitions for fields in the audit trail record. These definitions can be used by external
or vendor audit trail extract programs.
SQLE819A (sqle819a.f)
If the code page of the database is 819 (ISO Latin-1), this sequence sorts character strings that are
not FOR BIT DATA according to the host CCSID 500 (EBCDIC International) binary collation. This file is
used by the CREATE DATABASE API.
SQLE819B (sqle819b.f)
If the code page of the database is 819 (ISO Latin-1), this sequence sorts character strings that are
not FOR BIT DATA according to the host CCSID 037 (EBCDIC US English) binary collation. This file is
used by the CREATE DATABASE API.
SQLE850A (sqle850a.f)
If the code page of the database is 850 (ASCII Latin-1), this sequence sorts character strings that are
not FOR BIT DATA according to the host CCSID 500 (EBCDIC International) binary collation. This file is
used by the CREATE DATABASE API.
#include "sqlca.h"
extern struct sqlca sqlca;
30 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Procedure
To declare the SQLCA, code the INCLUDE SQLCA statement in your program:
• For C or C++ applications use:
• For Java™ applications, you do not explicitly use the SQLCA. Instead, use the SQLException instance
methods to get the SQLSTATE and SQLCODE values.
• For COBOL applications use:
What to do next
If your application must be compliant with the ISO/ANS SQL92 or FIPS 127-2 standard, do not use the
statements previously shown or the INCLUDE SQLCA statement.
If you want to use a specific user id (herrick) and password (mypassword), use the following
statement:
Note that if the precompiler option COMPATIBILITY_MODE is set to ORA, the following additional syntax
for the CONNECT statement is supported. The Db2 database manager provides this feature to facilitate
the migration of embedded SQL C applications from other database systems.
Parameter Description
username Either a host variable or a string specifying the
database user name
If you want to use a specific user id (herrick) and password (mypassword), use the following
statement:
If you want to use a specific user id (herrick) and password (mypassword), use the following
statement:
If you want to use a specific user id (herrick) and password (mypassword), use the following
statement:
32 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Supported SQL data types in C and C++ embedded SQL applications
Certain predefined C and C++ data types correspond to Db2 database column types. You can declare only
these C and C++ data types as host variables.
The following tables show the C and C++ equivalent of each column type. When the precompiler finds a
host variable declaration, it determines the appropriate SQL type value. The database manager uses this
value to convert the data exchanged between the application and itself.
1<=n<=255
struct tag {
short int;
char[n]
}
32 673<=n<=32 700
34 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Table 2. SQL Data Types Mapped to C and C++ Declarations (continued)
SQL Column Type“1” on page 38 C and C++ Data Type SQL Column Type Description
Null-terminated character form Allow at least 11 characters to
DATE
accommodate the null-terminator
(384 or 385)
VARCHAR structured form Allow at least 10 characters
Null-terminated character form Allow at least 9 characters to
TIME
accommodate the null-terminator
(388 or 389)
VARCHAR structured form Allow at least 8 characters
Null-terminated character form Allow 20- 33 characters to accommodate
TIMESTAMP(p)
“4” on page 38(392 for the null-terminator
or 393)
VARCHAR structured form Allow 19-32 characters.
XML value
XML“8” on page 38 struct {
(988 or 989) sqluint32 length;
char data[n];
}
SQLUDF_CLOB
Binary data
BINARY unsigned char myBinField[n];
1<= n <=255
Varbinary data
VARBINARY struct
myVarBinField_t
{sqluint16 length;char data[n];}
myVarBinField;
The following data types are only available in the DBCS or EUC environment when precompiled with the
WCHARTYPE NOCONVERT option.
1<=n<=127
1<=n<=16 336
16 337<=n<=16 350
The following data types are only available in the DBCS or EUC environment when precompiled with the
WCHARTYPE CONVERT option.
1<=n<=16 336
36 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Table 4. SQL Data Types Mapped to C and C++ Declarations (continued)
SQL Column Type“1” on page 38 C and C++ Data Type SQL Column Type Description
Non null-terminated varying double-byte
LONG VARGRAPHIC8 struct tag {
character string with 2-byte string length
(472 or 473) short int;
indicator
wchar_t [n]
}
16 337<=n<=16 350
The following data types are only available in the DBCS or EUC environment.
Note:
1. The first number under SQL Column Type indicates that an indicator variable is not provided, and the
second number indicates that an indicator variable is provided. An indicator variable is needed to indicate
NULL values, or to hold the length of a truncated string. These are the values that will be displayed in the
SQLTYPE field of the SQLDA for these data types.
2. For platform compatibility, use sqlint32. On 64-bit UNIX and Linux operating systems, "long" is a 64 bit
integer. On 64-bit Windows operating systems and 32-bit UNIX and Linux operating systems "long" is a 32
bit integer.
3. For platform compatibility, use sqlint64. The Db2 database system sqlsystm.h header file has a type
definition for sqlint64 as "__int64" on the supported Windows operating systems when using the Microsoft
compiler, "long long" on 32-bit UNIX and Linux operating systems, and "long" on 64 bit UNIX and Linux
operating systems.
4. The character string can be from 19 - 32 bytes in length without a null terminator depending on the number
of fractional seconds specified. The fractional seconds of the TIMESTAMP data type can be optionally
specified with 0-12 digits of timestamp precision.
When a timestamp value is assigned to a timestamp variable with a different number of fractional seconds,
the value is either truncated or padded with 0's to match the format of the timestamp variable.
5. FLOAT(n) where 0 < n < 25 is a synonym for REAL. The difference between REAL and DOUBLE in the SQLDA
is the length value (4 or 8).
6. The following SQL types are synonyms for DOUBLE:
• FLOAT
• FLOAT(n) where 24 < n < 54 is a synonym for DOUBLE
• DOUBLE PRECISION
7. This is not a column type but a host variable type.
8. The SQL_TYP_XML/SQL_TYP_NXML value is returned by DESCRIBE requests only. It cannot be used directly
by the application to bind application resources to XML values.
9. The LONG VARCHAR and LONG VARGRAPHIC data types are deprecated and might be removed in a future
release. Choose the CLOB or DBCLOB data type instead.
The following items are additional rules for supported C and C++ data types:
• The data type char can be declared as char or unsigned char.
• The database manager processes null-terminated variable-length character string data type char[n]
(data type 460), as VARCHAR(m).
– If LANGLEVEL is SAA1, the host variable length m equals the character string length n in char[n] or
the number of bytes preceding the first null-terminator (\0), whichever is smaller.
– If LANGLEVEL is MIA, the host variable length m equals the number of bytes preceding the first
null-terminator (\0).
• The database manager processes null-terminated, variable-length graphic string data type,
wchar_t[n] or sqldbchar[n] (data type 400), as VARGRAPHIC(m).
– If LANGLEVEL is SAA1, the host variable length m equals the character string length n in
wchar_t[n] or sqldbchar[n], or the number of characters preceding the first graphic null-
terminator, whichever is smaller.
– If LANGLEVEL is MIA, the host variable length m equals the number of characters preceding the first
graphic null-terminator.
• Unsigned numeric data types are not supported.
38 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
• The C and C++ data type int is not allowed because its internal representation is machine dependent.
Data types for procedures, functions, and methods in C and C++ embedded
SQL applications
There is a mapping between C and C++ and Db2 data types. When you are writing your embedded SQL
application, you must be aware of this mapping to ensure that you do not have unexpected data type
conversions or data truncation.
The following table lists the supported mappings between SQL data types and C and C++ data types for
procedures, UDFs, and methods.
1<=n<=32 672
32 673<=n<=32 700
1<=n<=32 672
40 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Table 6. SQL Data Types Mapped to C and C++ Declarations (continued)
SQL Column Type“1” on page 41 C and C++ Data Type SQL Column Type Description
This descriptor type value (988/989) will
XML Not supported
be defined to be used in the SQLDA for
(988/989)
describe, and to indicate XML Data (in
its serialized form). Existing character and
binary types (including LOBs and LOB file
reference types) can also be used to fetch
and insert the data (dynamic SQL only)
Note: The following data types are only available in the DBCS or EUC environment when precompiled with
the WCHARTYPE NOCONVERT option.
16 337<=n<=16 350
Note:
1. The first number under SQL Column Type indicates that an indicator variable is not provided, and the
second number indicates that an indicator variable is provided. An indicator variable is needed to indicate
NULL values, or to hold the length of a truncated string. These are the values that will be displayed in the
SQLTYPE field of the SQLDA for these data types.
2. The LONG VARCHAR and LONG VARGRAPHIC data types are deprecated and might be removed in a future
release. Choose the CLOB or DBCLOB data type instead.
Variable-length
VARCHAR(n) 01 name.
character string
(448 or 449) 49 length PIC S9(4) COMP-5.
49 name PIC X(n).
1<=n<=32 672
Long variable-length
LONG VARCHAR6 01 name.
character string
(456 or 457) 49 length PIC S9(4) COMP-5.
49 data PIC X(n).
32 673<=n<=32 700
42 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Table 8. SQL Data Types Mapped to COBOL Declarations (continued)
SQL Column Type“1” on page COBOL Data Type SQL Column Type
44 Description
01 MY-CLOB-FILE USAGE IS SQL TYPE IS CLOB- Descriptor for file
CLOB file reference
FILE. containing CLOB data
variable“4” on page 44
(920 or 921)
The following data types are only available in the DBCS environment.
Note:
1. The first number under SQL Column Type indicates that an indicator variable is not provided, and the
second number indicates that an indicator variable is provided. An indicator variable is needed to indicate
NULL values, or to hold the length of a truncated string. These are the values that will be displayed in the
SQLTYPE field of the SQLDA for these data types.
2. FLOAT(n) where 0 < n < 25 is a synonym for REAL. The difference between REAL and DOUBLE in the SQLDA
is the length value (4 or 8).
3. The following SQL types are synonyms for DOUBLE:
• FLOAT
• FLOAT(n) where 24 < n < 54 is a synonym for DOUBLE.
• DOUBLE PRECISION
4. This is not a column type but a host variable type.
5. The SQL_TYP_XML/SQL_TYP_NXML value is returned by DESCRIBE requests only. It cannot be used directly
by the application to bind application resources to XML values.
6. The LONG VARCHAR and LONG VARGRAPHIC data types are deprecated and might be removed in a future
release. Choose the CLOB or DBCLOB data type instead.
44 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
– Values for n and m must be greater than or equal to 1.
– The value for n + m cannot exceed 31.
– The value for s equals the value for n.
– The value for p equals the value for n + m.
– The repetition factors (n) and (m) are optional. The following examples are all valid:
(920 or 921)
(960 or 961)
SQL TYPE IS BLOB_FILE Descriptor for the file containing BLOB data
BLOB file reference variable“4”
on page 46
(916 or 917)
Note:
1. The first number under SQL Column Type indicates that an indicator variable is not provided, and the
second number indicates that an indicator variable is provided. An indicator variable is needed to indicate
NULL values, or to hold the length of a truncated string. These are the values that will be displayed in the
SQLTYPE field of the SQLDA for these data types.
2. FLOAT(n) where 0 < n < 25 is a synonym for REAL. The difference between REAL and DOUBLE in the SQLDA
is the length value (4 or 8).
3. The following SQL types are synonyms for DOUBLE:
• FLOAT
• FLOAT(n) where 24 < n < 54 is a synonym for DOUBLE.
• DOUBLE PRECISION
4. This is not a column type but a host variable type.
5. The LONG VARCHAR data type is deprecated, not recommended, and might be removed in a future release.
Choose the CLOB data type instead.
46 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
The rule for supported FORTRAN data types is:
• You can define dynamic SQL statements longer than 254 characters by using VARCHAR, or CLOB host
variables.
CLOB locator variable“4” on DECLARE :var_name LANGUAGE TYPE Identifies CLOB entities residing on the
page 49 CLOB LOCATOR server
(964 or 965)
DECLARE :var_name LANGUAGE TYPE Descriptor for file containing CLOB data
CLOB file reference
CLOB FILE
variable“4” on page 49
(920 or 921)
DECLARE :var_name LANGUAGE TYPE Descriptor for the file containing BLOB
BLOB file reference
BLOB FILE data
variable“4” on page 49
(916 or 917)
The following data types are only available in the DBCS environment.
48 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Table 12. SQL Column Types Mapped to REXX Declarations (continued)
SQL Column Type“1” on page 49 REXX Data Type SQL Column Type Description
Equivalent to GRAPHIC(n) Large object variable-length graphic
DBCLOB(n)
string of length n, where n ranges
(412 or 413)
from 1 to 1 073 741 823
DECLARE :var_name LANGUAGE Identifies DBCLOB entities residing
DBCLOB locator variable“4” on page
49 TYPE DBCLOB LOCATOR on the server
(968 or 969)
Note:
1. The first number under Column Type indicates that an indicator variable is not provided, and the second
number indicates that an indicator variable is provided. An indicator variable is needed to indicate NULL
values, or to hold the length of a truncated string.
2. FLOAT(n) where 0 < n < 25 is a synonym for REAL. The difference between REAL and DOUBLE in the SQLDA
is the length value (4 or 8).
3. The following SQL types are synonyms for DOUBLE:
• FLOAT
• FLOAT(n) where 24 < n < 54 is a synonym for DOUBLE.
• DOUBLE PRECISION
4. This is not a column type but a host variable type.
5. The LONG VARCHAR and LONG VARGRAPHIC data types are deprecated, not recommended, and might be
removed in a future release. Use the CLOB or DBCLOB data type instead.
foo1(){
.
.
.
BEGIN SQL DECLARE SECTION;
int x;
END SQL DECLARE SECTION;
x=10;
.
.
.
}
foo2(){
.
.
.
y=x;
.
.
.
}
Depending on the language, this example will either fail to compile because variable x is not declared in
function foo2(), or the value of x is not set to 10 in foo2(). To avoid this problem, you must either
declare x as a global variable, or pass x as a parameter to function foo2() as follows:
foo1(){
.
.
.
BEGIN SQL DECLARE SECTION;
int x;
END SQL DECLARE SECTION;
x=10;
foo2(x);
.
.
.
}
foo2(int x){
.
.
.
y=x;
.
.
.
}
50 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Table 13. Host Variable Declarations by Host Language
Language Example Source Code
C and C++
EXEC SQL BEGIN DECLARE SECTION;
short dept=38, age=26;
double salary;
char CH;
char name1[9], NAME2[9];
short nul_ind;
EXEC SQL END DECLARE SECTION;
COBOL
EXEC SQL BEGIN DECLARE SECTION END-EXEC.
01 age PIC S9(4) COMP-5 VALUE 26.
01 DEPT PIC S9(9) COMP-5 VALUE 38.
01 salary PIC S9(6)V9(3) COMP-3.
01 CH PIC X(1).
01 name1 PIC X(8).
01 NAME2 PIC X(8).
01 nul-ind PIC S9(4) COMP-5.
EXEC SQL END DECLARE SECTION END-EXEC.
FORTRAN
EXEC SQL BEGIN DECLARE SECTION
integer*2 age /26/
integer*4 dept /38/
real*8 salary
character ch
character*8 name1,NAME2
integer*2 nul_ind
EXEC SQL END DECLARE SECTION
For example, to generate the declarations for the STAFF table in the SAMPLE database in C in the output
file staff.h, issue the following command:
struct
{
short id;
struct
{
short length;
char data[9];
} name;
short dept;
char job[6];
short years;
double salary;
double comm;
} staff;
Note that the execution of this statement includes conversion between DECIMAL and DOUBLE data types.
To make the query results more readable on your screen, you could use the following SELECT statement:
The CAST function used in the preceding example returns a character-string representation of a number.
To convert data within your application, contact your compiler vendor for additional routines, classes,
built-in types, or APIs that support this conversion.
If your application code page is not the same as your database code page, character data types can also
be subject to character conversion.
52 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
applies to more than just columns. Functions can have XML value arguments and produce XML values
as well. Similarly, stored procedures can take XML values as both input and output parameters. Finally,
XQuery expressions produce XML values regardless of whether they access XML columns.
XML data is character in nature and has an encoding that specifies the character set used. The encoding
of XML data can be determined externally, derived from the base application type containing the
serialized string representation of the XML document. It can also be determined internally, which requires
interpretation of the data. For Unicode encoded documents, a byte order mark (BOM), consisting of
a Unicode character code at the beginning of a data stream is recommended. The BOM is used as a
signature that defines the byte order and Unicode encoding form.
Existing character and binary types, which include CHAR, VARCHAR, CLOB, and BLOB may be used in
addition to XML host variables for fetching and inserting data. However, they will not be subject to implicit
XML parsing, as XML host variables would. Instead, an explicit XMLPARSE function with default white
space stripping is injected and applied.
XML and XQuery restrictions on developing embedded SQL applications
To declare XML host variables in embedded SQL applications:
In the declaration section of the application, declare the XML host variables as LOB data types:
where <hostvar_name> is a CLOB host variable that contains XML data encoded in the mixed code page
of the application.
• SQL TYPE IS XML AS DBCLOB(n) <hostvar_name>
where <hostvar_name> is a DBCLOB host variable that contains XML data encoded in the application
graphic code page.
• SQL TYPE IS XML AS BLOB(n) <hostvar_name>
where <hostvar_name> is a BLOB host variable that contains XML data internally encoded“1” on page 53.
• SQL TYPE IS XML AS CLOB_FILE <hostvar_name>
where <hostvar_name> is a CLOB file that contains XML data encoded in the application mixed code
page.
• SQL TYPE IS XML AS DBCLOB_FILE <hostvar_name>
where <hostvar_name> is a DBCLOB file that contains XML data encoded in the application graphic code
page.
• SQL TYPE IS XML AS BLOB_FILE <hostvar_name>
where <hostvar_name> is a BLOB file that contains XML data internally encoded“1” on page 53.
Note:
1. Refer to the algorithm for determining encoding with XML 1.0 specifications (http://
www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info).
54 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Application can check the sqlca.sqlerrd[2] field to get the number of rows that are successfully fetched
with the same cursor.
The SQLWARN1 field in the SQLCA structure might contain an X or W if the value of a string column is
truncated when it is assigned to a host variable. The field contains an N if a null terminator is truncated.
A value of X is returned by the database manager only if all of the following conditions are met:
• A mixed code page connection exists where conversion of character string data from the database code
page to the application code page involves a change in the length of the data.
• A cursor is blocked.
• A null-indicator variable is provided by your application.
The value returned in the null-indicator variable will be the length of the resultant character string in the
application's code page.
In all other cases involving data truncation (as opposed to null terminator truncation), the database
manager returns a W. In this case, the database manager returns a value in the null-indicator variable to
the application that is the length of the resultant character string in the code page of the select list item
(either the application code page, the database code page, or nothing).
Before you can use null-indicator variables in the host language, declare the null-indicator variables. In
the following example, suitable for C and C++ programs, the null-indicator variable cmind can be declared
as:
The following table provides examples for the supported host languages:
COBOL
EXEC SQL FETCH C1 INTO :cm INDICATOR :cmind END-EXEC
IF cmind LESS THAN 0
DISPLAY 'Commission is NULL'
FORTRAN
EXEC SQL FETCH C1 INTO :cm INDICATOR :cmind
IF ( cmind .LT. 0 ) THEN
WRITE(*,*) 'Commission is NULL'
ENDIF
REXX
CALL SQLEXEC 'FETCH C1 INTO :cm INDICATOR :cmind'
IF ( cmind < 0 )
SAY 'Commission is NULL'
COBOL
EXEC SQL UPDATE staff SET job = 'Clerk' WHERE job = 'Mgr' END_EXEC.
IF SQLCODE LESS THAN 0
DISPLAY 'UPDATE ERROR: SQLCODE = ', SQLCODE.
FORTRAN
EXEC SQL UPDATE staff SET job = 'Clerk' WHERE job = 'Mgr'
if ( sqlcode .lt. 0 ) THEN
write(*,*) 'Update error: sqlcode = ', sqlcode
COBOL
EXEC SQL FETCH C1 INTO :cm END-EXEC
DISPLAY 'Commission = ' cm
FORTRAN
EXEC SQL FETCH C1 INTO :cm
WRITE(*,*) 'Commission = ', cm
REXX
CALL SQLEXEC 'FETCH C1 INTO :cm'
SAY 'Commission = ' cm
56 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Example: Referencing XML host variables in embedded SQL applications
You can create XML host variables in embedded SQL applications so that you can read and process XML
data.
The following sample applications demonstrate how to reference XML host variables in C and COBOL.
// as XML AS CLOB
// The XML value written to xmlBuf will be prefixed by an XML declaration
// similar to: <?xml version = "1.0" encoding = "ISO-8859-1" ?>
// Note: The encoding name will depend upon the application codepage
EXEC SQL SELECT xmlCol INTO :xmlBuf
FROM myTable
WHERE id = '001';
EXEC SQL UPDATE myTable
SET xmlCol = :xmlBuf
WHERE id = '001';
// as XML AS BLOB
// The XML value written to xmlblob will be prefixed by an XML declaration
// similar to: <?xml version = "1.0" encoding = "UTF-8"?>
EXEC SQL SELECT xmlCol INTO :xmlblob
FROM myTable
WHERE id = '001';
EXEC SQL UPDATE myTable
SET xmlCol = :xmlblob
WHERE id = '001';
// as CLOB
// The output will be encoded in the application character codepage,
// but will not contain an XML declaration
EXEC SQL SELECT XMLSERIALIZE (xmlCol AS CLOB(10K)) INTO :clobBuf
FROM myTable
WHERE id = '001';
EXEC SQL UPDATE myTable
SET xmlCol = XMLPARSE (:clobBuf PRESERVE WHITESPACE)
WHERE id = '001';
* as XML
EXEC SQL SELECT xmlCol INTO :xmlBuf
FROM myTable
WHERE id = '001' END-EXEC.
EXEC SQL UPDATE myTable
SET xmlCol = :xmlBuf
WHERE id = '001' END-EXEC.
* as BLOB
EXEC SQL SELECT xmlCol INTO :xmlblob
FROM myTable
WHERE id = '001' END-EXEC.
EXEC SQL UPDATE myTable
SET xmlCol = :xmlblob
WHERE id = '001' END-EXEC.
* as CLOB
EXEC SQL SELECT XMLSERIALIZE(xmlCol AS CLOB(10K)) INTO :clobBuf
FROM myTable
WHERE id= '001' END-EXEC.
Declare section for host variables in C and C++ embedded SQL applications
You must use an SQL declare section to identify host variable declarations. SQL declare sections alert the
precompiler to any host variables that can be referenced in subsequent SQL statements.
For example:
The C or C++ precompiler only recognizes a subset of valid C or C++ declarations as valid host variable
declarations. These declarations define either numeric or character variables. Host variables can be
grouped into a single host structure. You can declare C++ class data members as host variables.
58 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
A numeric host variable can be used as an input or output variable for any numeric SQL input or output
value. A character host variable can be used as an input or output variable for any character, date, time, or
timestamp SQL input or output value. The application must ensure that output variables are long enough
to contain the values that they receive.
You can define, name, and use a host variable within the SQL declare section. In the following example, a
struct type called staff_record is first defined. Then the variable named staff_detail is declared as being of
type staff_record:
typedef struct {
short id;
VARCHAR name[10+1];
short years;
double salary;
} staff_record;
staff_record staff_detail;
• The precompiler supports the same scope rules as the C and C++ programming languages. Therefore,
you can use the same name for two different variables each existing within their own scope. In the
following example, both declarations of the variable called empno are allowed; the second declaration
does not cause an error:
file: main.sqc
...
void scope1()
{
EXEC SQL BEGIN DECLARE SECTION ;
short empno;
...
}
void scope2()
{
EXEC SQL BEGIN DECLARE SECTION ;
.
.
.
short age = 26; /* SQL type 500 */
short year; /* SQL type 500 */
sqlint32 salary; /* SQL type 496 */
sqlint32 deptno; /* SQL type 496 */
float bonus; /* SQL type 480 */
double wage; /* SQL type 480 */
char mi; /* SQL type 452 */
char name[6]; /* SQL type 460 */
struct {
short len;
char data[24];
} address; /* SQL type 448 */
struct {
short len;
char data[32695];
} voice; /* SQL type 456 */
sql type is clob(1m)
chapter; /* SQL type 408 */
sql type is clob_locator
chapter_locator; /* SQL type 964 */
sql type is clob_file
chapter_file_ref; /* SQL type 920 */
sql type is blob(1m)
video; /* SQL type 404 */
sql type is blob_locator
video_locator; /* SQL type 960 */
sql type is blob_file
video_file_ref; /* SQL type 916 */
sql type is dbclob(1m)
tokyo_phone_dir; /* SQL type 412 */
sql type is dbclob_locator
tokyo_phone_dir_lctr; /* SQL type 968 */
sql type is dbclob_file
tokyo_phone_dir_flref; /* SQL type 924 */
sql type is varbinary(12)
myVarBinField; /* SQL type 908 */
sql type is binary(4)
myBinField; /* SQL type 912 */
struct {
short len;
sqldbchar data[100];
} vargraphic1; /* SQL type 464 */
/* Precompiled with
WCHARTYPE NOCONVERT option */
struct {
short len;
wchar_t data[100];
} vargraphic2; /* SQL type 464 */
/* Precompiled with
WCHARTYPE CONVERT option */
struct {
short len;
sqldbchar data[10000];
} long_vargraphic1; /* SQL type 472 */
/* Precompiled with
WCHARTYPE NOCONVERT option */
struct {
short len;
wchar_t data[10000];
} long_vargraphic2; /* SQL type 472 */
/* Precompiled with
WCHARTYPE CONVERT option */
sqldbchar graphic1[100]; /* SQL type 468 */
/* Precompiled with
WCHARTYPE NOCONVERT option */
60 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
wchar_t graphic2[100]; /* SQL type 468 */
/* Precompiled with
WCHARTYPE CONVERT option */
char date[11]; /* SQL type 384 */
char time[9]; /* SQL type 388 */
char timestamp[27]; /* SQL type 392 */
short wage_ind; /* Null indicator */
.
.
.
The SQLCODE declaration is assumed during the precompile step. Note that when using this option, the
INCLUDE SQLCA statement must not be specified.
In an application that is made up of multiple source files, the SQLCODE and SQLSTATE variables can be
defined in the first source file as in the previous example. Subsequent source files should modify the
definitions as follows:
sqlint32
4
long
int
__int64
long long
int
5
long
int
varname ;
= value
*
& const
volatile
Notes:
1 REAL (SQLTYPE 480), length 4
2 DOUBLE (SQLTYPE 480), length 8
3 SMALLINT (SQLTYPE 500)
4 For maximum application portability, use sqlint32 for INTEGER host variables and sqlint64 for
BIGINT host variables. By default, the use of long host variables results in the precompiler error
SQL0402 on platforms where long is a 64 bit quantity, such as 64 BIT UNIX. Use the PREP option
LONGERROR NO to force Db2 to accept long variables as acceptable host variable types and treat
them as BIGINT variables.
5 For maximum application portability, use sqlint32 and sqlint64 for INTEGER and BIGINT host
variables. To use the BIGINT data type, your platform must support 64 bit integer values. By default,
the use of long host variables results in the precompiler error SQL0402 on platforms where long is a
64 bit quantity, such as 64 BIT UNIX. Use the PREP option LONGERROR NO to force Db2 to accept long
variables as acceptable host variable types and treat them as BIGINT variables.
register
CHAR
C String = value
CHAR
62 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
1
varname
*
& const
volatile
C String
2
varname [ length ]
( varname )
*
& const
volatile
Notes:
1 CHAR (SQLTYPE 452), length 1
2 Null-terminated C string (SQLTYPE 460); length can be any valid constant expression
Form 2: Syntax for variable-length character host variables in C and C++ embedded SQL applications
struct { short var1
auto const tag int
extern volatile
static
register
1
; char var2 [ length ] ; }
unsigned
varname Values
*
& const
volatile
Values
= { value-1 , value-2 }
Notes:
1In form 2, length can be any valid constant expression. Its value after evaluation determines if the
host variable is VARCHAR (SQLTYPE 448) or LONG VARCHAR (SQLTYPE 456).
Variable-Length Character Host Variable Considerations:
The wchar_t and sqldbchar data types for graphic data in C and C++
embedded SQL applications
The size and encoding of Db2 graphic data is constant from one operating system to another for a
particular code page. However, the size and internal format of the ANSI C or C++ wchar_t data type
depend on which compiler and operating system you use.
The sqldbchar data type is defined by Db2 to be 2 bytes in size, and is intended to be a portable way of
manipulating DBCS and UCS-2 data in the same format in which it is stored in the database.
You can define all Db2 C graphic host variable types with either the wchar_t or sqldbchar data
type. You must use the wchar_t data type if you build your application with the WCHARTYPE CONVERT
precompile option.
If you build your application with the WCHARTYPE NOCONVERT precompile option, you can use the
sqldbchar data type for maximum portability between different Db2 client and server environments.
You can use the wchar_t data type with the WCHARTYPE NOCONVERT option, but only on environments
where the wchar_t data type is defined as 2 bytes in length.
64 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
If you incorrectly use either a wchar_t or sqldbchar data type in host variable declarations, an error
can be returned during the precompile process.
WCHARTYPE precompiler option for graphic data in C and C++ embedded SQL
applications
You can use the WCHARTYPE precompiler option to specify whether you want to use multibyte format or
wide-character format for your graphic data.
There are two possible values for the WCHARTYPE option:
CONVERT
If you select the WCHARTYPE CONVERT option in Linux or UNIX operating systems, character codes
are converted between the graphic host variable and the database manager. For graphic input host
variables, the character code is converted from wide-character format to multibyte DBCS character
format with the ANSI C function wcstombs() before the data is sent to the database manager. For
graphic output host variables, the character code is converted from multibyte DBCS character format
to wide-character format with the ANSI C function mbstowcs() before the data received from the
database manager is stored in the host variable.
For Windows operating systems, if a conversion failure is encountered for graphic host variables, user
can set the SkipLocalCPConversionForWcharConvert keyword to ON in the IBM data server
driver configuration file (db2dsdriver.cfg) to avoid the failure.
The advantage to using the WCHARTYPE CONVERT option is that it allows your application to use
the ANSI C mechanisms for dealing with wide-character strings (L-literals, 'wc' string functions, and
others) without having to explicitly convert the data to multibyte format before data is sent to the
database manager. The disadvantage is that the implicit conversion can have an impact on the
performance of your application at run time, and it can increase memory requirements.
If you select the WCHARTYPE CONVERT option, declare all graphic host variables with wchar_t
instead of sqldbchar.
If you want the WCHARTYPE CONVERT option behavior, but your application does not need
to be precompiled (for example, a CLI application), then define the C preprocessor macro
SQL_WCHART_CONVERT at compile time. This ensures that certain definitions in the Db2 header files
use the data type wchar_t instead of sqldbchar.
NOCONVERT (default)
If you choose the WCHARTYPE NOCONVERT option, or do not specify any WCHARTYPE option,
no implicit character code conversion occurs between the application and the database manager.
Data in a graphic host variable is sent to and received from the database manager as unaltered
DBCS characters. This has the advantage of improved performance, but the disadvantage that your
application must either refrain from using wide-character data in wchar_t host variables, or must
explicitly call the wcstombs() and mbstowcs() functions to convert the data to and from multibyte
format when interfacing with the database manager.
If you select the WCHARTYPE NOCONVERT option, declare all graphic host variables with the
sqldbchar type for maximum portability to other Db2 client/server environments.
You must consider the guidelines include in the following list:
• Because wchar_t or sqldbchar support is used to handle DBCS data, its use requires DBCS or EUC
capable hardware and software. This support is only available in the DBCS environment of Db2, or for
dealing with GRAPHIC data in any application (including single-byte applications) connected to a UCS-2
database.
• Avoid use of non-DBCS (non-double byte characters) characters, and wide-characters that can be
converted to non-DBCS characters, in graphic strings. Graphic strings are not validated to ensure that
their values contain only double-byte character code points. Graphic host variables must contain only
DBCS data, or, if the WCHARTYPE CONVERT setting is in effect, wide-character data that converts to
DBCS data. Use character host variables to store mixed double-byte and single-byte data. Mixed data
host variables are unaffected by the setting of the WCHARTYPE option.
66 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
struct { short var-1
auto const tag int
extern volatile
static
register
1 2
; var-2 [ length ] ; }
sqldbchar
wchar_t
Variable ;
*
& const
volatile
Variable
variable-name
= { value-1 , value-2 }
Notes:
1 To determine which of the two graphic types to be used, see the description of the wchar_t and
sqldbchar data types in C and C++.
2 length can be any valid constant expression. Its value after evaluation determines if the host variable
is VARGRAPHIC (SQLTYPE 464) or LONG VARGRAPHIC (SQLTYPE 472). The value of length must be
greater than or equal to 1, and not greater than the maximum length of LONG VARGRAPHIC which is
16 350.
Graphic declaration (VARGRAPHIC structured form) Considerations:
1. var-1 and var-2 must be simple variable references (no operators) and cannot be used as host
variables.
2. value-1 and value-2 are initializers for var-1 and var-2. value-1 must be an integer and value-2 must
be a wide-character string literal (L-literal) if the WCHARTYPE CONVERT precompiler option is used.
3. The struct tag can be used to define other data areas, but itself cannot be used as a host variable.
static
register
CHAR
C string = value
CHAR
2
varname
*
& const
volatile
C string
3
varname [ length ]
( varname )
*
& const
volatile
Notes:
1 To determine which of the two graphic types to be used, see the description of the wchar_t and
sqldbchar data types in C and C++.
2 GRAPHIC (SQLTYPE 468), length 1
3 Null-terminated graphic string (SQLTYPE 400)
Declaration of large object type host variables in C and C++ embedded SQL
applications
Large object (LOB) type host variables that you declare in your embedded C or C++ application are treated
as if they were declared in a C or C++ program. You can use host variables to exchange data between the
embedded application and the database manager.
68 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
The syntax for declaring large object (LOB) host variables in C or C++ is:
register
1
length )
*
& const
volatile
LOB data
Notes:
1 length can be any valid constant expression, in which the constant K, M, or G can be used. The value
of length after evaluation for BLOB and CLOB must be 1 <= length <= 2 147 483 647. The value of
length after evaluation for DBCLOB must be 1 <= length <= 1 073 741 823.
LOB host variable considerations:
1. The SQL TYPE IS clause is needed to distinguish the three LOB-types from each other so that type
checking and function resolution can be carried out for LOB-type host variables that are passed to
functions.
2. SQL TYPE IS, BLOB, CLOB, DBCLOB, K, M, G can be in mixed case.
3. The maximum length allowed for the initialization string "init-data" is 32 702 bytes, including string
delimiters (the same as the existing limit on C and C++ strings within the precompiler).
4. The initialization length, init-len, must be a numeric constant (for example, it cannot include K, M, or
G).
5. A length for the LOB must be specified; that is, the following declaration is not permitted:
6. If the LOB is not initialized within the declaration, no initialization will be done within the precompiler-
generated code.
7. If a DBCLOB is initialized, it is the user's responsibility to prefix the string with an 'L' (indicating a
wide-character string).
Note: Wide-character literals, for example, L"Hello", should only be used in a precompiled program
if the WCHARTYPE CONVERT precompile option is selected.
BLOB example:
Declaration:
CLOB example:
Declaration:
DBCLOB example:
Declaration:
Precompiled with the WCHARTYPE NOCONVERT option, results in the generation of the following
structure:
struct my_dbclob1_t {
sqluint32 length;
sqldbchar data[30000];
} my_dbclob1;
Declaration:
Precompiled with the WCHARTYPE CONVERT option, results in the generation of the following structure:
struct my_dbclob2_t {
sqluint32 length;
wchar_t data[30000];
} my_dbclob2 = SQL_DBCLOB_INIT(L"mydbdata");
Declaration of large object locator type host variables in C and C++ embedded
SQL applications
Large object (LOB) locator host variables that you declare in your embedded C or C++ application are
treated as if they were declared in a C or C++ program. You can use host variables to exchange data
between the embedded application and the database manager.
The syntax for declaring large object (LOB) locator host variables in C or C++ is:
70 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
SQL TYPE IS BLOB_LOCATOR
auto const CLOB_LOCATOR
extern volatile
DBCLOB_LOCATOR
static
register
Variable
Variable
* variable-name
& const = init-value
volatile
sqluint32 my_locator;
Declaration of file reference type host variables in C and C++ embedded SQL
applications
File reference type host variables that you declare in your embedded C or C++ application are treated as
if they were declared in a C or C++ program. You can use host variables to exchange data between the
embedded application and the database manager.
The syntax for declaring file reference host variables in C or C++ is:
register
Variable
Variable
* variable-name
& const = init-value
volatile
Note: SQL TYPE IS, BLOB_FILE, CLOB_FILE, DBCLOB_FILE can be in mixed case.
CLOB file reference example (other LOB file reference type declarations are similar):
Declaration:
Note: This structure is equivalent to the sqlfile structure located in the sql.h header. See Figure 1 on page
72 to refer to the syntax diagram.
char mystring[20];
char (*mystring)[20];
• Use parentheses when declaring a pointer to a null-terminated character array. In all other cases,
parentheses are not allowed. For example:
72 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
EXEC SQL BEGIN DECLARE SECTION;
char (*arr)[10]; /* correct */
char *(arr); /* incorrect */
char *arr[10]; /* incorrect */
EXEC SQL END DECLARE SECTION;
The first declaration is a pointer to a 10-byte character array. This is a valid host variable. The second is
not a valid declaration. The parentheses are not allowed in a pointer to a character. The third declaration
is an array of pointers. This is not a supported data type.
The host variable declaration:
char *ptr;
is accepted, but it does not mean null-terminated character string of undetermined length. Instead, it
means a pointer to a fixed-length, single-character host variable. This might not be what is intended. To
define a pointer host variable that can indicate different character strings, use the first declaration form
shown previously in this topic.
• When pointer host variables are used in SQL statements, they should be prefixed by the same number
of asterisks as they were declared with, as in the following example:
• Only the asterisk can be used as an operator over a host variable name.
• The maximum length of a host variable name is not affected by the number of asterisks specified,
because asterisks are not considered part of the name.
• Whenever using a pointer variable in an SQL statement, you should leave the optimization level
precompile option (OPTLEVEL) at the default setting of 0 (no optimization). This means that no SQLDA
optimization will be done by the database manager.
class STAFF
{
private:
EXEC SQL BEGIN DECLARE SECTION;
char staff_name[20];
short int staff_id;
double staff_salary;
EXEC SQL END DECLARE SECTION;
short staff_in_db;
.
.
};
Data members are only directly accessible in SQL statements through the implicit this pointer provided
by the C++ compiler in class member functions. You cannot explicitly qualify an object instance (such as
SELECT name INTO :my_obj.staff_name ...) in an SQL statement.
If you directly refer to class data members in SQL statements, the database manager resolves the
reference using the this pointer. For this reason, you should leave the optimization level precompile option
(OPTLEVEL) at the default setting of 0 (no optimization).
class STAFF
{
.
.
.
public:
.
.
.
In this example, class data members staff_name, staff_id, and staff_salary are used directly in
the INSERT statement. Because they have been declared as host variables (see the first example in this
section), they are implicitly qualified to the current object with the this pointer. In SQL statements, you
can also refer to data members that are not accessible through the this pointer. You do this by referring to
them indirectly using pointer or reference host variables.
The following example shows a new method, asWellPaidAs that takes a second object, otherGuy. This
method references its members indirectly through a local pointer or reference host variable, as you
cannot reference its members directly within the SQL statement.
VARBINARY
Example
Declaring:
74 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Results in the generation of the following C code:
Declaring:
On retrieval from the database, the length of the data is set properly in the corresponding structure.
Scope resolution and class member operators in C and C++ embedded SQL
applications
You cannot use the C++ scope resolution operator '::', nor the C and C++ member operators '.' or '->' in
embedded SQL statements.
You can easily accomplish the same thing through use of local pointer or reference variables, which
are set outside the SQL statement, to point to the required scoped variable, then used inside the SQL
statement to refer to it. The following example shows the correct method to use:
Binary storage of variable values using the FOR BIT DATA clause in C and C++
embedded SQL applications
You can declare certain database columns by using the FOR BIT DATA clause. These columns, which
generally contain characters, are used to hold binary information.
You cannot use the standard C or C++ string type 460 for columns designated FOR BIT DATA. The
database manager truncates this data type when a null character is encountered. Use either the
VARCHAR (SQL type 448) or CLOB (SQL type 408) structures.
76 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Initialization of host variables in C and C++ embedded SQL applications
In C and C++ declare sections, you can declare and initialize multiple variables on a single line. However,
you must initialize variables using the "=" symbol, not parentheses.
The following example shows the correct and incorrect methods of initialization in a declare section:
Macro expansion and the DECLARE SECTION of C and C++ embedded SQL
applications
The C or C++ precompiler cannot directly process any C macro that is used in a declaration within a
declare section. You must first preprocess the source file with an external C preprocessor by specifying
the exact command for invoking a C preprocessor to the precompiler through the PREPROCESSOR option.
When you specify the PREPROCESSOR option, the precompiler first processes all the SQL INCLUDE
statements by incorporating the contents of all the files referred to in the SQL INCLUDE statement into
the source file. The precompiler then invokes the external C preprocessor using the command you specify
with the modified source file as input. The preprocessed file, which the precompiler always expects to
have an extension of .i, is used as the new source file for the rest of the precompiling process.
Any #line macro generated by the precompiler no longer references the original source file, but instead
references the preprocessed file. To relate any compiler errors back to the original source file, retain
comments in the preprocessed file. This helps you to locate various sections of the original source files,
including the header files. The option to retain comments is commonly available in C preprocessors, and
you can include the option in the command you specify through the PREPROCESSOR option. You must
not have the C preprocessor output any #line macros itself, as they can be incorrectly mixed with ones
generated by the precompiler.
Notes on using macro expansion:
1. The command you specify through the PREPROCESSOR option must include all the required options,
but not the name of the input file. For example, for IBM C on AIX you can use the option:
xlC -P -DMYMACRO=1
2. The precompiler expects the command to generate a preprocessed file with a .i extension. However,
you cannot use redirection to generate the preprocessed file. For example, you cannot use the
following option to generate a preprocessed file:
3. Any errors the external C preprocessor encounters are reported in a file with a name corresponding to
the original source file, but with a .err extension.
4. For compilers (gcc/clang/OpenXLC) that do not automatically generate the .i file
and do not recognize the file suffix as C/C++ file, the options -x c and -o
<inputfile_name_without_suffix>.i need to be included:
ibm-clang -E -x c -o <inputfile_name_without_suffix>.i
For example, if the input file is named myprogram.sqc, the PREPROCESSOR command using ibm-
clang is:
ibm-clang -E -x c -o myprogram.i
For more details refer to the compiler documentation for the -x and -o options.
#define SIZE 3
The previous declarations resolve to the following example after you use the PREPROCESSOR option:
Host structure support in the declare section of C and C++ embedded SQL
applications
A host structure contains a list of host variables that can be referred to by embedded SQL statements.
With host structure support, the C or C++ precompiler allows host variables to be grouped into a single
host structure.
Host structure support provides a shorthand for referencing that same set of host variables in an SQL
statement.
For example, the following host structure can be used to access some of the columns in the STAFF table
of the SAMPLE database:
struct tag
{
short id;
struct
{
short length;
char data[10];
} name;
struct
{
short years;
double salary;
} info;
} staff_record;
The fields of a host structure can be any of the valid host variable types. Valid types include all numeric,
character, and large object types. Nested host structures are also supported up to 25 levels. In the
example shown previously, the field info is a sub-structure, whereas the field name is not, as it
represents a VARCHAR field. The same principle applies to LONG VARCHAR, VARGRAPHIC and LONG
VARGRAPHIC. Pointer to host structure is only supported when it is not nested within another structure.
There are two ways to reference the host variables grouped in a host structure in an SQL statement:
• The host structure name can be referenced in an SQL statement.
78 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
EXEC SQL SELECT id, name, years, salary
INTO :staff_record
FROM staff
WHERE id = 10;
The precompiler converts the reference to staff_record into a list, separated by commas, of all the
fields declared within the host structure. Each field is qualified with the host structure names of all
levels to prevent naming conflicts with other host variables or fields. This is equivalent to the following
method.
• Fully qualified host variable names can be referenced in an SQL statement.
Here, the DELETE statement expects a single character-based host variable. By giving a host structure
instead, the statement results in a precompile-time error:
Other uses of host structures, which can cause an SQL0087N error to occur, include PREPARE, EXECUTE
IMMEDIATE, CALL, indicator variables and SQLDA references. Host structures with exactly one field are
permitted in such situations, as are references to individual fields (second example).
short ind_tab[10];
The preceding example declares an indicator table with 10 elements. It can be used in an SQL statement
as follows:
The following lists each host structure field with its corresponding indicator variable in the table:
staff_record.id
ind_tab[0]
staff_record.name
ind_tab[1]
short scalar_ind;
If an indicator table is specified along with a host variable instead of a host structure, only the first
element of the indicator table, for example ind_tab[0], will be used:
struct tag
{
short i[2];
} test_record;
The array will be expanded into its elements when test_record is referenced in an SQL statement
making :test_record equivalent to :test_record.i[0], :test_record.i[1].
80 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
k<n
k characters are moved to the target host variable and a null character is placed in character k +
1. If an indicator variable was specified with the host variable, the value of the indicator variable
is set to 0.
For input:
When the database manager encounters an input host variable of one of these SQLTYPE values
that does not end with a null-terminator, it will assume that character n+1 will contain the null-
terminator character.
• If the LANGLEVEL option on the PREP command is MIA:
For output:
If...
Then...
k >= n
n - 1 characters are moved to the target host variable, SQLWARN1 is set to 'W', and SQLCODE 0
(SQLSTATE 01501). The nth character is set to the null-terminator. If an indicator variable was
specified with the host variable, the value of the indicator variable is set to k.
k+1=n
k characters are moved to the target host variable, and the null-terminator is placed in character
n. If an indicator variable was specified with the host variable, the value of the indicator variable
is set to 0.
k+1<n
k characters are moved to the target host variable, n - k -1 blanks are appended on the right
starting at character k + 1, then the null-terminator is placed in character n. If an indicator
variable was specified with the host variable, the value of the indicator variable is set to 0.
For input:
When the database manager encounters an input host variable of one of these SQLTYPE values that
does not end with a null character, SQLCODE -302 (SQLSTATE 22501) is returned.
As previously defined, when specified in any other SQL context, a host variable of SQLTYPE 460 with
length n is treated as a VARCHAR data type with length n and a host variable of SQLTYPE 468 with length
n is treated as a VARGRAPHIC data type with length n.
while (1) {
EXEC SQL FETCH empcr INTO :empno :lastname; /* bulk fetch */
... /* 100 or less rows */
...
}
end_fetch:
EXEC SQL CLOSE empcr;
82 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Use of C or C++ host variable arrays in INSERT statements
In the following example, host variable arrays arr_in1 and arr_in2 are used for an INSERT statement:
// Declaring host variables.
EXEC SQL BEGIN DECLARE SECTION;
sqlint32 arr_in1[3];
char arr_in2[3][11];
EXEC SQL END DECLARE SECTION;
...
// Populating the arrays.
for ( i = 0; i < 3; i++)
{
arr_in1[i] = 100 + i;
sprintf(arr_in2[i], "hello%d", arr_in1[i]);
}
// The INSERT operation was successful and 3 rows has been stored in database.
printf(“sqlca.sqlerrd[2] = %d\n”, sqlca.sqlerrd[2] ); // 3
...
// Populating the arrays.
for ( i = 0; i < 3; i++)
{
arr_in1[i] = 100 + i;
}
arr_in2[0] = 1000;
arr_in2[1] = 1001;
84 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
– User-defined data type
– XML
• FOR N ROWS clause can be used to specify the cardinality for INSERT and MERGE statement, where N
can be an integer or a host variable of type int or short. If array host variables are used, it will take the
minimum cardinality value among all the host variables that are used in the SQL.
• Host variable array support is not provided for Db2 for z/OS® and Db2 for i servers.
Structure arrays
You can use structure arrays for FETCH INTO, INSERT, UPDATE, and DELETE statements that are non-
dynamic, when you set the precompiler option COMPATIBILITY_MODE to ORA.
You can use structure arrays to store multiple column data in a structure form.
For a structure array that is declared for an INSERT, UPDATE, or DELETE statement, you must ensure that
all array elements are initialized with a value. Otherwise, unexpected data can get introduced or removed
from the table.
The total number of rows that are successfully processed is stored in the sqlca.sqlerrd[3] field.
However, the sqlca.sqlerrd[3] field does not represent the number of rows that are committed
successfully in the case of INSERT, UPDATE, or DELETE operations.
The total number of rows that are impacted by the INSERT, UPDATE, or DELETE operation is stored in the
sqlca.sqlerrd[2] field.
In one FETCH INTO statement, the maximum number of records that can be retrieved is the cardinality of
the array that is declared. If more rows are available after the first fetch, you can repeat the FETCH INTO
statement to obtain the next set of rows.
A structure array can be used to store multiple column data in a structure form when a FETCH INTO
statement is run. In the following example, a structure array is used for a FETCH INTO statement:
You can use a structure array to store multiple rows for an INSERT statement. In the following example, a
structure array is used for an INSERT statement:
// Declare structure array with cardinality of 3.
EXEC SQL BEGIN DECLARE SECTION;
typedef struct _st_type {
int id;
char name[21];
} st_type;
st_type st[3];
EXEC SQL END DECLARE SECTION;
...
// Populating the array.
for( i=0; i<3; i++)
{
memset( &st[i], 0x00, sizeof(st_type));
if( i==0) { st[i].id = 100; strcpy(st[i].name, "hello1");}
if( i==1) { st[i].id = 101; strcpy(st[i].name, "hello2");}
if( i==2) { st[i].id = 102; strcpy(st[i].name, "hello3");}
}
// The structure elements must be in
// the same order as that of the table elements.
//
EXEC SQL INSERT INTO tbl values (:st);
// The INSERT operation was successful and 3 rows has been stored in database.
printf(“sqlca.sqlerrd[2] = %d\n”, sqlca.sqlerrd[2] ); // 3
86 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
In the following example, the indicator variable array that is called bonus_ind is declared. The bonus_ind
indicator variable array can have up to 100 elements, the same cardinality as the bonus array variable.
When the data is being fetched, if the value of bonus is NULL, the value in bonus_ind is negative.
while (1) {
EXEC SQL FETCH empcr INTO :empno :lastname :edlevel,
:bonus INDICATOR :bonus_ind
...
...
}
end_fetch:
EXEC SQL CLOSE empcr;
Instead of being identified by the INDICATOR keyword, an indicator variable can immediately follow its
corresponding host variable, as shown in the following example:
In the following example, the indicator variable arrays ind_in1 and ind_in2 are declared. It can have up to
three elements, the same cardinality as the arr_in1 and arr_in2 array variables. If the value of ind_in1 or
ind_in2 is negative, the NULL value is inserted for the corresponding arr_in1 or arr_in2 value.
// Declare host & indicator variablesof array size 3
EXEC SQL BEGIN DECLARE SECTION;
sqlint32 arr_in1[3];
char arr_in2[3][11];
short ind_in1[3]; // indicator array size is same as host
// variable’s array size
short ind_in2[3]; // note here indicator array size is greater
// than host variable’s array size
EXEC SQL END DECLARE SECTION;
...
// Populating the arrays.
for ( i = 0; i < 3; i++)
{
arr_in1[i] = i + 1;
sprintf(arr_in2[i], "hello%d", arr_in1[i]);
}
ind_in1[0] = 0;
ind_in1[1] = SQL_NULL_DATA; // Mark it as a NULL data
ind_in1[2] = 0;
ind_in2[0] = 0;
ind_in2[1] = 0;
ind_in2[2] = SQL_NULL_DATA; // Mark it as a NULL data
If the cardinality of indicator variable array does not match the cardinality of the corresponding host
variable array, an error is returned.
In the following example, the indicator structure array MyStructInd is declared.
...
Important: The following conditions must be met when the indicator structure array is used.
• The cardinality of the indicator structure array must be equal to or greater than the cardinality of the
structure array.
• All members in the indicator structure array must use the short data type.
• The number of members in the indicator structure array must match the number of members in the
corresponding structure array.
• For INSERT, UPDATE and DELETE operations, application must ensure that all indicator variables are
initialized with either 0 or SQL_NULL_DATA (-1).
The total number of rows that are successfully processed is stored in the sqlca.sqlerrd[3] field.
However, the sqlca.sqlerrd[3] field does not represent successfully committed number of rows in
the case of INSERT, UPDATE, or DELETE operations. The total number of rows that are impacted by the
INSERT, UPDATE, or DELETE operation is stored in the sqlca.sqlerrd[2] field.
88 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Declare section for host variables in COBOL embedded SQL applications
You must use an SQL declare section must be used to identify host variable declarations. The SQL
declare section alerts the precompiler to any host variables that can be referenced in subsequent SQL
statements.
For example:
If neither of these is specified, the SQLCODE declaration is assumed during the precompile step. The
SQLCODE and SQLSTATE variables can be declared using level 01 (as shown in the previous example) or
level 77. Note that when using this option, the INCLUDE SQLCA statement should not be specified.
For applications made up of multiple source files, the SQLCODE and SQLSTATE declarations can be
included in each source file as shown previously.
IS
01 variable-name PICTURE picture-string
77 PIC
1
COMP-3
IS COMPUTATIONAL-3
USAGE
COMP-5
COMPUTATIONAL-5
.
IS
VALUE value
Notes:
1 An alternative for COMP-3 is PACKED-DECIMAL.
90 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Floating point
01 variable-name
77 IS
USAGE
1
COMPUTATIONAL-1 .
COMP-1 IS
2 VALUE value
COMPUTATIONAL-2
COMP-2
Notes:
1 REAL (SQLTYPE 480), Length 4
2 DOUBLE (SQLTYPE 480), Length 8
Numeric host variable considerations:
1. Picture-string must have one of the following forms:
• S9(m)V9(n)
• S9(m)V
• S9(m)
2. Nines can be expanded (for example., "S999" instead of S9(3)")
3. m and n must be positive integers.
Fixed Length
IS
01 variable-name PICTURE picture-string
77 PIC
.
IS
VALUE value
Variable length
01 variable-name .
PIC
COMP-5
IS COMPUTATIONAL-5
USAGE
.
IS
VALUE value
IS
49 identifier-2 PICTURE picture-string
PIC
.
IS
VALUE value
However, because blanks can be significant in passwords, the p-word host variable should be
declared as a VARCHAR data item, so that your application can explicitly indicate the significant
password length for the CONNECT statement as follows:
92 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Declaration of fixed length and variable length graphic host variables in
COBOL embedded SQL applications
Fixed-length and variable-length graphic host variables that you declare in your embedded COBOL
application are treated as if they were declared in a COBOL program. You can use host variables to
exchange data between the embedded application and the database manager.
Following is the syntax for graphic host variables.
Fixed Length
IS
01 variable-name PICTURE picture-string USAGE
77 PIC
IS
DISPLAY-1 .
IS
VALUE value
Variable Length
01 variable-name .
IS
49 identifier-1 PICTURE S9(4)
PIC
COMP-5
IS COMPUTATIONAL-5
USAGE
.
IS
VALUE value
IS IS
49 identifier-2 PICTURE picture-string USAGE
PIC
DISPLAY-1 .
IS
VALUE value
length ) .
K
01 MY-BLOB.
49 MY-BLOB-LENGTH PIC S9(9) COMP-5.
49 MY-BLOB-DATA PIC X(2097152).
CLOB example:
Declaring:
01 MY-CLOB.
49 MY-CLOB-LENGTH PIC S9(9) COMP-5.
49 MY-CLOB-DATA PIC X(131072000).
DBCLOB example:
Declaring:
01 MY-DBCLOB.
49 MY-DBCLOB-LENGTH PIC S9(9) COMP-5.
49 MY-DBCLOB-DATA PIC G(30000) DISPLAY-1.
94 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Declaration of large object locator type host variables in COBOL embedded
SQL applications
Large object (LOB) locator type host variables that you declare in your embedded COBOL application
are treated as if they were declared in a COBOL program. You can use host variables to exchange data
between the embedded application and the database manager.
The syntax for declaring large object (LOB) locator host variables in COBOL is:
BLOB-LOCATOR .
CLOB-LOCATOR
DBCLOB-LOCATOR
• SQL TYPE IS, BLOB-FILE, CLOB-FILE, DBCLOB-FILE can be either uppercase, lowercase, or mixed.
BLOB file reference example (other LOB types are similar):
Declaring:
01 MY-FILE.
49 MY-FILE-NAME-LENGTH PIC S9(9) COMP-5.
49 MY-FILE-DATA-LENGTH PIC S9(9) COMP-5.
49 MY-FILE-FILE-OPTIONS PIC S9(9) COMP-5.
49 MY-FILE-NAME PIC X(255).
01 foo1.
10 a pic s9(4) comp-5.
10 a1 redefines a pic x(2).
10 b pic x(10).
That is, the subordinate item a1 that is declared with the REDEFINES clause, is not automatically
expanded out in such situations. If a1 is unambiguous, you can explicitly refer to a subordinate with
a REDEFINES clause in an SQL statement, as follows:
or
Binary storage of variable values using the FOR BIT DATA clause in COBOL
embedded SQL applications
You can declare certain database columns using the FOR BIT DATA clause. These columns, which
generally contain characters, are used to hold binary information.
The CHAR(n), VARCHAR, LONG VARCHAR, and BLOB data types are the COBOL host variable types that
can contain binary data. You must use these data types when working with columns with the FOR BIT
DATA attribute.
Note: The LONG VARCHAR data type is deprecated and might be removed in a future release.
96 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Host structure support in the declare section of COBOL embedded SQL
applications
In an application program, a host structure contains a list of host variables that can be referred to by
embedded SQL statements. The COBOL precompiler supports declarations of group data items in the host
variable declare section.
Host structure support provides a shorthand for referring to a set of elementary data items in an SQL
statement. For example, the following group data item can be used to access some of the columns in the
STAFF table of the SAMPLE database:
01 staff-record.
05 staff-id pic s9(4) comp-5.
05 staff-name.
49 l pic s9(4) comp-5.
49 d pic x(9).
05 staff-info.
10 staff-dept pic s9(4) comp-5.
10 staff-job pic x(5).
Group data items in the declare section can have any of the valid host variable types described previously
as subordinate data items. This includes all numeric and character types, as well as all large object
types. You can nest group data items up to 10 levels. Note that you must declare VARCHAR character
types with the subordinate items at level 49, as in the example shown previously. If they are not at
level 49, the VARCHAR is treated as a group data item with two subordinates, and is subject to the rules
of declaring and using group data items. In the previous example, staff-info is a group data item,
whereas staff-name is a VARCHAR. The same principle applies to LONG VARCHAR, VARGRAPHIC, and
LONG VARGRAPHIC. You may declare group data items at any level between 02 and 49.
You can use group data items and their subordinates in four ways:
Method 1.
The entire group may be referenced as a single host variable in an SQL statement:
The precompiler converts the reference to staff-record into a list, separated by commas, of all the
subordinate items declared within staff-record. Each elementary item is qualified with the group
names of all levels to prevent naming conflicts with other items. This is equivalent to the following
method.
Method 2.
The second way of using group data items:
Note: The reference to staff-id is qualified with its group name using the prefix staff-record., and
not staff-id of staff-record as in pure COBOL.
Assuming there are no other host variables with the same names as the subordinates of staff-record,
the preceding statement can also be coded as in method 3, eliminating the explicit group qualification.
Method 3.
As in pure COBOL, this method is acceptable to the precompiler as long as a given subordinate item can
be uniquely identified. If, for example, staff-job occurs in more than one group, the precompiler issues
an error indicating an ambiguous reference:
Method 4.
To resolve the ambiguous reference, you can use partial qualification of the subordinate item, for
example:
Because a reference to a group item alone, as in method 1, is equivalent to a comma-separated list of its
subordinates, there are instances where this type of reference leads to an error. For example:
Here, the CONNECT statement expects a single character-based host variable. By giving the staff-
record group data item instead, the host variable results in the following precompile-time error:
Other uses of group items that cause an SQL0087N to occur include PREPARE, EXECUTE IMMEDIATE,
CALL, indicator variables, and SQLDA references. Groups with only one subordinate are permitted in such
situations, as are references to individual subordinates, as in methods 2, 3, and 4 shown previously.
01 <indicator-table-name>.
05 <indicator-name> pic s9(4) comp-5
occurs <table-size> times.
For example:
01 staff-indicator-table.
05 staff-indicator pic s9(4) comp-5
occurs 7 times.
98 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
This indicator table can be used effectively with the first format of group item reference shown previously:
Here, the precompiler detects that staff-indicator was declared as an indicator table, and expands
it into individual indicator references when it processes the SQL statement. staff-indicator(1) is
associated with staff-id of staff-record, staff-indicator(2) is associated with staff-name of
staff-record, and so on.
Note: If there are k more indicator entries in the indicator table than there are subordinates in the data
item (for example, if staff-indicator has 10 entries, making k=6), the k extra entries at the end of
the indicator table are ignored. Likewise, if there are k fewer indicator entries than subordinates, the last
k subordinates in the group item do not have indicators associated with them. Note that you can refer to
individual elements in an indicator table in an SQL statement.
The SQLCOD declaration is assumed during the precompile step. The variable named SQLSTATE can also
be SQLSTA. Note that when using this option, the INCLUDE SQLCA statement should not be specified.
For applications that contain multiple source files, the declarations of SQLCOD and SQLSTATE can be
included in each source file, as shown previously.
INTEGER*2 varname
INTEGER*4 / initial-value /
REAL*4
REAL *8
DOUBLE PRECISION
100 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Declaration of fixed-length and variable length character host variables in
FORTRAN embedded SQL applications
You must declare character host variables when you program an embedded SQL application in FORTRAN.
Host variables are treated like FORTRAN variables, and allow for the exchange of data between the
embedded application and the database manager.
The syntax for fixed-length character host variables is:
Fixed length
Syntax for character host variables in FORTRAN: fixed length
,
CHARACTER varname
*n / initial-value /
Variable length
,
VARCHAR example:
Declaring:
character my_varchar(1000+2)
integer*2 my_varchar_length
character my_varchar_data(1000)
equivalence( my_varchar(1),
+ my_varchar_length )
equivalence( my_varchar(3),
+ my_varchar_data )
The application can manipulate both my_varchar_length and my_varchar_data; for example, to set
or examine the contents of the host variable. The base name (in this case, my_varchar), is used in SQL
statements to refer to the VARCHAR as a whole.
The application can manipulate both my_lvarchar_length and my_lvarchar_data; for example, to
set or examine the contents of the host variable. The base name (in this case, my_lvarchar), is used in
SQL statements to refer to the LONG VARCHAR as a whole.
Note: In a CONNECT statement, such as in the following example, the FORTRAN character string host
variables dbname and userid will have any trailing blanks removed before processing.
However, because blanks can be significant in passwords, you should declare host variables for
passwords as VARCHAR, and have the length field set to reflect the actual password length:
CLOB K
BLOB example:
Declaring:
102 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Results in the generation of the following structure:
character my_blob(2097152+4)
integer*4 my_blob_length
character my_blob_data(2097152)
equivalence( my_blob(1),
+ my_blob_length )
equivalence( my_blob(5),
+ my_blob_data )
CLOB example:
Declaring:
character my_clob(131072000+4)
integer*4 my_clob_length
character my_clob_data(131072000)
equivalence( my_clob(1),
+ my_clob_length )
equivalence( my_clob(5),
+ my_clob_data )
CLOB_LOCATOR
integer*4 my_locator
CLOB_FILE
character my_file(267)
integer*4 my_file_name_length
integer*4 my_file_data_length
integer*4 my_file_file_options
character*255 my_file_name
equivalence( my_file(1),
+ my_file_name_length )
equivalence( my_file(5),
+ my_file_data_length )
equivalence( my_file(9),
+ my_file_file_options )
equivalence( my_file(13),
+ my_file_name )
104 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Host variables in REXX
Host variables are REXX language variables that are referenced within SQL statements. Host variables
allow an application to exchange data with the database manager. After an application is precompiled,
host variables are used by the compiler as any other REXX variable.
Follow the rules described in the following sections when naming, declaring, and using host variables.
To ensure that a character string is not converted to a numeric data type, enclose the string with single
quotation marks as in the following example:
VAR = '100'
REXX sets the variable VAR to the 3 byte character string 100. If single quotation marks are to be included
as part of the string, follow this example:
VAR = "'100'"
When inserting numeric data into a CHARACTER field, the REXX interpreter treats numeric data as integer
data, thus you must concatenate numeric strings explicitly and surround them with single quotation
marks.
106 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
SQLRODA
The input/output SQLDA structure for stored procedures invoked using the CALL statement. It is also
the output SQLDA structure for stored procedures invoked using the Database Application Remote
Interface (DARI) API.
SQLRIDA
The input SQLDA structure for stored procedures invoked using the Database Application Remote
Interface (DARI) API.
SQLRDAT
An SQLCHAR structure for server procedures invoked using the Database Application Remote
Interface (DARI) API.
On Windows-based platforms, the RxFuncAdd commands need to be executed only once for all sessions.
On AIX, the SysAddFuncPkg should be executed in every REXX/SQL application.
Details on the Rxfuncadd and SysAddFuncPkg APIs are available in the REXX documentation for
Windows-based platforms and AIX.
It is possible that tokens within statements or commands that are passed to the SQLEXEC, SQLDBS, and
SQLDB2 routines could correspond to REXX variables. In this case, the REXX interpreter substitutes the
variable's value before calling SQLEXEC, SQLDBS, or SQLDB2.
To avoid this situation, enclose statement strings in quotation marks (' ' or " "). If you do not use quotation
marks, any conflicting variable names are resolved by the REXX interpreter, instead of being passed to the
SQLEXEC, SQLDBS or SQLDB2 routines.
CLOB
:hv2="'string with embedded delimiting quotation marks ",
"longer than 32K...'"
DBCLOB
:hv3="G'DBCS string with embedded delimiting single ",
"quotation marks, beginning with G, longer than 32K...'"
BLOB
:hv4="BIN'string with embedded delimiting single ",
"quotation marks, beginning with BIN, any length...'"
Declaration of large object locator type host variables in REXX embedded SQL
applications
You must declare LOB locator host variables in your application. When a REXX embedded SQL application
encounters these declarations the host variables are treated as locators for the remainder of the program.
Locator values are stored in REXX variables in an internal format.
The syntax for declaring LOB locator host variables in REXX is:
108 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
,
CLOB
DBCLOB
Example:
Data represented by LOB locators returned from the engine can be freed in REXX/SQL using the FREE
LOCATOR statement which has the following format:
Syntax for FREE LOCATOR statement
,
Example:
CLOB
DBCLOB
Example:
File reference variables in REXX contain three fields. For the preceding example they are:
hv3.FILE_OPTIONS.
Set by the application to indicate how the file will be used.
hv3.DATA_LENGTH.
Set by Db2 to indicate the size of the file.
hv3.NAME.
Set by the application to the name of the LOB file.
For FILE_OPTIONS, the application sets the following keywords:
Keyword (integer value)
Meaning
READ (2)
File is to be used for input. This is a regular file that can be opened, read and closed. The length of the
data in the file (in bytes) is computed (by the application requester code) upon opening the file.
You should include this statement at the end of LOB applications. Note that you can include it anywhere
as a precautionary measure to clear declarations which might have been left by previous applications,
such as at the beginning of a REXX SQL application.
In the previous example, cmind is examined for a negative value. If it is not negative, the application can
use the returned value of cm. If it is negative, the fetched value is NULL and cm must not be used. The
database manager does not change the value of the host variable in this case.
110 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
• An error detected during the insertion of a group of rows causes all the rows of that group to be
backed out. A group of rows is defined as all the rows inserted through executions of a buffered insert
statement:
– From the beginning of the unit of work,
– Since the statement was prepared (if it is dynamic), or
– Since the previous execution of another updating statement. For a list of statements that close (or
flush) a buffered insert, see the description of buffered inserts in partitioned database environments.
• An inserted row may not be immediately visible to SELECT statements issued after the INSERT by the
same application program, if the SELECT is executed using a cursor.
A buffered INSERT statement is either open or closed. The first invocation of the statement opens the
buffered INSERT, the row is added to the appropriate buffer, and control is returned to the application.
Subsequent invocations add rows to the buffer, leaving the statement open. While the statement is
open, buffers may be sent to their destination partitions, where the rows are inserted into the target
table's partition. If any statement or API that closes a buffered insert is invoked while a buffered INSERT
statement is open (including invocation of a different buffered INSERT statement), or if a PREPARE
statement is issued against an open buffered INSERT statement, the open statement is closed before the
new request is processed. If the buffered INSERT statement is closed, the remaining buffers are flushed.
The rows are then sent to the target partitions and inserted. Only after all the buffers are sent and all the
rows are inserted does the new request begin processing.
If errors are detected during the closing of the INSERT statement, the SQLCA for the new request will be
filled in describing the error, and the new request is not done. Also, the entire group of rows that were
inserted through the buffered INSERT statement since it was opened are removed from the database. The
state of the application will be as defined for the particular error detected. For example:
• If the error is a deadlock, the transaction is rolled back (including any changes made before the
buffered insert section was opened).
• If the error is a unique key violation, the state of the database is the same as before the statement was
opened. The transaction remains active, and any changes made before the statement was opened are
not affected.
For example, consider the following application that is bound with the buffered insert option:
Suppose the file contains 8 000 values, but value 3 258 is not legal (for example, a unique key violation).
Each 1 000 inserts results in the execution of another SQL statement, which then closes the INSERT
INTO t2 statement. During the fourth group of 1 000 inserts, the error for value 3 258 will be detected.
It may be detected after the insertion of more values (not necessarily the next one). In this situation, an
error code is returned for the INSERT INTO t2 statement.
The error may also be detected when an insertion is attempted on table t3, which closes the INSERT
INTO t2 statement. In this situation, the error code is returned for the INSERT INTO t3 statement,
even though the error applies to table t2.
Suppose, instead, that you have 3 900 rows to insert. Before being told of the error on row number 3
258, the application may exit the loop and attempt to issue a COMMIT. The unique-key-violation return
code will be issued for the COMMIT statement, and the COMMIT will not be performed. If the application
wants to COMMIT the 3 000 rows that are in the database thus far (the last execution of EXEC SQL
INSERT INTO t3 ... ends the savepoint for those 3 000 rows), the COMMIT has to be reissued.
Similar considerations apply to ROLLBACK as well.
112 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
– REVOKE
– ROLLBACK
– ROLLBACK TO SAVEPOINT
– RUNSTATS
– SAVEPOINT
– SELECT INTO
– UPDATE
– Execution of any other statement, but not another (looping) execution of the buffered INSERT
– End of application
The following APIs will close an open buffered insert:
– BIND (API)
– REBIND (API)
– RUNSTATS (API)
– REORG (API)
– REDISTRIBUTE (API)
In any of these situations where another statement closes the buffered insert, the coordinator
partition waits until every database partition receives the buffers and the rows are inserted. It
then executes the other statement (the one closing the buffered insert), provided all the rows were
successfully inserted.
The standard interface in a partitioned database environment, (without a buffered insert) loads one row at
a time doing the following steps (assuming that the application is running locally on one of the database
partitions):
1. The coordinator partition passes the row to the database manager that is on the same partition.
2. The database manager uses indirect hashing to determine the database partition where the row
should be placed:
• The target partition receives the row.
• The target partition inserts the row locally.
• The target partition sends a response to the coordinator partition.
3. The coordinator partition receives the response from the target partition.
4. The coordinator partition gives the response to the application.
The insertion is not committed until the application issues a COMMIT.
5. Any INSERT statement containing the VALUES clause is a candidate for buffered insert, regardless of
the number of rows or the type of elements in the rows. That is, the elements can be constants, special
registers, host variables, expressions, functions and so on.
For a given INSERT statement with the VALUES clause, the Db2 SQL compiler might not buffer the
insert based on semantic, performance, or implementation considerations. If you prepare or bind your
application with the INSERT BUF option, ensure that it is not dependent on a buffered insert. This means:
• Errors can be reported asynchronously for buffered inserts, or synchronously for regular inserts. If
reported asynchronously, an insert error might be reported on a subsequent insert within the buffer, or
on the other statement that closes the buffer. The statement that reports the error is not executed. For
example, consider using a COMMIT statement to close a buffered insert loop. The commit reports an
SQLCODE -803 (SQLSTATE 23505) due to a duplicate key from an earlier insert. In this scenario, the
commit is not executed. If you want your application to really commit, for example, some updates that
are performed before it enters the buffered insert loop, you must reissue the COMMIT statement.
• Rows inserted can be immediately visible through a SELECT statement using a cursor without a buffered
insert. With a buffered insert, the rows will not be immediately visible. Do not write your application to
depend on these cursor-selected rows if you precompile or bind it with the INSERT BUF option.
114 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
These examples return data from the XML documents in table CUSTOMER from the sample database.
Example 1: Executing XQuery expressions directly in C and C++ dynamic SQL by prepending the
"XQUERY" keyword
In C and C++ applications, XQuery expressions can be issued in the following way:
Example 2: Executing XQuery expressions in static SQL using the XMLQUERY function and
XMLEXISTS predicate
SQL statements containing the XMLQUERY function can be prepared statically, as follows:
116 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Comments in REXX embedded SQL applications
SQL comments are not supported in REXX applications.
• COBOL (updat.sqb)
The following three examples are from the updat sample. See this sample for a complete program that
shows how to modify table data in COBOL.
The following example shows how to insert table data:
The following example shows how to update table data where job-update is a reference to a host
variable declared in the declaration section of the source code:
Because the number of SQLVAR entries required depends on the number of columns in the result table,
an application must be able to allocate an appropriate number of SQLVAR elements when needed. Use
one of the following methods:
Procedure
• Provide the largest SQLDA (that is, the one with the greatest number of SQLVAR entries) that is
needed. The maximum number of columns that can be returned in a result table is 255. If any of
the columns being returned is either a LOB type or a distinct type, the value in SQLN is doubled, and
the number of SQLVAR entries needed to hold the information is doubled to 510. However, as most
SELECT statements do not even retrieve 255 columns, most of the allocated space is unused.
• Provide a smaller SQLDA with fewer SQLVAR entries. In this case, if there are more columns in the
result than SQLVAR entries allowed for in the SQLDA, no descriptions are returned. Instead, the
database manager returns the number of select list items detected in the SELECT statement. The
application allocates an SQLDA with the required number of SQLVAR entries, then uses the DESCRIBE
statement to acquire the column descriptions.
• When any of the columns returned has a LOB or user defined type, provide an SQLDA with the exact
number of SQLVAR entries.
118 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
What to do next
For all three methods, the question arises as to how many initial SQLVAR entries you should allocate.
Each SQLVAR element uses up 44 bytes of storage (not counting storage allocated for the SQLDATA and
SQLIND fields). If memory is plentiful, the first method of providing an SQLDA of maximum size is easier
to implement.
The second method of allocating a smaller SQLDA is only applicable to programming languages such as C
and C++ that support the dynamic allocation of memory. For languages such as COBOL and FORTRAN that
do not support the dynamic allocation of memory, use the first method.
EXEC SQL
PREPARE STMT INTO :*minsqlda FROM :dstring;
Suppose that the statement contained in dstring is a SELECT statement that returns 20 columns in each
row. After the PREPARE statement (or a DESCRIBE statement), the SQLD field of the SQLDA contains the
number of columns of the result table for the prepared SELECT statement.
The SQLVAR entries in the SQLDA are set in the following cases:
• SQLN >= SQLD and no column is either a LOB or a distinct type.
The first SQLD SQLVAR entries are set and SQLDOUBLED is set to blank.
• SQLN >= 2*SQLD and at least one column is a LOB or a distinct type.
2* SQLD SQLVAR entries are set and SQLDOUBLED is set to 2.
• SQLD <= SQLN < 2*SQLD and at least one column is a distinct type, but there are no LOB columns.
The first SQLD SQLVAR entries are set and SQLDOUBLED is set to blank. If the SQLWARN bind option is
YES, a warning SQLCODE +237 (SQLSTATE 01594) is issued.
The SQLVAR entries in the SQLDA are not set (requiring allocation of additional space and another
DESCRIBE) in the following cases:
• SQLN < SQLD and no column is either a LOB or distinct type.
No SQLVAR entries are set and SQLDOUBLED is set to blank. If the SQLWARN bind option is YES, a
warning SQLCODE +236 (SQLSTATE 01005) is issued.
Allocate SQLD SQLVAR entries for a successful DESCRIBE.
• SQLN < SQLD and at least one column is a distinct type, but there are no LOB columns.
No SQLVAR entries are set and SQLDOUBLED is set to blank. If the SQLWARN bind option is YES, a
warning SQLCODE +239 (SQLSTATE 01005) is issued.
Allocate 2*SQLD SQLVAR entries for a successful DESCRIBE, including the names of the distinct types.
• SQLN < 2*SQLD and at least one column is a LOB.
Procedure
• A fixed-length header, 16 bytes in length, containing fields such as SQLN and SQLD
• A variable-length array of SQLVAR entries, of which each element is 44 bytes in length on 32-bit
platforms, and 56 bytes in length on 64-bit platforms.
What to do next
The number of SQLVAR entries needed for fulsqlda is specified in the SQLD field of minsqlda. Assume
this value is 20. Therefore, the storage allocation required for fulsqlda is:
This value represents the size of the header plus 20 times the size of each SQLVAR entry, giving a total of
896 bytes.
You can use the SQLDASIZE macro to avoid doing your own calculations and to avoid any version-specific
dependencies.
120 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Describing a SELECT statement in a dynamically executed SQL program
After you allocate sufficient space for the second SQLDA (in this example, called fulsqlda), you must
code the application to describe the SELECT statement.
Procedure
Code your application to perform the following steps:
1. Store the value 20 in the SQLN field of fulsqlda (the assumption in this example is that the result
table contains 20 columns, and none of these columns are LOB columns).
2. Obtain information about the SELECT statement using the second SQLDA structure, fulsqlda. Two
methods are available:
• Use another PREPARE statement, specifying fulsqlda instead of minsqlda.
• Use the DESCRIBE statement specifying fulsqlda.
What to do next
Using the DESCRIBE statement is preferred because the costs of preparing the statement a second
time are avoided. The DESCRIBE statement reuses information previously obtained during the prepare
operation to fill in the new SQLDA structure. The following statement can be issued:
After this statement is executed, each SQLVAR element contains a description of one column of the result
table.
Procedure
Code your application to do the following tasks:
1. Analyze each SQLVAR description to determine how much space is required for the value of that
column.
Note that for LOB values, when the SELECT is described, the data type given in the SQLVAR is
SQL_TYP_xLOB. This data type corresponds to a plain LOB host variable, that is, the whole LOB will
be stored in memory at one time. This will work for small LOBs (up to a few MB), but you cannot
use this data type for large LOBs (say 1 GB) because the stack is unable to allocate enough memory.
It will be necessary for your application to change its column definition in the SQLVAR to be either
SQL_TYP_xLOB_LOCATOR or SQL_TYPE_xLOB_FILE. (Note that changing the SQLTYPE field of the
SQLVAR also necessitates changing the SQLLEN field.) After changing the column definition in the
SQLVAR, your application can then allocate the correct amount of storage for the new type.
2. Allocate storage for the value of that column.
3. Store the address of the allocated storage in the SQLDATA field of the SQLDA structure.
What to do next
These steps are accomplished by analyzing the description of each column and replacing the content of
each SQLDATA field with the address of a storage area large enough to hold any values from that column.
The length attribute is determined from the SQLLEN field of each SQLVAR entry for data items that are not
of a LOB type. For items with a type of BLOB, CLOB, or DBCLOB, the length attribute is determined from
the SQLLONGLEN field of the secondary SQLVAR entry.
For a successful FETCH, you could write the application to obtain the data from the SQLDA and display the
column headings. For example:
display_col_titles( sqldaPointer ) ;
After the data is displayed, you should close the cursor and release any dynamically allocated memory.
For example:
The effect of this macro is to calculate the required storage for an SQLDA with n SQLVAR elements.
To create an SQLDA structure with COBOL, you can either embed an INCLUDE SQLDA statement or use
the COPY statement. Use the COPY statement when you want to control the maximum number of SQLVAR
entries and hence the amount of storage that the SQLDA uses. For example, to change the default number
of SQLVAR entries from 1489 to 1, use the following COPY statement:
COPY "sqlda.cbl"
replacing --1489--
by --1--.
The FORTRAN language does not directly support self-defining data structures or dynamic allocation.
No SQLDA include file is provided for FORTRAN, because it is not possible to support the SQLDA as a
data structure in FORTRAN. The precompiler will ignore the INCLUDE SQLDA statement in a FORTRAN
program.
122 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
However, you can create something similar to a static SQLDA structure in a FORTRAN program, and
use this structure wherever an SQLDA can be used. The file sqldact.f contains constants that help in
declaring an SQLDA structure in FORTRAN.
Execute calls to SQLGADDR to assign pointer values to the SQLDA elements that require them.
The following table shows the declaration and use of an SQLDA structure with one SQLVAR element.
COBOL
WORKING-STORAGE SECTION.
77 SALARY PIC S99999V99 COMP-3.
77 SAL-IND PIC S9(4) COMP-5.
integer*2 sqlvar1
parameter ( sqlvar1 = sqlda_header_sz + 0*sqlvar_struct_sz )
124 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Table 17. Db2 SQLDA SQL Types
SQL Column Type SQLTYPE numeric SQLTYPE symbolic name“1” on page 125
value
DATE 384/385 SQL_TYP_DATE / SQL_TYP_NDATE
TIME 388/389 SQL_TYP_TIME / SQL_TYP_NTIME
TIMESTAMP 392/393 SQL_TYP_STAMP / SQL_TYP_NSTAMP
n/a“2” on page 125 400/401 SQL_TYP_CGSTR / SQL_TYP_NCGSTR
BLOB 404/405 SQL_TYP_BLOB / SQL_TYP_NBLOB
CLOB 408/409 SQL_TYP_CLOB / SQL_TYP_NCLOB
DBCLOB 412/413 SQL_TYP_DBCLOB / SQL_TYP_NDBCLOB
VARCHAR 448/449 SQL_TYP_VARCHAR / SQL_TYP_NVARCHAR
CHAR 452/453 SQL_TYP_CHAR / SQL_TYP_NCHAR
LONG VARCHAR 456/457 SQL_TYP_LONG / SQL_TYP_NLONG
n/a“3” on page 125 460/461 SQL_TYP_CSTR / SQL_TYP_NCSTR
VARGRAPHIC 464/465 SQL_TYP_VARGRAPH / SQL_TYP_NVARGRAPH
GRAPHIC 468/469 SQL_TYP_GRAPHIC / SQL_TYP_NGRAPHIC
LONG VARGRAPHIC 472/473 SQL_TYP_LONGRAPH / SQL_TYP_NLONGRAPH
FLOAT 480/481 SQL_TYP_FLOAT / SQL_TYP_NFLOAT
REAL“4” on page 125 480/481 SQL_TYP_FLOAT / SQL_TYP_NFLOAT
DECIMAL“5” on page 125 484/485 SQL_TYP_DECIMAL / SQL_TYP_DECIMAL
INTEGER 496/497 SQL_TYP_INTEGER / SQL_TYP_NINTEGER
SMALLINT 500/501 SQL_TYP_SMALL / SQL_TYP_NSMALL
n/a 804/805 SQL_TYP_BLOB_FILE / SQL_TYPE_NBLOB_FILE
n/a 808/809 SQL_TYP_CLOB_FILE / SQL_TYPE_NCLOB_FILE
n/a 812/813 SQL_TYP_DBCLOB_FILE / SQL_TYPE_NDBCLOB_FILE
n/a 960/961 SQL_TYP_BLOB_LOCATOR / SQL_TYP_NBLOB_LOCATOR
n/a 964/965 SQL_TYP_CLOB_LOCATOR / SQL_TYP_NCLOB_LOCATOR
n/a 968/969 SQL_TYP_DBCLOB_LOCATOR /
SQL_TYP_NDBCLOB_LOCATOR
XML 988/989 SQL_TYP_XML / SQL_TYP_XML
Note: These defined types can be found in the sql.h include file located in the include sub-directory of the
sqllib directory. (For example, sqllib/include/sql.h for the C programming language.)
1. For the COBOL programming language, the SQLTYPE name does not use underscore (_) but uses a hyphen
(-) instead.
2. This is a null-terminated graphic string.
3. This is a null-terminated character string.
4. The difference between REAL and DOUBLE in the SQLDA is the length value (4 or 8).
5. Precision is in the first byte. Scale is in the second byte.
Procedure
To process a variable-list SELECT statement, code your application to do the following steps:
1. Declare an SQLDA.
An SQLDA structure must be used to process varying-list SELECT statements.
2. PREPARE the statement using the INTO clause.
The application then determines whether the SQLDA structure declared has enough SQLVAR elements.
If it does not, the application allocates another SQLDA structure with the required number of SQLVAR
elements, and issues an additional DESCRIBE statement using the new SQLDA.
3. Allocate the SQLVAR elements.
Allocate storage for the host variables and indicators needed for each SQLVAR. This step involves
placing the allocated addresses for the data and indicator variables in each SQLVAR element.
4. Process the SELECT statement.
A cursor is associated with the prepared statement, opened, and rows are fetched using the properly
allocated SQLDA structure.
126 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Saving SQL requests from end users
If the users of your application can issue SQL requests from the application, you might want to save these
requests.
To execute this statement, specify a host variable or an SQLDA structure for the USING clause of the
EXECUTE statement. The contents of the host variable is used to specify the value of EMPNO.
The data type and length of the parameter marker depend on the context of the parameter marker
inside the SQL statement. If the data type of a parameter marker is not obvious from the context of the
statement in which it is used, use a CAST specification to specify the data type. A parameter marker for
which you use a CAST specification is a typed parameter marker. A typed parameter marker is treated like
a host variable of the data type used in the CAST specification. For example, the statement SELECT ?
FROM SYSCAT.TABLES is invalid because the data type of the result column is unknown. However,
the statement SELECT CAST(? AS INTEGER) FROM SYSCAT.TABLES is valid because the CAST
specification indicates that the parameter marker represents an INTEGER value; the data type of the
result column is known.
If the SQL statement contains more than one parameter marker, the USING clause of the EXECUTE
statement must specify one of the following types of information:
• A list of host variables, one variable for each parameter marker
• An SQLDA that has one SQLVAR entry for each parameter marker for non-LOB data types or two SQLVAR
entries per parameter marker for LOB data types
The host variable list or SQLVAR entries are matched according to the order of the parameter markers in
the statement, and the data types must be compatible.
• COBOL (varinp.sqb)
The following example is from the COBOL sample varinp.sqb, and shows how to use a parameter
marker in search and update conditions:
128 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
However, for each programming language there are different methods to issue this command. No matter
which host language, each host variable used in the procedure must be declared to match the data type
which is required.
Client applications and the calling of routines exchange information with procedures through parameters
and result sets. The parameters for procedures are defined by the direction the data is traveling (the
parameter mode).
There are three types of parameters for procedures:
• IN parameters: data passed to the procedure.
• OUT parameters: data returned by the procedure.
• INOUT parameters: data passed to the procedure that is, during procedure execution, replaced by data
to be returned from the procedure.
The mode of parameters and their data types are defined when a procedure is registered with the CREATE
PROCEDURE statement.
In the previous statement inout_median, out_sqlcode, and out_buffer are host variables and medianind,
codeind, and bufferind are null indicator variables.
Note: You can also call stored procedures dynamically by preparing a CALL statement.
( argument )
argument
expression
parameter-name => DEFAULT
NULL
Parameter description
procedure-name
A name of the procedure, which is described in the catalog, that you want to call.
130 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
After you have written a select-statement, you code the SQL statements that define how information will
be passed to your application.
You can think of the result of a select-statement as being a table having rows and columns, much like a
table in the database. If only one row is returned, you can deliver the results directly into host variables
specified by the SELECT INTO statement.
If more than one row is returned, you must use a cursor to fetch them one at a time. A cursor is a named
control structure used by an application program to point to a specific row within an ordered set of rows.
Procedure
For embedded SQL applications, you can use the following techniques to scroll through data that has
been retrieved:
• Keep a copy of the data that has been fetched in the application memory and scroll through it by some
programming technique.
• Use SQL to retrieve the data again, typically by using a second SELECT statement.
Procedure
To keep a copy of the data, your application can do the one of the following tasks:
• Save the fetched data in virtual storage.
• Write the data to a temporary file (if the data does not fit in virtual storage). One effect of this approach
is that a user, scrolling backward, always sees exactly the same data that was fetched, even if the data
in the database was changed in the interim by a transaction.
• Using an isolation level of repeatable read, the data you retrieve from a transaction can be retrieved
again by closing and opening a cursor. Other applications are prevented from updating the data in your
result set. Isolation levels and locking can affect how users update data.
Procedure
You can retrieve data a second time by using any of the following methods:
• Retrieve data from the beginning
To retrieve the data again from the beginning of the result table, close the active cursor and reopen it.
This action positions the cursor at the beginning of the result table. But, unless the application holds
locks on the table, others may have changed it, so what had been the first row of the result table may
no longer be.
• Retrieve data from the middle
Now, suppose that you want to return to the rows that start with DEPTNO = 'M95' and fetch
sequentially from that point. Code the following statement:
To retrieve the same rows in reverse order, specify that the order is descending, as in the following
statement:
A cursor on the second statement retrieves rows in exactly the opposite order from a cursor on the
first statement. Order of retrieval is guaranteed only if the first statement specifies a unique ordering
sequence.
For retrieving rows in reverse order, it can be useful to have two indexes on the DEPTNO column, one in
ascending order, and the other in descending order.
132 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
AND DEPTNO >= 'Z98'
ORDER BY DEPTNO
Because of the subtle relationships between the form of an SQL statement and the values in this
statement, never assume that two different SQL statements will return rows in the same order unless
the order is uniquely determined by an ORDER BY clause.
Procedure
To update previously retrieved data, you can do one of two things:
• If you have a second cursor on the data to be updated and the SELECT statement uses none of the
restricted elements, you can use a cursor-controlled UPDATE statement. Name the second cursor in
the WHERE CURRENT OF clause.
• In other cases, use UPDATE with a WHERE clause that names all the values in the row or specifies
the primary key of the table. You can issue one statement many times with different values of the
variables.
Procedure
To process a cursor:
1. Specify the cursor using a DECLARE CURSOR statement.
2. Perform the query and build the result table using the OPEN statement.
3. Retrieve rows one at a time using the FETCH statement.
4. Process rows with the DELETE or UPDATE statements (if required).
5. Terminate the cursor using the CLOSE statement.
What to do next
An application can use several cursors concurrently. Each cursor requires its own set of DECLARE
CURSOR, OPEN, CLOSE, and FETCH statements.
EXEC SQL DECLARE c1 CURSOR FOR SELECT * FROM staff WHERE id >= 310;
EXEC SQL OPEN c1;
EXEC SQL FETCH c1 INTO :id, :name, :dept, :job:jobInd, :years:yearsInd, :salary,
:comm:commInd;
The sample shows almost all possible cases of table data modification.
• COBOL (openftch.sqb)
The following example is from the sample openftch. This example selects from a table using a cursor,
opens the cursor, and fetches rows from the table.
134 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
• C, C++, and COBOL applications can use the GET ERROR MESSAGE API to obtain the corresponding
information related to the SQLCA passed in.
printf("%s", sqlInfo);
return 1;
}
else
{ sprintf( sqlInfoToken, "--- end warning report ---\n");
strcat( sqlInfo, sqlInfoToken);
printf("%s", sqlInfo);
return 0;
} /* endif */
} /* endif */
return 0;
}
C developers can also use an equivalent function, sqlglm(), which has the signature:
if ( SQLCA.SQLCODE = 0 ) then
return 0
else do
say '--- error report ---'
say 'ERROR occurred :' errloc
say 'SQLCODE :' SQLCA.SQLCODE
/*********************\
* GET ERROR MESSAGE *
\*********************/
call SQLDBS 'GET MESSAGE INTO :errmsg LINEWIDTH 80'
say errmsg
say '--- end error report ---'
136 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
An SQLCODE value of 0 means successful execution (with possible SQLWARN warning conditions). A
positive value means that the statement was successfully executed but with a warning, as with truncation
of a host variable. A negative value means that an error condition occurred.
An additional field, SQLSTATE, contains a standardized error code consistent across other IBM database
products and across SQL92-conformant database managers. Practically speaking, you should use
SQLSTATE values when you are concerned about portability since SQLSTATE values are common across
many database managers.
The first element of the SQLWARN array, SQLWARN0, contains a blank if all other elements are blank.
SQLWARN0 contains a W if at least one other element contains a warning character.
Note: If you want to develop applications that access various IBM RDBMS servers you should:
• Where possible, have your applications check the SQLSTATE rather than the SQLCODE.
• If your applications will use Db2 Connect, consider using the mapping facility provided by Db2 Connect
to map SQLCODE conversions between unlike databases.
Note: The occurrence of an error with an accompanying SQLSTATE value of class code 40 indicates
that the error has resulted in the rollback of the transaction and the release of any locks held by the
transaction. Errors occurring with other SQLSTATE class code values will not result in a rollback of the
transaction nor the release of locks held by the transaction. See SQLSTATE Messages.
Applications that are precompiled with the COMPATIBILITY_MODE ORA option can issue one of the
following statements to achieve the ROLLBACK operation along with the disconnect operation in a single
statement:
When working with FORTRAN applications, a database connection is closed by issuing the following
statement:
138 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
The following example demonstrates the array INSERT through COBOL.
Identification Division.
Program-ID. "arrayfetch".
Data Division.
Working-Storage Section.
copy "sqlca.cbl".
Procedure Division.
Main Section.
display "Sample COBOL program: ARRAY INSERT".
MOVE 5 to cnt.
MOVE "Row1" to c1(1).
MOVE "Row2" to c1(2).
MOVE "Row3" to c1(3).
MOVE "Row4" to c1(4).
MOVE "Row5" to c1(5).
MOVE 1 to c2(1).
move 10 to c2(2).
MOVE 50 to c2(3).
MOVE 100 to c2(4).
MOVE 500 to c2(5).
EXEC SQL INSERT INTO test VALUES (:c2, :c1
) FOR :cnt ROWS END-EXEC.
End-Prog.
stop run.
Identification Division.
Program-ID. "openftch".
Data Division.
Working-Storage Section.
copy "sqlca.cbl".
EXEC SQL BEGIN DECLARE SECTION END-EXEC.
01 dept-rec.
Procedure Division.
Main Section.
display "Sample COBOL program: OPENFTCH".
MOVE 5 TO cnt.
EXEC SQL DECLARE c1 CURSOR FOR SELECT name, dept 1
FROM staff
WHERE job='Mgr' END-EXEC.
Fetch-Loop Section.
EXEC SQL FETCH c1 FOR :cnt ROWS
INTO :pname,
:dept END-EXEC.
End-Fetch-Loop. exit.
End-Prog.
stop run.
01 Monthly-sales-rec.
03 Monthly-sales pic s9(9) comp-5 OCCURS 12 TIMES.
140 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
The previous declartion specifices 12 fields, all of which have the same PIC. The individual fields are
referenced by using subscripts such as MONTHLY-SALES(1).
Restrictions
• The Multi-row fetch and array INSERT do not support the LOB array's. The Db2 precompiler
throws SQL1727N error, if the application uses the LOB array’s in INSERT/UPDATE/DELETE/FETCH
statements.
• The Multi-row fetch and array insert do not support table of records (array of structure).
• The Db2 precompiler throws SQL0104N error if the application uses the NON-ATOMIC keyword in
the INSERT statement because the Db2 server does not support this keyword.
• The Db2 embedded SQL supports running the array insert/update/delete operations in atomic mode
only.
• The Db2 Precompiler does not consider the declaration of array of structure/record.
• The Db2 server and client does not support ROWSET cursors. Hence the Db2 precompiler strips off
the WITH ROWSET POSITIONING keyword from the DECLARE CURSOR statement, and the NEXT
ROWSET keyword from the FETCH statement.
144 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
If your application uses a code page that is not the same as your database code page, you need to
consider which code page to use when precompiling.
If your application uses user-defined functions (UDFs) or user-defined distinct types (UDTs), you might
need to use the FUNCPATH parameter when you precompile your application. This parameter specifies
the function path that is used to resolve UDFs and UDTs for applications containing static SQL. If
FUNCPATH is not specified, the default function path is SYSIBM, SYSFUN, USER, where USER refers
to the current user ID.
Before precompiling an application you must connect to a server, either implicitly or explicitly. Although
you precompile application programs at the client workstation and the precompiler generates modified
source and messages on the client, the precompiler uses the server connection to perform some of the
validation.
The precompiler also creates the information the database manager needs to process the SQL statements
against a database. This information is stored in a package, in a bind file, or in both, depending on the
precompiler options selected.
A typical example of using the precompiler follows. To precompile a C embedded SQL source file called
filename.sqc, you can issue the following command to create a C source file with the default name
filename.c and a bind file with the default name filename.bnd:
Restriction: The byte order mark (BOM) with UTF-8 for a C embedded SQL source file is not supported.
The precompiler generates up to four types of output:
Modified Source
This file is the new version of the original source file after the precompiler converts the SQL
statements into Db2 runtime API calls. It is given the appropriate host language extension.
Package
If you use the PACKAGE parameter (the default), or do not specify any of the BINDFILE, SYNTAX,
or SQLFLAG parameters, the package is stored in the connected database. The package contains
all the information required to issue the static SQL statements of a particular source file against
this database only. Unless you specify a different name with the PACKAGE USING parameter, the
precompiler forms the package name from the first 8 characters of the source file name.
If you use the PACKAGE parameter without SQLERROR CONTINUE, the database used during the
precompile process must contain all of the database objects referenced by the static SQL statements
in the source file. For example, you cannot precompile a SELECT statement unless the table it
references exists in the database.
With the VERSION parameter, the bind file (if the BINDFILE parameter is used) and the package
(either if bound at PREP time or if bound separately) is designated with a particular version identifier.
Many versions of packages with the same name and creator can exist at once.
Bind File
If you use the BINDFILE parameter, the precompiler creates a bind file (with extension .bnd) that
contains the data required to create a package. This file can be used later with the BIND command
to bind the application to one or more databases. If you specify BINDFILE and do not specify
the PACKAGE parameter, binding is deferred until you invoke the BIND command. Note that for the
command line processor (CLP), the default for PREP does not specify the BINDFILE parameter. Thus,
if you are using the CLP and want the binding to be deferred, you need to specify the BINDFILE
parameter.
Specifying SQLERROR CONTINUE creates a package, even if errors occur when binding SQL
statements. Those statements that fail to bind for authorization or existence reasons can be
incrementally bound at execution time if VALIDATE RUN is also specified. Any attempt to issue them
at run time generates an error.
146 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
You can also group packages for general administration purposes, or to provide variations in the packages
(for example, maintaining backup variations of applications, or testing new variations of applications).
When multiple schemas are used for packages, the database manager must determine in which schema
to look for a package. To accomplish this task, the database manager uses the value of the CURRENT
PACKAGESET special register. You can set this special register to a single schema name to indicate that
any package to be invoked belongs to that schema. If an application uses packages in different schemas,
a SET CURRENT PACKAGESET statement might have to be issued before each package is invoked if the
schema for the package is different from that of the previous package.
Note: Only Db2 for z/OS Version 9.1 has a CURRENT PACKAGESET special register, which allows you
to explicitly set the value (a single schema name) with the corresponding SET CURRENT PACKAGESET
statement. Although Db2 has a SET CURRENT PACKAGESET statement, it does not have a CURRENT
PACKAGESET special register. This means that CURRENT PACKAGESET cannot be referenced in other
contexts (such as in a SELECT statement) with Db2. Db2 for IBM i does not provide support for CURRENT
PACKAGESET.
The Db2 database server has more flexibility when it can consider a list of schemas during package
resolution. The list of schemas is similar to the SQL path that is provided by the CURRENT PATH special
register. The schema list is used for user-defined functions, procedures, methods, and distinct types.
Note: The SQL path is a list of schema names that Db2 should consider when trying to determine the
schema for an unqualified function, procedure, method, or distinct type name.
If you need to associate multiple variations of a package (that is, multiple sets of BIND options for a
package) with a single compiled program, consider isolating the path of schemas that are used for SQL
objects from the path of schemas that are used for packages.
The CURRENT PACKAGE PATH special register allows you to specify a list of package schemas. Other Db2
family products provide similar capability with special registers such as CURRENT PATH and CURRENT
PACKAGESET, which are pushed and popped for nested procedures and user-defined functions without
corrupting the runtime environment of the invoking application. The CURRENT PACKAGE PATH special
register provides this capability for package schema resolution.
Many installations use more than one schema for packages. If you do not specify a list of package
schemas, you must issue the SET CURRENT PACKAGESET statement (which can contain at most one
schema name) each time you require a package from a different schema. If, however, you issue a SET
CURRENT PACKAGE PATH statement at the beginning of the application to specify a list of schema names,
you do not need to issue a SET CURRENT PACKAGESET statement each time a package in a different
schema is needed.
For example, assume that the following packages exist, and, using the following list, that you want
to invoke the first one that exists on the server: SCHEMA1.PKG1, SCHEMA2.PKG2, SCHEMA3.PKG3,
SCHEMA.PKG, and SCHEMA5.PKG5. Assuming the current support for a SET CURRENT PACKAGESET
statement in Db2 (that is, accepting a single schema name), a SET CURRENT PACKAGESET statement
have to be issued before trying to invoke each package to specify the specific schema. For this example,
five SET CURRENT PACKAGESET statements need to be issued. However, using the CURRENT PACKAGE
PATH special register, a single SET statement is sufficient. For example:
Note: In Db2, you can set the CURRENT PACKAGE PATH special register in the db2cli.ini file, by using
the SQLSetConnectAttr API, in the SQLE-CLIENT-INFO structure, and by including the SET CURRENT
PACKAGE PATH statement in embedded SQL programs. Only Db2 for z/OS, Version 8 or later, supports the
SET CURRENT PACKAGE PATH statement. If you issue this statement against a Db2 server or against Db2
for IBM i, -30005 is returned.
You can use multiple schemas to maintain several variations of a package. These variations can be a
very useful in helping to control changes made in production environments. You can also use different
variations of a package to keep a backup version of a package, or a test version of a package (for example,
to evaluate the impact of a new index). A previous version of a package is used in the same way as a
If you need to revert to the previous version of the package, the production version of the application can
be dropped with the DROP PACKAGE statement, which causes the old version of the application (load
module or executable) that was bound using the BACKUP schema to be invoked instead (application path
techniques could be used here, specific to each operating system platform).
Note: This example assumes that the only difference between the versions of the package are in the BIND
options that were used to create the packages (that is, there are no differences in the executable code).
The application does not use the SET CURRENT PACKAGESET statement to select the schema it wants.
Instead, it allows Db2 to pick up the package by checking for it in the schemas listed in the CURRENT
PACKAGE PATH special register.
Note: The Db2 for z/OS precompile process stores a consistency token in the DBRM (which can be set
using the LEVEL option), and during package resolution a check is made to ensure that the consistency
token in the program matches the package. Similarly, the Db2 bind process stores a timestamp in the bind
file. Db2 also supports a LEVEL option.
Another reason for creating several versions of a package in different schemas could be to cause different
BIND options to be in affect. For example, you can use different qualifiers for unqualified name references
in the package.
Applications are often written with unqualified table names. This supports multiple tables that have
identical table names and structures, but different qualifiers to distinguish different instances. For
example, a test system and a production system might have the same objects created in each, but
they might have different qualifiers (for example, PROD and TEST). Another example is an application
that distributes data into tables across different Db2 systems, with each table having a different qualifier
(for example, EAST, WEST, NORTH, SOUTH; COMPANYA, COMPANYB; Y1999, Y2000, Y2001). With Db2
for z/OS, you specify the table qualifier using the QUALIFIER option of the BIND command. When you
use the QUALIFIER option, users do not have to maintain multiple programs, each of which specifies
the fully qualified names that are required to access unqualified tables. Instead, the correct package can
be accessed at runtime by issuing the SET CURRENT PACKAGESET statement from the application, and
specifying a single schema name. However, if you use SET CURRENT PACKAGESET, multiple applications
will still need to be kept and modified: each one with its own SET CURRENT PACKAGESET statement to
access the required package. If you issue a SET CURRENT PACKAGE PATH statement instead, all of the
schemas could be listed. At execution time, Db2 could choose the correct package.
Note: Db2 also supports a QUALIFIER bind option. However, the QUALIFIER bind option only affects
static SQL or packages that use the DYNAMICRULES option of the BIND command.
148 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Precompiler generated timestamps
When an application is precompiled with binding enabled, the package and modified source file are
generated with matching timestamps. These timestamps are individually known as a consistency token.
If multiple versions of a package exist (by using the PRECOMPILE VERSION option), each version will have
an associated timestamp. When the application is run, the package name, creator and timestamp are
sent to the database manager, which checks for a package whose name, creator and timestamp match
that sent by the application. If such a match does not exist, one of the two following SQL error codes is
returned to the application:
• SQL0818N (timestamp conflict). This error is returned if a single package is found that matches the
name and creator (but not the consistency token), and the package has a version of "" (an empty string)
• SQL0805N (package not found). This error is returned in all other situations.
Remember that when you bind an application to a database, the first eight characters of the application
name are used as the package name unless you override the default by using the PACKAGE USING
parameter on the PREP command. As well, the version ID will be "" (an empty string) unless it is specified
by the VERSION parameter of the PREP command. This means that if you precompile and bind two
programs using the same name without changing the version ID, the second package will replace the
package of the first. When you run the first program, you will get a timestamp or a package not found
error because the timestamp for the modified source file no longer matches that of the package in the
database. The package not found error can also result from the use of the ACTION REPLACE REPLVER
precompile or bind option as in the following example:
1. Precompile and bind the package SCHEMA1.PKG specifying VERSION VER1. Then generate the
associated application A1.
2. Precompile and bind the package SCHEMA1.PKG, specifying VERSION VER2 ACTION REPLACE
REPLVER VER1. Then generate the associated application A2.
The second precompile and bind generates a package SCHEMA1.PKG that has a VERSION of VER2, and
the specification of ACTION REPLACE REPLVER VER1 removes the SCHEMA1.PKG package that had a
VERSION of VER1.
An attempt to run the first application will result in a package mismatch and will fail.
A similar symptom will occur in the following example:
1. Precompile and bind the package SCHEMA1.PKG, specifying VERSION VER1. Then generate the
associated application A1
2. Precompile and bind the package SCHEMA1.PKG, specifying VERSION VER2. Then generate the
associated application A2
At this point it is possible to run both applications A1 and A2, which will be executed from packages
SCHEMA1.PKG versions VER1 and VER2. If, for example, the first package is dropped (using the DROP
PACKAGE SCHEMA1.PKG VERSION VER1 SQL statement), an attempt to run the application A1 will fail
with a package not found error.
When a source file is precompiled but a package is not created, a bind file and modified source file are
generated with matching timestamps. To run the application, the bind file is bound in a separate BIND
step to create a package and the modified source file is compiled and linked. For an application that
requires multiple source modules, the binding process must be done for each bind file.
In this deferred binding scenario, the application and package timestamps match because the bind
file contains the same timestamp as the one that was stored in the modified source file during
precompilation.
150 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
bind. At run time, when the package is first loaded, the database manager uses the current session
environment (rather than the package) to set up the section entries and other entities (text is populated
and the package cache is accessed). Thereafter, the statements in the bound file behave the same
as they would if you were using dynamic SQL. For example, sections will be implicitly recompiled for
Database Definition Language invalidations, special register updates, and so on. The Db2 database
manager provides this feature to facilitate the migration of embedded SQL C applications from other
database systems.
The following table shows the combination of the DYNAMICRULES value and the runtime environment that
yields each dynamic SQL behavior.
Table 18. How DYNAMICRULES and the Runtime Environment Determine Dynamic SQL Statement Behavior
DYNAMICRULES Value Behavior of Dynamic SQL Behavior of Dynamic SQL Statements
Statements in a Standalone in a Routine Environment
Program Environment
BIND Bind behavior Bind behavior
RUN Run behavior Run behavior
DEFINEBIND Bind behavior Define behavior
DEFINERUN Run behavior Define behavior
INVOKEBIND Bind behavior Invoke behavior
INVOKERUN Run behavior Invoke behavior
The following table shows the dynamic SQL attribute values for each type of dynamic SQL behavior.
152 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Table 19. Definitions of Dynamic SQL Statement Behaviors (continued)
Dynamic SQL Setting for Setting for Setting for Dynamic Setting for Dynamic
Attribute Dynamic SQL Dynamic SQL SQL Attributes: SQL Attributes: Invoke
Attributes: Bind Attributes: Run Define Behavior Behavior
Behavior Behavior
Can execute No Yes No No
GRANT, REVOKE,
ALTER, CREATE,
DROP,
COMMENT ON,
RENAME, SET
INTEGRITY, and
SET EVENT
MONITOR STATE
Package recreation using the BIND command and an existing bind file
Binding is the process that creates the package the database manager needs to access the database
when the application is executed.
By default the PRECOMPILE command creates a package. Binding is done implicitly at precompile time
unless the BINDFILE command parameter is specified. The PACKAGE command parameter allows you to
specify a package name for the package created at precompile time.
A typical example of using the BIND command follows. To bind a bind file named filename.bnd to the
database, you can issue the following command:
BIND filename.bnd
One package is created for each separately precompiled source code module. If an application has five
source files, of which three require precompilation, three packages or bind files are created. By default,
each package is given a name that is the same as the name of the source module from which the .bnd file
originated, but truncated to 8 characters. To explicitly specify a different package name, you must use the
PACKAGE USING parameter on the PREP command. The version of a package is given by the VERSION
precompile parameter and defaults to the empty string. If the name and schema of this newly created
package is the same as a package that currently exists in the target database, but the version identifier
differs, a new package is created and the previous package still remains. However if a package exists that
matches the name, schema and the version of the package being bound, then that package is dropped
and replaced with the new package being bound (specifying ACTION ADD on the bind would prevent that
and an error (SQL0719) would be returned instead).
Bind considerations
If your application uses a code page that differs from the database code page, you must ensure that the
code page used by the application is compatible with the database code page during the bind process.
If your application issues calls to any of the database manager utility APIs, such as IMPORT or EXPORT,
you must bind the supplied utility bind files to the database.
You can use bind options to control certain operations that occur during binding, as in the following
examples:
• The QUERYOPT bind parameter takes advantage of a specific optimization class when binding.
• The EXPLSNAP bind parameter stores Explain Snapshot information for eligible SQL statements in the
Explain tables.
• The FUNCPATH bind parameter properly resolves user-defined distinct types and user-defined functions
in static SQL.
If the bind process starts but never returns, it might be that other applications connected to the database
hold locks that you require. In this case, ensure that no applications are connected to the database. If
they are, disconnect all applications on the server and the bind process will continue.
154 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
If your application will access a server using Db2 Connect, you can use the BIND command parameters
available for that server.
Bind files are not compatible with earlier versions of Db2. In mixed-level environments, Db2 can only use
the functions available to the lowest level of the database environment. For example, if a version 8 client
connects to a version 7.2 server, the client will only be able to use version 7.2 functions. As bind files
express the functionality of the database, they are subject to the mixed-level restriction.
If you need to rebind higher-level bind files on lower-level systems, you can:
• Use a lower level IBM data server client to connect to the higher-level server and create bind files which
can be shipped and bound to the lower-level Db2 environment.
• Use a higher-level IBM data server client in the lower-level production environment to bind the higher-
level bind files that were created in the test environment. The higher-level client passes only the options
that apply to the lower-level server.
Blocking considerations
When you want to turn blocking off for an embedded SQL application and the source code is not available,
the application must be rebound using the BIND command and setting the BLOCKING NO clause.
Existing embedded SQL applications must be rebound using the BIND command and setting the
BLOCKING ALL or BLOCKING UNAMBIGUOUS clauses to request blocking (if they are not already bound
in this fashion). Embedded applications will retrieve the LOB values from the server a row at a time, when
a block of rows have been retrieved from the server
156 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
1. Make sure that you have sufficient authority for your IBM mainframe database server management
system:
System z
The authorizations required are:
• SYSADM or
• SYSCTRL or
• BINDADD and CREATE IN COLLECTION NULLID
Note: The BINDADD and the CREATE IN COLLECTION NULLID privileges provide sufficient
authority only when the packages do not already exist. For example, if you are creating them
for the first time.
If the packages already exist, and you are binding them again, then the authority required to
complete the task(s) depends on who did the original bind.
A) If you did the original bind and you are doing the bind again, then having any of the previously
listed authorities will allow you to complete the bind.
B) If your original bind was done by someone else and you are doing the second bind, then you
will require either the SYSADM or the SYSCTRL authorities to complete the bind. Having just the
BINDADD and the CREATE IN COLLECTION NULLID authorities will not allow you to complete
the bind. It is still possible to create a package if you do not have either SYSADM or SYSCTRL
privileges. In this situation you would need the BIND privilege on each of the existing packages
that you intend to replace.
VSE or VM
The authorization required is DBA authority. If you want to use the GRANT option on the bind
command (to avoid granting access to each Db2 Connect package individually), the NULLID user ID
must have the authority to grant authority to other users on the following tables:
• system.syscatalog
• system.syscolumns
• system.sysindexes
• system.systabauth
• system.syskeycols
• system.syssynonyms
• system.syskeys
• system.syscolauth
• system.sysuserauth
On the VSE or VM system, you can issue:
Where DBALIAS, USERID, and PASSWORD apply to the IBM mainframe database server, ddcsmvs.lst
is the bind list file for z/OS, and path represents the location of the bind list file.
For example drive:\sqllib\bnd\ applies to all Windows operating systems, and INSTHOME/
sqllib/bnd/ applies to all Linux and UNIX operating systems, where drive represents the logical
ddcspkgn @bindfile.lst
For example:
ddcspkgn @ddcsmvs.lst
To determine these values for Db2 Connect execute the ddcspkgn utility, for example:
ddcspkgn @ddcsmvs.lst
Optionally, this utility can be used to determine the package name of individual bind files, for example:
ddcspkgn bindfile.bnd
Note:
a. Using the bind option sqlerror continue is required; however, this option is automatically
specified for you when you bind applications using the Db2 tools or the Command Line Processor
(CLP). Specifying this option turns bind errors into warnings, so that binding a file containing errors
can still result in the creation of a package. In turn, this allows one bind file to be used against
multiple servers even when a particular server implementation might flag the SQL syntax of another
to be invalid. For this reason, binding any of the list files ddcsxxx.lst against any particular IBM
mainframe database server should be expected to produce some warnings.
b. If you are connecting to a Db2 database through Db2 Connect, use the bind list db2ubind.lst
and do not specify sqlerror continue, which is only valid when connecting to a IBM mainframe
database server. Also, to connect to a Db2 database, it is recommended that you use the Db2
clients provided and not Db2 Connect.
3. Use similar statements to bind each application or list of applications.
4. If you have remote clients from a previous release of Db2, you might need to bind the utilities on these
clients to Db2 Connect.
158 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Package versioning
If you need to create multiple versions of an application, you can use the VERSION parameter in the
PRECOMPILE command. This option allows multiple versions of the same package name (that is, the
package name and creator name) to coexist.
For example, assume that you have an application called foo1, which is compiled from foo1.sqc.
You would precompile and bind the package foo1 to the database and deliver the application to the
users. The users could then run the application. To make subsequent changes to the application, you
would update foo1.sqc, then repeat the process of recompiling, binding, and sending the application
to the users. If the VERSION parameter was not specified for either the first or second precompilation of
foo1.sqc, the first package is replaced by the second package. Any user who attempts to run the old
version of the application will receive the SQLCODE -818, indicating a mismatched timestamp error.
To avoid the mismatched timestamp error and in order to allow both versions of the application to run
at the same time, use package versioning. As an example, when you build the first version of foo1,
precompile it using the VERSION parameter, as follows:
This first version of the program may now be run. When you build the new version of foo1, precompile it
with the command:
At this point this new version of the application will also run, even if there still are instances of the first
application still executing. Because the package version for the first package is V1.1 and the package
version for the second is V1.2, no naming conflict exists: both packages will exist in the database and both
versions of the application can be used.
You can use the ACTION parameter of the PRECOMPILE or BIND commands with the VERSION parameter
of the PRECOMPILE command. You use the ACTION parameter to control the way in which different
versions of packages can be added or replaced.
Package privileges do not have granularity at the version level. That is, a GRANT or a REVOKE of a package
privilege applies to all versions of a package that share the name and creator. So, if package privileges
on package foo1 were granted to a user or a group after version V1.1 was created, when version V1.2 is
distributed the user or group has the same privileges on version V1.2. This behavior is usually required
because typically the same users and groups have the same privileges on all versions of a package. If you
do not want the same package privileges to apply to all versions of an application, you should not use the
PRECOMPILE VERSION parameter to accomplish package versioning. Instead, you should use different
package names (either by renaming the updated source file, or by using the PACKAGE USING parameter
to explicitly rename the package).
In this example, db_name is the name of the database, user_name is the name of the user, and
file_name is the name of the application that will be bound. Note that user_name and schema_name
are typically the same value. Then use the SET CURRENT PACKAGESET statement to specify which
package to use, and therefore, which qualifiers will be used. If COLLECTION is not specified, then the
Note: By default the bldapp sample scripts for building executables from source code will build 64-bit
executables.
The following table lists the build files by platform and programming language, and the directories where
they are located. In the online documentation, the build file names are hot-linked to the source files in
HTML. The user can also access the text files in the appropriate samples directories.
n/a
IBM COBOL bldapp bldapp.bat
samples/cobol bldrtn bldrtn.bat
160 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Table 21. Build files by language and platform (continued)
AIX Linux Windows
Platform —>
Language
The build files are used in the documentation for building applications and routines because they
demonstrate very clearly the compile and link options that Db2 recommends for the supported compilers.
There are generally many other compile and link options available, and users are free to experiment
with them. See your compiler documentation for all the compile and link options provided. Besides
building the sample programs, developers can also build their own programs with the build files. The
sample programs can be used as templates that can be modified by users to assist in their application
development.
Conveniently, the build files are designed to build a source file with any file name allowed by the compiler.
This is unlike the makefiles, where the program names are hardcoded into the file. The makefiles access
the build files for compiling and linking the programs they make. The build files use the $1 variable
on UNIX and Linux and the %1 variable on Windows operating systems to substitute internally for the
program name. Incremented numbers for these variable names substitute for other arguments that might
be required.
The build files allow for quick and easy experimentation, as each one is suited to a specific kind of
program-building, such as stand-alone applications, routines (stored procedures and UDFs) or more
specialized program types such as multi-connection or multi-threaded programs. Each type of build file is
provided wherever the specific kind of program it is designed for is supported by the compiler.
The object and executable files produced by a build file are automatically overwritten each time a
program is built, even if the source file is not modified. This is not the case when using a makefile.
It means a developer can rebuild an existing program without having to delete previous object and
executable files, or modifying the source.
The build files contain a default setting for the sample database. If the user is accessing another
database, they can simply supply another parameter to override the default. If they are using the other
database consistently, they could hardcode this database name, replacing sample, within the build file
itself.
For embedded SQL programs, except when using the IBM COBOL precompiler on Windows, the build files
call another file, embprep, that contains the precompile and bind steps for embedded SQL programs.
These steps might require the optional parameters for user ID and password, depending on where the
embedded SQL program is being built.
Finally, the build files can be modified by the developer for his or her convenience. Besides changing
the database name in the build file (explained previously) the developer can easily hardcode other
parameters within the file, change compile and link options, or change the default Db2 instance path. The
simple, straightforward, and specific nature of the build files makes tailoring them to your needs an easy
task.
Error-checking utilities
The Db2 Client provides several utility files. The utility files contain functions that you can use for error
checking and printing out error information. Utility files are provided for each language in the samples
directory.
When used with an application program, the error-checking utility files provide helpful error information,
and make debugging a Db2 program much easier. Most of the error-checking utilities use the Db2 APIs
GET SQLSTATE MESSAGE (sqlogstt) and GETERROR MESSAGE (sqlaintp) to obtain pertinent SQLSTATE
and SQLCA information related to problems encountered in program execution. The CLI utility file,
utilcli.c, does not use these Db2 APIs; instead it uses equivalent CLI statements. With all the error-
In order to use the utility functions, the utility file must first be compiled, and then its object file linked
in during the creation of the target program's executable file. Both the makefile and build files in the
samples directories do this for the programs that require the error-checking utilities.
The example demonstrates how the error-checking utilities are used in Db2 programs. The
utilemb.h header file defines the EMB_SQL_CHECK macro for the functions SqlInfoPrint() and
TransRollback():
SqlInfoPrint() checks the SQLCODE and prints out any available information related to the specific
error encountered. It also points to where the error occurred in the source code. TransRollback()
allows the utility file to safely rollback a transaction where an error has occurred. It uses the embedded
SQL statement EXEC SQL ROLLBACK. The example demonstrates how the C program dbuse calls
the utility functions by using the macro, supplying the value "Delete with host variables --
Execute" for the MSG_STR parameter of the SqlInfoPrint() function:
The EMB_SQL_CHECK macro ensures that if the DELETE statement fails, the transaction will be safely
rolled back, and an appropriate error message printed out.
Developers are encouraged to use and expand upon these error-checking utilities when creating their own
Db2 programs.
162 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Building applications and routines written in C and C++
You are provided with build scripts for various operating systems with your Db2 product. You can build
embedded SQL applications in C and C++ with these files. Aside from build scripts that you can use to
build applications, there is a specific bldrtn script provided that you can use to build routines, such as
stored procedures and user defined functions.
For applications and routines written in VisualAge®, configuration files are used to build the applications.
The C application samples provided vary from tutorials to client level or instance level examples, they can
be found in the sqllib/samples/c directory for UNIX and sqllib\samples\c directory for Windows.
AIX C++ embedded SQL and Db2 administrative API applications compile and link
options
The compile and link options for building C++ embedded SQL and Db2 administrative API applications
with the IBM XL C/C++ for AIX compiler are available in the bldapp build script.
164 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Link options:
$CC
The gcc or xlc_r compiler; use the compiler as a front end for the linker.
$EXTRA_C_FLAGS
Contains one of the following flags:
• -m31 on Linux for zSeries only, to build a 32-bit library;
• -m32 on Linux for x86, x64 and POWER, to build a 32-bit library;
• -m64 on Linux for zSeries, POWER, x64, to build a 64-bit library; or
• No value on Linux for IA64, to build a 64-bit library.
-o $1
Specify the executable.
$1.o
Specify the object file.
utilemb.o
If an embedded SQL program, include the embedded SQL utility object file for error checking.
utilapi.o
If a non-embedded SQL program, include the Db2 API utility object file for error checking.
$EXTRA_LFLAG
For 32-bit it contains the value "-Wl,-rpath,$DB2PATH/lib32", and for 64-bit it contains the value
"-Wl,-rpath,$DB2PATH/lib64".
-L$DB2PATH/$LIB
Specify the location of the Db2 static and shared libraries at link-time. For example, for 32-bit:
$HOME/sqllib/lib32, and for 64-bit: $HOME/sqllib/lib64.
-ldb2
Link with the Db2 library.
Refer to your compiler documentation for additional compiler options.
166 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
-debug
Include debugging information.
-out:%1.exe
Specify a filename
%1.obj
Include the object file
utilemb.obj
If an embedded SQL program, include the embedded SQL utility object file for error checking.
utilapi.obj
If not an embedded SQL program, include the Db2 API utility object file for error checking.
db2api.lib
Link with the Db2 library.
bldapp cli_info
cli_info
bldapp tbmod
2. If connecting to another database on the same instance, also enter the database name:
3. If connecting to a database on another instance, also enter the user ID and password of the
database instance:
tbmod
2. If accessing another database on the same instance, enter the executable name and the
database name:
tbmod database
3. If accessing a database on another instance, enter the executable name, database name, and
user ID and password of the database instance:
Procedure
• Building and running embedded SQL applications
There are three ways to build the embedded SQL application, tbmod, from the C
source file tbmod.sqc in sqllib\samples\c, or from the C++ source file tbmod.sqx in
sqllib\samples\cpp:
– If connecting to the sample database on the same instance, enter:
bldapp tbmod
– If connecting to another database on the same instance, also enter the database name:
168 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
– If connecting to a database on another instance, also enter the user ID and password of the
database instance:
tbmod
– If accessing another database on the same instance, enter the executable name and the database
name:
tbmod database
– If accessing a database on another instance, enter the executable name, database name, and user
ID and password of the database instance:
bldmt dbthrds
dbthrds
– If accessing another database on the same instance, enter the executable name and the database
name:
dbthrds database
– If accessing a database on another instance, enter the executable name, database name, and user
ID and password of the database instance:
Example
The following examples show you how to build and run Db2 API and embedded SQL applications.
bldapp cli_info
The result is an executable file, cli_info.exe. You can run the executable file by entering the
executable name (without the extension) on the command line:
cli_info
Procedure
To ensure that the TCP/IP listener is running:
1. Set the environment variable DB2COMM to TCP/IP as follows:
db2set DB2COMM=TCPIP
170 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
2. Update the database manager configuration file with the TCP/IP service name as specified in the
services file:
Each instance has a TCP/IP service name listed in the services file. Ask your system administrator if
you cannot locate it or do not have the file permission to change the services file.
3. Stop and restart the database manager in order for these changes to take effect:
db2stop
db2start
Results
The dbmcon.exe program is created from five files in either the samples\c or samples\cpp
directories:
dbmcon.sqc or dbmcon.sqx
Main source file for connecting to both databases.
dbmcon1.sqc or dbmcon1.sqx
Source file for creating a package bound to the first database.
dbmcon1.h
Header file for dbmcon1.sqc or dbmcon1.sqx included in the main source file, dbmcon.sqc or
dbmcon.sqx, for accessing the SQL statements for creating and dropping a table bound to the first
database.
dbmcon2.sqc or dbmcon2.sqx
Source file for creating a package bound to the second database.
dbmcon2.h
Header file for dbmcon2.sqc or dbmcon2.sqx included in the main source file, dbmcon.sqc or
dbmcon.sqx, for accessing the SQL statements for creating and dropping a table bound to the second
database.
To build the multi-connection sample program, dbmcon.exe, enter:
dbmcon
172 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Link Options:
cob
Use the compiler as a front end for the linker.
-x
Produces an executable program.
-o $1
Specify the executable program.
$1.o
Specify the program object file.
-L$DB2PATH/$LIB
Specify the location of the Db2 runtime shared libraries. For example: $HOME/sqllib/lib32.
-ldb2
Link to the Db2 library.
-ldb2gmf
Link to the Db2 exception-handler library for Micro Focus COBOL.
Refer to your compiler documentation for additional compiler options.
Procedure
• When you precompile your application using the PRECOMPILE command, use the target ibmcob
option.
• Do not use tab characters in your source files.
• You can use the PROCESS and CBL keywords in the first line of your source files to set compile options.
• If your application contains only embedded SQL, but no Db2 API calls, you do not need to use the
pgmname(mixed) compile option. If you use Db2 API calls, you must use the pgmname(mixed)
compile option.
• If you are using the "System z host data type support" feature of the IBM COBOL for Linux on x86
compiler, the Db2 include files for your applications are in the following directory:
$HOME/sqllib/include/cobol_i
If you are building Db2 sample programs using the script files provided, the include file path specified
in the script files must be changed to point to the cobol_i directory and not the cobol_a directory.
If you are NOT using the "System z host data type support" feature of the IBM COBOL for Linux on
x86 compiler, or you are using an earlier version of this compiler, then the Db2 include files for your
applications are in the following directory:
$HOME/sqllib/include/cobol_a
COPY "sql.cbl".
174 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
To build the non-embedded SQL sample program client from the source file client.cbl, enter:
bldapp client
The result is an executable file client. You can run the executable file against the sample database by
entering:
client
Procedure
• There are three ways to build the embedded SQL application, updat, from the source file updat.sqb:
a) If connecting to the sample database on the same instance, enter:
bldapp updat
b) If connecting to another database on the same instance, also enter the database name:
c) If connecting to a database on another instance, also enter the user ID and password of the
database instance:
updat
b) If accessing another database on the same instance, enter the executable name and the database
name:
updat database
c) If accessing a database on another instance, enter the executable name, database name, and user
ID and password of the database instance:
176 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
checkerr.obj
Include the error-checking utility object file.
db2api.lib
Link with the Db2 library.
Refer to your compiler documentation for additional compiler options.
Procedure
• When you precompile your application using the PRECOMPILE command, use the target ibmcob
option.
• Do not use tab characters in your source files.
• You can use the PROCESS and CBL keywords in the first line of your source files to set compile options.
• If your application contains only embedded SQL, but no Db2 API calls, you do not need to use the
pgmname(mixed) compile option. If you use Db2 API calls, you must use the pgmname(mixed)
compile option.
• If you are using the "System z host data type support" feature of the IBM COBOL for Linux on x86
compiler, the Db2 include files for your applications are in the following directory:
$HOME/sqllib/include/cobol_i
If you are building Db2 sample programs using the script files provided, the include file path specified
in the script files must be changed to point to the cobol_i directory and not the cobol_a directory.
$HOME/sqllib/include/cobol_a
COPY "sql.cbl".
Procedure
• When you precompile your application with the Db2 precompiler, and use the command line processor
command db2 prep, use the target ibmcob option.
• Do not use tab characters in your source files.
• Use the PROCESS and CBL keywords in your source files to set compile options. Place the keywords in
columns 8 to 72 only.
• If your application contains only embedded SQL, but no Db2 API calls, you do not need to use the
pgmname(mixed) compile option. If you use Db2 API calls, you must use the pgmname(mixed)
compile option.
• If you are using the "System/390 host data type support" feature of the IBM VisualAge COBOL
compiler, the Db2 include files for your applications are in the following directory:
%DB2PATH%\include\cobol_i
If you are building Db2 sample programs using the batch files provided, the include file path specified
in the batch files must be changed to point to the cobol_i directory and not the cobol_a directory.
If you are NOT using the "System/390 host data type support" feature of the IBM VisualAge COBOL
compiler, or you are using an earlier version of this compiler, then the Db2 include files for your
applications are in the following directory:
%DB2PATH%\include\cobol_a
COPY "sql.cbl".
Procedure
• When you precompile your application using the PRECOMPILE command, use the target mfcob
option.
• Ensure that the LIB environment variable points to %DB2PATH%\lib by using the following command:
set LIB="%DB2PATH%\lib;%LIB%"
• The Db2 COPY files for Micro Focus COBOL reside in %DB2PATH%\include\cobol_mf. Set the
COBCPY environment variable to include the directory as follows:
178 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
set COBCPY="%DB2PATH%\include\cobol_mf;%COBCPY%"
You must ensure that the previously mentioned environment variables are permanently set in the
System settings. This can be checked by going through the following steps:
a) Open the Control Panel
b) Select System
c) Select the Advanced tab
d) Click Environment Variables
e) Check the System variables list for the required environment variables. If not present, add them to
the System variables list
Setting them in either the User settings, at a command prompt, or in a script is insufficient.
What to do next
You must make calls to all Db2 application programming interfaces using calling convention 74. The Db2
COBOL precompiler automatically inserts a CALL-CONVENTION clause in a SPECIAL-NAMES paragraph. If
the SPECIAL-NAMES paragraph does not exist, the Db2 COBOL precompiler creates it, as follows:
Identification Division
Program-ID. "static".
special-names.
call-convention 74 is DB2API.
Also, the precompiler automatically places the symbol DB2API, which is used to identify the calling
convention, after the "call" keyword whenever a Db2 API is called. This occurs, for example, whenever the
precompiler generates a Db2 API runtime call from an embedded SQL statement.
If calls to Db2 APIs are made in an application which is not precompiled, you should manually create a
SPECIAL-NAMES paragraph in the application, similar to that given previously. If you are calling a Db2 API
directly, then you will need to manually add the DB2API symbol after the "call" keyword.
ln -s $COBDIR/lib/libcob* /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobrts.so /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobrts_t.so /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobrts.so.2 /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobrts_t.so.2 /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobcrtn.so /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobcrtn.so.2 /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobmisc.so /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobmisc_t.so /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobmisc.so.2 /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobmisc_t.so.2 /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobscreen.so /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobscreen.so.2 /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobtrace.so /usr/lib
ln -s /opt/lib/mfcobol/lib/libcobtrace_t.so /usr/lib
Procedure
• When you precompile your application using the PRECOMPILE command, use the target mfcob
option.
• You must include the Db2 COBOL COPY file directory in the Micro Focus COBOL environment variable
COBCPY. The COBCPY environment variable specifies the location of the COPY files. The Db2 COPY
files for Micro Focus COBOL reside in sqllib/include/cobol_mf under the database instance
directory.
To include the directory, enter:
– On bash or Korn shell:
export COBCPY=$HOME/sqllib/include/cobol_mf:$COBDIR/cpylib
– On C shell:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/sqllib/lib:$COBDIR/lib
– On C shell:
Results
Note: You might want to set COBCPY, COBDIR, and LD_LIBRARY_PATH in the .bashrc, .kshrc
(depending on shell being used), .bash_profile, .profile (depending on shell being used), or in
the .login. .
Procedure
• When you precompile your application using the PRECOMPILE command, use the target mfcob
option.
• You must include the Db2 COBOL COPY file directory in the Micro Focus COBOL environment
variable COBCPY. The COBCPY environment variable specifies the location of the COPY files. The Db2
COPY files for Micro Focus COBOL are in sqllib/include/cobol_mf under the database instance
directory.
180 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
To include the directory, enter:
– On bash or Korn shell:
export COBCPY=$COBCPY:$HOME/sqllib/include/cobol_mf
– On C shell:
Note: You might want to set COBCPY in the .profile or .login file.
bldapp client
The result is an executable file client. You can run the executable file against the sample database by
entering:
client
Procedure
• There are three ways to build the embedded SQL application, updat, from the source file updat.sqb:
a) If connecting to the sample database on the same instance, enter:
bldapp updat
b) If connecting to another database on the same instance, also enter the database name:
c) If connecting to a database on another instance, also enter the user ID and password of the
database instance:
b) If accessing another database on the same instance, enter the executable name and the database
name:
updat database
c) If accessing a database on another instance, enter the executable name, database name, and user
ID and password of the database instance:
bldapp client
The result is an executable file client. You can run the executable file against the sample database by
entering:
client
Procedure
• There are three ways to build the embedded SQL application, updat, from the source file updat.sqb:
a) If connecting to the sample database on the same instance, enter:
bldapp updat
b) If connecting to another database on the same instance, also enter the database name:
c) If connecting to a database on another instance, also enter the user ID and password of the
database instance:
182 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
updat
b) If accessing another database on the same instance, enter the executable name and the database
name:
updat database
c) If accessing a database on another instance, enter the executable name, database name, and user
ID and password of the database instance:
bldapp client
The result is an executable file client.exe. You can run the executable file against the sample
database by entering the executable name (without the extension):
client
Procedure
• There are three ways to build the embedded SQL application, updat, from the source file updat.sqb:
a) If connecting to the sample database on the same instance, enter:
bldapp updat
c) If connecting to a database on another instance, also enter the user ID and password of the
database instance:
updat
b) If accessing another database on the same instance, enter the executable name and the database
name:
updat database
c) If accessing a database on another instance, enter the executable name, database name, and user
ID and password of the database instance:
bldapp client
The result is an executable file client.exe. You can run the executable file against the sample
database by entering the executable name (without the extension):
client
Procedure
• There are three ways to build the embedded SQL application, updat, from the source file updat.sqb:
184 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
a) If connecting to the sample database on the same instance, enter:
bldapp updat
b) If connecting to another database on the same instance, also enter the database name:
c) If connecting to a database on another instance, also enter the user ID and password of the
database instance:
updat
b) If accessing another database on the same instance, enter the executable name and the database
name:
updat database
c) If accessing a database on another instance, enter the executable name, database name, and user
ID and password of the database instance:
Procedure
To build and run your REXX applications:
• On Windows operating systems, your application file can have any name. After creation, you can run
your application from the operating system command prompt by invoking the REXX interpreter as
follows:
REXX file_name
• On AIX, you can run your application using either of the following two methods:
– At the shell command prompt, type rexx name where name is the name of your REXX program.
– If the first line of your REXX program contains a "magic number" (#!) and identifies the directory
where the REXX/6000 interpreter resides, you can run your REXX program by typing its name at the
shell command prompt. For example, if the REXX/6000 interpreter file is in the /usr/bin directory,
include the following line as the very first line of your REXX program:
#! /usr/bin/rexx
chmod +x name
Run your REXX program by typing its file name at the shell command prompt.
Note: On AIX, you should set the LIBPATH environment variable to include the directory where the
REXX SQL library, db2rexx is located. For example:
export LIBPATH=/lib:/usr/lib:/$DB2PATH/lib
186 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
On Windows, REXX programs are not required to start with a comment. However, for portability reasons
you are recommended to start each REXX program with a comment that begins in the first column of the
first line. This will allow the program to be distinguished from a batch command on other platforms:
rexx updat.cmd
Procedure
1. Precompile the application by issuing the PRECOMPILE command.
For example:
The PRECOMPILE command generates a .c or .C file, that contains a modified form of the source code
in a .sqc or .sqC file, and an application package. If you use the BINDFILE option, the PRECOMPILE
command generates a bind file. In the preceding example, the bind file would be called myapp.bnd.
The BIND command associates the application package with and stores the package within the
database.
3. Compile the modified application source and the source files that do not contain embedded SQL to
create an application object file (a .obj file).
For example:
4. Link the application object files with the Db2 and host language libraries to create an executable
program using the link command.
For example:
188 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Chapter 5. Deploying and running embedded SQL
applications
Embedded SQL applications are portable and can be placed in remote database components. You can
compile the application in one location and run the package on a different component.
connectionLevelLoadBalancing <database> Must be set to true if you want to use transaction-level workload
balancing. The value is true by default. However, the default is false if
the server accessed is Db2 for z/OS .
maxTransportIdleTime <wlb> Specifies the maximum elapsed time in number of seconds before an idle
transport is dropped. The default is 60 seconds. The minimum supported
value is 0.
maxTransportWaitTime <wlb> Specifies the number of seconds that the client waits for a transport to
become available. The default is 1 second. The minimum supported value
is 0 and -1 is used to specify unlimited value.
maxTransports <wlb> Specifies the maximum number of physical connections that can be
made for each application process that connects to the Db2 pureScale®
instance. The default is -1 (unlimited). However, the default is 1000 if the
server accessed is Db2 for z/OS.
maxRefreshInterval <wlb> Specifies the maximum elapsed time in number of seconds before
the server list is refreshed. The default is 10 seconds. The minimum
supported value is 0.
maxAcrRetries The maximum number of connection retries for automatic client reroute.
The registry variable DB2_MAX_CLIENT_CONNRETRIES overrides this
value. If DB2_MAX_CLIENT_CONNRETRIES is not set, the default is that
the connection is tried again for 10 minutes. A value of 0 means that one
attempt at reconnection is made. If the server accessed isDb2 for z/OS,
the maxAcrRetries is recommended to be set to no higher than 5.
alternateserverlist Specifies a set of server names and port numbers that identify alternate
servers to which a connection is attempted if a failure occurs on the first
connection to the database. The alternate server list is not used after the
first connection. In a Db2 pureScale environment, the entries in the list
can be members of a Db2 pureScale instance. In a non-Db2 pureScale
environment, there is an entry for the primary server and an entry for the
high availability disaster recovery (HADR) standby server. The alternate
server list is not used after the first connection.
affinityFailbackInterval The number of seconds to wait after the first transaction boundary to fail
back to the primary server. Set this value if you want to fail back to the
primary server. The default is 0, which means that no attempt is made to
fail back to the primary server.
clientaffinitydefined <client> elements that define the server order for automatic client
reroute for each client. Each <client> element contains a listname
attribute that associates a client with a <list> element from the
<affinitylist> element.
You can use the IBM data server driver configuration file (db2dsdriver.cfg) to set the client
information registers. You can set the client information register keywords in the <dsn>, <database>,
or <parameters> section of the IBM data server driver configuration file. The list of supported IBM data
server driver keywords for client information are listed in Table 3.
Table 25. Supported client information keywords
Keywords Header
ClientCorrelationToken1 Sets the client correlation token that is sent to a Db2 for z/OS Version 11
server in new function mode (NFM).
ClientUserID Sets the client user ID (accounting user ID) that is sent to a database.
The ClientUserID keyword is for identification purposes only and is
not used for any authentication.
ClientWorkstationName Sets the client workstation name that is sent to a database server.
enableDefaultClientInfo1 Specifies whether the default client information register values, which
are set on the Db2 for z/OS server, are returned to the application.
1 You can set the specified keyword only when you are connecting to the Db2 for z/OS server.
190 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
The embedded SQL application cannot perform seamless failover. Also, the ability to resolve the data
source name (DSN) with <dsncollection> section entry in the db2dsdriver.cfg file is only supported
with IBM Data Server Driver Package.
IBM data server clients supports the use of the <dsncollection> section entry in the db2dsdriver.cfg
file to resolve DSN entry.
The following steps outline the process involved with database alias resolution:
1. The embedded SQL application requests to CONNECT to the database alias.
2. The embedded SQL application looks up the catalog database directory to see if the specified
database alias name exists.
• If information is found, the embedded application uses the database name, host name, and port
number information from the catalog. Proceed to step 4.
• If information is not found, the <dsncollection> sections in the db2dsdriver.cfg file is used to
resolve the database alias name to the database name, host name, and port number information.
3. The application looks for database alias information in the db2dsdriver.cfg file:
• If database alias information is not found, a database connection error is returned to the embedded
SQL application.
• If database alias information is found, the database name, host name, port number, and data server
driver parameters that are specified in the <dsn> section are used.
4. Using the database name, host name, and port number, the <databases> section for matching entry is
searched.
5. If a matching entry for the database name, host name, and port number is found in the <databases>
section, the parameters specified under the matching <database> section is applied to the connection.
6. The database connection is attempted with information that is specified in the catalog and
db2dsdriver.cfg file.
In Db2 Version 9.7 Fix Pack 6 and later fix packs, the embedded SQL application can use following
timeout values and connection parameters in the db2dsdriver.cfg file:
• MemberConnectTimeout
• ReceiveTimeout
• TcpipConnectTimeout
• keepAliveTimeOut
• ConnectionTimeout
• CommProtocol
• Authentication
• SSLClientLabel
• TargetPrincipal
• SecurityTransportMode
• SSLclientkeystoredb
• SSLclientkeystash
• SSLClientKeystoredbPassword
Any unrecognized data server keywords are ignored silently by the embedded SQL application.
Attention: In Db2 11.5.6 and newer versions, the SSLServerCertificate keyword is supported
through the db2dsdriver.cfg file.
192 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Chapter 6. Compatibility features for migration
The Db2 database manager provides features that facilitate the migration of embedded SQL C
applications from other database systems.
You can enable these compatibility features by setting the precompiler option COMPATIBILITY_MODE to
ORA. For example, the following command enables the compatibility features when you compile the file
named tbsel.sqc:
The following features are supported when the COMPATIBILITY_MODE ORA precompile option is
specified:
• Ability to specify the RELEASE option with EXEC SQL ROLLBACK and EXEC SQL COMMIT statements.
• Enhanced CONNECT statement syntax.
• Simple type definition for the VARCHAR type.
• Suppression of unspecified indicator variable error when the required NULL indicator is not specified
and the UNSAFENULL YES option of the PRECOMPILE command is not set.
• Use of anonymous block to call a stored procedure.
• Use of C and C++ host variable arrays for FETCH INTO, INSERT, UPDATE, and DELETE statements that
are non-dynamic.
• Use of double quotation marks to specify file names with the INCLUDE statement.
• Use of INDICATOR variable arrays for FETCH INTO, INSERT, UPDATE, and DELETE statements that are
non-dynamic.
• Use of structure type, structure arrays, and structure indicator arrays.
Additionally, the following features are supported for C or C++ embedded SQL applications even if you do
not issue the PRECOMPILE command with the COMPATIBILITY_MODE ORA option:
• Use of the STATICASDYNAMIC string for the GENERIC parameter of the BIND command to provide true
dynamic SQL behavior for the package that is bound in a session.
• Use of a string literal with the PREPARE statement.
• Use of three-part name to call a stored procedure.
• Use of WHENEVER condition DO action statement.
while (1) {
EXEC SQL FETCH empcr INTO :empno :lastname; /* bulk fetch */
... /* 100 or less rows */
...
}
194 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
end_fetch:
EXEC SQL CLOSE empcr;
...
// Populating the arrays.
for ( i = 0; i < 3; i++)
{
arr_in1[i] = 100 + i;
sprintf(arr_in2[i], "hello%d", arr_in1[i]);
}
// The INSERT operation was successful and 3 rows has been stored in database.
printf(“sqlca.sqlerrd[2] = %d\n”, sqlca.sqlerrd[2] ); // 3
...
// Populating the arrays.
for ( i = 0; i < 3; i++)
{
arr_in1[i] = 100 + i;
}
arr_in2[0] = 1000;
arr_in2[1] = 1001;
196 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
– CLOB file reference
– CLOB locator variable
– User-defined data type
– XML
• FOR N ROWS clause can be used to specify the cardinality for INSERT and MERGE statement, where N
can be an integer or a host variable of type int or short. If array host variables are used, it will take the
minimum cardinality value among all the host variables that are used in the SQL.
• Host variable array support is not provided for Db2 for z/OS and Db2 for i servers.
The inout_median, out_sqlcode, and out_buffer are host variables and medianind, codeind, and bufferind
are null indicator variables.
Remember: The embedded SQL applications do not support returning the values from a stored
procedure.
When you set the precompiler option COMPATIBILITY_MODE to ORA, you can also specify the following
CONNECT statement syntax:
You can use only single quotation marks without setting the precompiler option COMPATIBILITY_MODE
to ORA.
198 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
WHERE workdept = 'D21';
while (1) {
EXEC SQL FETCH empcr INTO :empno :lastname :edlevel,
:bonus INDICATOR :bonus_ind
...
...
}
end_fetch:
EXEC SQL CLOSE empcr;
Instead of being identified by the INDICATOR keyword, an indicator variable can immediately follow its
corresponding host variable, as shown in the following example:
In the following example, the indicator variable arrays ind_in1 and ind_in2 are declared. It can have up to
three elements, the same cardinality as the arr_in1 and arr_in2 array variables. If the value of ind_in1 or
ind_in2 is negative, the NULL value is inserted for the corresponding arr_in1 or arr_in2 value.
// Declare host & indicator variablesof array size 3
EXEC SQL BEGIN DECLARE SECTION;
sqlint32 arr_in1[3];
char arr_in2[3][11];
short ind_in1[3]; // indicator array size is same as host
// variable’s array size
short ind_in2[3]; // note here indicator array size is greater
// than host variable’s array size
EXEC SQL END DECLARE SECTION;
...
// Populating the arrays.
for ( i = 0; i < 3; i++)
{
arr_in1[i] = i + 1;
sprintf(arr_in2[i], "hello%d", arr_in1[i]);
}
ind_in1[0] = 0;
ind_in1[1] = SQL_NULL_DATA; // Mark it as a NULL data
ind_in1[2] = 0;
ind_in2[0] = 0;
ind_in2[1] = 0;
ind_in2[2] = SQL_NULL_DATA; // Mark it as a NULL data
If the cardinality of indicator variable array does not match the cardinality of the corresponding host
variable array, an error is returned.
In the following example, the indicator structure array MyStructInd is declared.
struct MyStructInd
{
short c1_ind;
short c2_ind;
} MyStructVarInd[3];
EXEC SQL END DECLARE SECTION;
...
Remember: The PRECOMPILE command returns the SQL1696N error if you use the new syntax without
setting the COMPATIBILITY_MODE parameter to ORA.
Description
The command line process command BIND contains the GENERIC parameter. The GENERIC parameter
specifies a string that contains any option-value pairs. Each option and value must be separated by one or
more blank spaces. The syntax for this string is displayed as follows:
The option-values available for the Linux, Unix, and Windows (LUW) platforms are the following strings:
• HV_EXPANSION_FACTOR <1|2|3|4>
• STATICASDYNAMIC [YES|NO]
HV_EXPANSION_FACTOR <1|2|3|4>
This option applies a multiplier to CHAR and VARCHAR host variables. It is also expand character
host variable lengths within database server to accomdate code page conversion expansion in unequal
codepage environment.
You should use this string in order to resolve -302 errors occurring in static SQL applications running in
unequal codepage environments even after table definitions increased to accommodate expansion. This
200 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
is because static SQL by default uses the defined length of the host variable provided by the client during
BIND to size the equivalent database server memory location for the variable.
Assume there's a 819 codepage application with string "niño". This requires a 4 byte character string
variable in the application. However in unicode UTF-8 the string requires 5 bytes as ñ takes 2 bytes to
represent. So if you had an application running codepage 819 connecting to a unicode (utf-8) database,
issue
To force the database to allocate 2 times the defined application length for the server representation of
the variable. So in this example the 4 byte variable becomes 8 bytes in the database server. This enables
the string niño on expansion to 5 bytes in UTF-8, so it still fits in the memory available to the variable
STATICASDYNAMIC [YES|NO]
You can set the Db2 database manager to store all statements in the catalogs and marks them as
incremental bind. To achieve this setting, the STATICASDYNAMIC YES string must be set for the
GENERIC BIND command option.
At run time, when the package is first loaded, the database manager uses the current session
environment (rather than the package) to set up the section entries and other entities (text is populated
and the package cache is accessed).
Thereafter, the statements in the bound file behave the same as they would if you were using dynamic
SQL. For example, sections are implicitly recompiled for database definition language invalidations,
special register updates. The new syntax is defined as follows:
Structure arrays
You can use structure arrays for FETCH INTO, INSERT, UPDATE, and DELETE statements that are non-
dynamic, when you set the precompiler option COMPATIBILITY_MODE to ORA.
You can use structure arrays to store multiple column data in a structure form.
For a structure array that is declared for an INSERT, UPDATE, or DELETE statement, you must ensure that
all array elements are initialized with a value. Otherwise, unexpected data can get introduced or removed
from the table.
The total number of rows that are successfully processed is stored in the sqlca.sqlerrd[3] field.
However, the sqlca.sqlerrd[3] field does not represent the number of rows that are committed
successfully in the case of INSERT, UPDATE, or DELETE operations.
The total number of rows that are impacted by the INSERT, UPDATE, or DELETE operation is stored in the
sqlca.sqlerrd[2] field.
In one FETCH INTO statement, the maximum number of records that can be retrieved is the cardinality of
the array that is declared. If more rows are available after the first fetch, you can repeat the FETCH INTO
statement to obtain the next set of rows.
You can use a structure array to store multiple rows for an INSERT statement. In the following example, a
structure array is used for an INSERT statement:
// Declare structure array with cardinality of 3.
EXEC SQL BEGIN DECLARE SECTION;
typedef struct _st_type {
int id;
char name[21];
} st_type;
st_type st[3];
EXEC SQL END DECLARE SECTION;
...
// Populating the array.
for( i=0; i<3; i++)
{
memset( &st[i], 0x00, sizeof(st_type));
if( i==0) { st[i].id = 100; strcpy(st[i].name, "hello1");}
if( i==1) { st[i].id = 101; strcpy(st[i].name, "hello2");}
if( i==2) { st[i].id = 102; strcpy(st[i].name, "hello3");}
}
// The structure elements must be in
// the same order as that of the table elements.
//
EXEC SQL INSERT INTO tbl values (:st);
// The INSERT operation was successful and 3 rows has been stored in database.
printf(“sqlca.sqlerrd[2] = %d\n”, sqlca.sqlerrd[2] ); // 3
202 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
• You cannot create a structure array within another structure array (for example, nested structure
arrays).
• Maximum size of array element (cardinality) is 32672.
• The following C and C++ data types are not supported for use with structure arrays:
– BLOB
– BLOB file reference
– BLOB locator variable
– CLOB
– CLOB file reference
– CLOB locator variable
– User-defined data type
– XML
# Below both PRECOMPILE option give error as COMPATIBILITY_MODE ORA is not set.
db2 prep test.sqc UNSAFENULL YES
db2 prep test.sqc UNSAFENULL NO
Remember: Even if you do not set the COMPATIBILITY_MODE parameter to ORA while precompiling, an
application can check the sqlca.sqlerrd[2] structure to get the cumulative sum of the number of
rows that were successfully populated until the last fetch in non-array host variables.
SQLWARNING CONTINUE
...
EXEC SQL WHENEVER NOT FOUND DO sqlError();
...
while(sqlca.sqlcode == SQL_RC_OK)
{
// some application logic
}
...
}
204 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
Index
Index 205
BLOB data type (continued) C/C++ language (continued)
FORTRAN 45 applications (continued)
REXX 47 executing static SQL statements 117
blob_file C/C++ type 33 input files 21
BLOB_FILE FORTRAN data type 45 multiple thread database access 16
blob_locator C/C++ type 33 output files 21
BLOB_LOCATOR FORTRAN data type 45 build files 160
BLOB-FILE COBOL type 41 Chinese (Traditional) EUC considerations 76
BLOB-LOCATOR COBOL type 41 class data members 73
blocking comments 116
cursors 155 connecting to databases 31
buffered inserts data types
advantages 112 functions 39
asynchronous 110 methods 39
buffer size 112 overview 33
closed state 110 stored procedures 39
considerations 110 supported 33
deadlock errors 110 declaring graphic host variables 64
error detection 110 disconnecting from databases 137
error reporting 110 embedded SQL statements 2
group of rows 110 error-checking utility files 161
INSERT BUF bind option 112 file reference declarations 71
long field restriction 114 FOR BIT DATA 76
not supported in CLP 114 graphic host variables 64, 66, 67
open state 110 host structure support 78
overview 112 host variables
partially filled 112 declaring 58
restrictions 114 initializing 77
savepoint consideration 112 naming 59
SELECT buffered insert 110 purpose 58
statements that close 112 include files 24
transaction logs 112 indicator tables 79
unique key violation 110 Japanese EUC considerations 76
buffers LOB data declarations 68
size for buffered insert 112 LOB locator declarations 70
build scripts member operator restrictions 75
C and C++ applications and routines 163 multiconnection applications
COBOL applications and routines 171 building (Windows) 170
embedded SQL applications 160 multithreaded applications
Windows 168
null-terminated strings 80
C numeric host variables 61
C language pointers to data types 72
application template 22 programming considerations 14
applications qualification operator restrictions 75
building (UNIX) 167 restrictions
building (Windows) 168 #ifdefs 77
compiler options (AIX) 163 SQLCODE variables 61
compiler options (Linux) 164 sqldbchar data type 64
compiler options (Windows) 166 SQLSTATE variables 61
batch files 187 stored procedures 129
build files 160 wchar_t data type 64
development environment 22 WCHARTYPE precompiler option 65
error-checking utility files 161 C# .NET
multiconnection applications batch files 160
building on Windows 170 CALL procedure
multithreaded applications anonymous block 197
Windows 168 three-part name 197
C/C++ language char C/C++ data type 33
applications CHAR data type
building (Windows) 168 COBOL 41
compiler options (AIX) 163 conversion to C/C++
compiler options (Linux) 165 33
compiler options (Windows) 166 FORTRAN 45
206 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
CHAR data type (continued) COBOL language (continued)
REXX 47 IBM COBOL compiler
character host variables Windows 178
C/C++ fixed and null-terminated include files 26
62 indicator tables 98
FORTRAN 101 Japanese EUC 96
character sets LOB data declarations 94
multibyte in FORTRAN 104 LOB locator declarations 95
CHARACTER*n FORTRAN data type 45 Micro Focus applications
Chinese (Traditional) code sets building (UNIX) 182
C/C++ 76 building (Windows) 184
COBOL 96 compiler options (AIX) 172
FORTRAN 104 compiler options (Linux) 175
class data members 73 compiler options (Windows) 177
CLOB data type Micro Focus compiler
C/C++ 33, 76 Linux 179
COBOL 41 Windows 178
FORTRAN 45 REDEFINES 96
REXX 47 restrictions 15
clob_file C/C++ data type 33 SQLCODE variables 90
CLOB_FILE FORTRAN data type 45 SQLSTATE variables 90
clob_locator C/C++ data type 33 code pages
CLOB_LOCATOR FORTRAN data type 45 binding 154
CLOB-FILE COBOL type 41 collating sequences
CLOB-LOCATOR COBOL type 41 include files
closed state C/C++ 24
buffered inserts 110 COBOL 26
closing buffered insert 112 FORTRAN 28
COBOL language COLLECTION parameters 159
AIX columns
IBM compiler 177 data types
Micro Focus compiler 180 creating (C/C++) 33
applications creating (COBOL) 41
host variables 88 creating (FORTRAN) 45
input files 21 SQL 52
output files 21 null values
static SQL statements 117 null-indicator variables 54
build files 160 comments
Chinese (Traditional) EUC 96 SQL
comments 116 C and C++ applications 2
connecting to databases 31 COBOL applications 4
data types FORTRAN applications 3
BINARY 89 REXX applications 5
COMP 89 COMMIT statement
COMP-4 89 embedded SQL application
supported SQL data types in COBOL embedded SQL RELEASE option 200
applications 41 COMP data types 89
disconnecting from databases 137 COMP-1 data types 41
embedded SQL statements 4 COMP-3 data types 41
error-checking utility files 161 COMP-4 data types 89
FOR BIT DATA 96 COMP-5 data types 41
host structures 97 compilers
host variables build files 160
declaring 89 embedded SQL applications 7
declaring file reference 95 IBM COBOL
declaring fixed-length character 91 AIX 177
declaring graphic 93 Windows 178
declaring numeric 90 Micro Focus COBOL
naming 88 AIX 180
IBM COBOL applications Windows 178
building (AIX) 181 compiling
building (Windows) 183 embedded SQL applications 150
compiler options (AIX) 172, 173 completion codes
compiler options (Windows) 176 SQL statements 30
Index 207
configuration files data types (continued)
VisualAge 163 CLOB 76
CONNECT statement COBOL 41
embedded SQL 197 compatibility issues 52
consistency conversion
tokens 149 C/C++ 33
contexts COBOL 41
application dependencies between 19 FORTRAN 45
database dependencies between 19 REXX 47
setting between threads 16 DECIMAL
setting in multithreaded Db2 applications FORTRAN 45
details 16 embedded SQL applications
coordinator partition C/C++ 33, 73, 76
without buffered insert 112 mappings 52
CREATE IN COLLECTION NULLID authority 156 FOR BIT DATA
CREATE PROCEDURE statement C/C++ 76
embedded SQL applications 128, 129 COBOL 96
critical sections FORTRAN 45
multithreaded embedded SQL applications 19 graphic types 64
CURRENT EXPLAIN MODE special register host variables 52, 73
dynamic SQL statements 153 mappings
CURRENT PATH special register embedded SQL applications 32, 52
bound dynamic SQL 153 pointers in C/C++ 72
CURRENT QUERY OPTIMIZATION special register VARCHAR
bound dynamic SQL 153 C/C++ 76
cursors databases
embedded SQL applications 130, 133 accessing
multiple in application 133 multiple threads 16
names contexts 16
REXX 5 DATE data type
processing C/C++ 33
SQLDA structure 122 COBOL 41
summary 133 FORTRAN 45
rows REXX 47
deleting 133 DB2ARXCS.BND REXX bind file 186
retrieving 133 db2bfd command
updating 133 overview 150
sample program 134 db2dclgn command
declaring host variables 51
DBCLOB data type
D COBOL 41
data REXX 47
deleting dbclob_file C/C++ data type 33
statically executed SQL applications 133 dbclob_locator C/C++ data type 33
fetched 131 DBCLOB-FILE COBOL data type 41
retrieving DBCLOB-LOCATOR COBOL data type 41
second time 131, 132 ddcs400.lst file 156
scrolling through previously retrieved 131 ddcsmvs.lst file 156
updating ddcsvm.lst file 156
previously retrieved data 133 ddcsvse.lst file 156
statically executed SQL applications 133 DDL
Data Manipulation Language (DML) statements
dynamic SQL performance 11 dynamic SQL performance 11
data retrieval deadlocks
static SQL 130 error in buffered insert 110
data structures multithreaded applications 19
user-defined with multiple threads 18 DECIMAL data type
data types conversion
BINARY 89 C/C++ 33
C COBOL 41
embedded SQL applications 33, 73, 76 FORTRAN 45
C++ REXX 47
embedded SQL applications 33, 73, 76 declare sections
class data members in C/C++ 73 C and C++ embedded SQL applications 58
208 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
declare sections (continued) embedded SQL applications (continued)
COBOL embedded SQL applications 89 COBOL
FORTRAN embedded SQL applications 99 include files 26
DECLARE statements statements 4
C/C++ declare section 58, compiling 7, 189
60 CONNECT statement 197
COBOL declare section 89 db2dsdriver.cfg file 189
FORTRAN declare section 99 declare section 1
statement rules 49 deploying 189
DESCRIBE statement designing 21
processing arbitrary statements 126 development environment 7
DOUBLE data type double quotation marks 198
C/C++ programs dynamic statement execution 10, 116
33 errors 149
dynamic SQL FORTRAN
arbitrary statements include files 28
determining type 126 restrictions 15
processing 126 statements 3
binding 153 host variables
cursors overview 49
processing 122 referencing 56
deleting rows 133 include files
DESCRIBE statement C/C++ 24
overview 10, 117 COBOL 26
DYNAMICRULES effects 151 FORTRAN 28
embedded SQL comparison 11 overview 24
EXECUTE IMMEDIATE statement indicator variable 203
overview 10 operating systems supported 7
EXECUTE statement overview 1
overview 10 packages 158
limitations 10 performance
overview 10 BIND command REOPT option 155
parameter markers 127 overview 13
performance precompiling
static SQL comparison 11 applications accessing multiple servers 146
PREPARE statement errors 149
overview 10 warnings 149
SQLDA programming 21
declaring 118 restrictions
static SQL comparison 11 C/C++ 14
support statements 10 FORTRAN 15
DYNAMICRULES precompile/bind option overview 14
effects on dynamic SQL 151 REXX 15
REXX
restrictions 15
E statements 5
Embedded SQLCA structure 1
SQL/COBOL statements
Support C/C++ 2
MRI COBOL 4
MRF 138 FORTRAN 3
embedded SQL applications REXX 5
access plans 155 static statement execution 10, 116
authorization 9 VARCHAR 198
BIND options 200 warnings 149
C/C++ XML values 53
BREAK action 203 error messages
include file syntax 198 handling 30
include files 24 SQLCA structure 136
PREPARE statements 201 SQLCODE field 136
RELEASE option 200 SQLSTATE field 136
restrictions 14 SQLWARN field 136
statements 2 warning condition flag 136
WHENEVER statement 203 errors
Index 209
errors (continued) FORTRAN language (continued)
checking using utility files 161 connecting to databases 31
detecting in buffered insert 110 data types 45
embedded SQL applications embedding SQL statements 3
C/C++ include files 24 file reference declarations 103
COBOL include files 26 host variables
FORTRAN include files 28 declaring 99
SQLCA structure fields 55 naming 99
SQLCA structures 30 referencing 3
examples include files 28
class data members in SQL statements 73 indicator variables 104
parameter markers in dynamic SQL program 128 Japanese code set 104
REXX program 107 LOB data declarations 102
SQL declare section template 60 LOB locator declarations 103
exception handlers multibyte character sets 104
overview 137 numeric host variables 100
EXEC SQL INCLUDE SQLCA statement 18 programming 15
EXECUTE IMMEDIATE statement restrictions 99
overview 10 SQL declare section example 99
EXECUTE statement SQLCODE variables 100
overview 10 SQLSTATE variables 100
exit list routines 137 fullselect
explain snapshots buffered insert consideration 114
binding 154
Extended UNIX Code (EUC)
Chinese (Traditional)
G
C/C++ applications 76 get error message API
COBOL applications 96 error message retrieval 134
FORTRAN applications 104 predefined REXX variables 105
Japanese graphic data
C/C++ applications 76 host variables
COBOL applications 96 C/C++ embedded SQL applications 67
FORTRAN applications 104 COBOL embedded SQL applications 93
VARGRAPHIC 66
F GRAPHIC data type
C/C++ 33
FETCH statement COBOL 41
host variables 117 FORTRAN 45
repeated data access 131 REXX 47
SQLDA structure 121 selecting 64
file reference declarations in REXX 109
files
reference declarations in C/C++
H
71 host structure support
FIPS 127-2 standard C/C++ 78
declaring SQLSTATE and SQLCODE as host variables 136 COBOL 97
flagger utility for precompiling 144 host variables
FLOAT data type C-array 81, 85, 86, 193, 198, 201
C/C++ conversion C/C++ applications 58
33 character data declarations
COBOL 41 COBOL 91
FORTRAN 45 FORTRAN 101
REXX 47 class data members 73
flushed buffered inserts 112 COBOL applications 41
FOR BIT DATA data type 76 declaring
FOR UPDATE clause C/C++ 58
details 133 COBOL 89
FORTRAN language db2dclgn declaration generator 51
applications embedded SQL application overview 50
host variables 99 FORTRAN 99
input files 21 variable list statement 126
output files 21 dynamic SQL 10
Chinese (Traditional) code set 104 embedded SQL applications
comments 116
210 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
host variables (continued) INCLUDE statement (continued)
embedded SQL applications (continued) BIND command (continued)
C/C++ 68 STATICASDYNAMIC option 193
COBOL 94 CONNECT statement 193
FORTRAN 102 double quotation marks 193
overview 49 indicator tables
REXX 108 C/C++ 79
enabling compatibility features 193, 198 COBOL 98
file reference declarations indicator variables
C/C++ 71 C 81, 193
COBOL 95 compatibility features 193
FORTRAN 103 FORTRAN 104
REXX 109 identifying null SQL values 54
REXX (clearing) 110 REXX 110
FORTRAN applications 3 INSERT BUF bind option
graphic data buffered inserts 112
C/C++ 64 INSERT statement
COBOL 93 not supported in CLP 114
FORTRAN 104 VALUES clause 112
host language statements 49 inserting data
initializing in C/C++ 77 without buffered insert 112
LOB data declarations INTEGER data type
C/C++ 68 C/C++ 33
COBOL 94 COBOL 41
FORTRAN 102 FORTRAN 45
REXX 108 REXX 47
LOB file reference declarations 110 INTEGER*2 FORTRAN data type 45
LOB locator declarations INTEGER*4 FORTRAN data type 45
C/C++ 70 interrupt handlers
COBOL 95 overview 137
FORTRAN 103 isolation levels
REXX 108 repeatable read (RR) 131
REXX (clearing) 110
naming
C/C++ 59
J
COBOL 88 Japanese Extended UNIX Code (EUC) code page
FORTRAN 99 C/C++ embedded SQL applications 76
REXX 105 COBOL embedded SQL applications 96
null-terminated strings 80 FORTRAN embedded SQL applications 104
pointers in C/C++ 72
referencing from SQL 56
REXX applications 105 L
SQL statements 49
LANGLEVEL precompile option
static SQL 49
MIA 33
truncation 54
SAA1 33
WCHARTYPE precompiler option 65
SQL92E 61, 90, 100
large objects (LOBs)
I C/C++ declarations 68
locators
IBM COBOL declarations in C/C++
Linux 70
IBM Compiler 174 latches 16
include files libdb2.so libraries
C/C++ embedded SQL applications 24 restrictions 192
COBOL embedded SQL applications 26 linking
FORTRAN embedded SQL applications 28 details 150
locating in COBOL applications 4 Linux
overview 24 C
INCLUDE SQLCA statement applications 164
declaring SQLCA structure 30 C++
INCLUDE SQLDA statement applications 165
creating SQLDA structure 122 libraries
INCLUDE statement libaio.so.2 192
BIND command
Index 211
Linux (continued) NULLID 156
Micro Focus COBOL NUMERIC data type
applications 175 C/C++ 33
configuring compilers 179 COBOL 41
Linux on x86 FORTRAN 45
IBM COBOL applications REXX 47
compiler and link options 173 numeric host variables
LOB data type C/C++ 61
data declarations in C/C++ COBOL 90
68 FORTRAN 100
locks
buffered insert error 110
long C/C++ data type 33
O
long fields Object REXX for Windows applications
buffered inserts, restriction 114 building 186
long int C/C++ data type 33 open state
long long C/C++ data type 33 buffered inserts 110
long long int C/C++ data type 33 optimizer
LONG VARCHAR data type dynamic SQL 11
C/C++ 33 static SQL 11
COBOL 41
FORTRAN 45
REXX 47 P
LONG VARGRAPHIC data type
packages
C/C++ 33
creating
COBOL 41
BIND command and existing bind file 153
FORTRAN 45
embedded SQL applications 146
REXX 47
host database servers 156
inoperative 154
M invalid state 154
privileges
macro expansion overview 158
C/C++ language REXX application support 186
77 schemas 146
member operators System i database servers 156
C/C++ restriction time stamp errors 149
75 versions
MIA LANGLEVEL precompile option 33 privileges 159
multi-threaded applications same name 159
building parameter markers
C++ (Windows) 168 dynamic SQL
files 160 determining statement type 126
multibyte code pages example 128
Chinese (Traditional) code sets variable input 127
C/C++ 76 examples 128
COBOL 96 typed 127
FORTRAN 104 partitioned database environments
Japanese code sets buffered inserts
C/C++ 76 considerations 110
COBOL 96 purpose 112
FORTRAN 104 restrictions 114
multiconnection applications performance
build files 160 buffered inserts 112
building Windows C/C++ dynamic SQL 11
170 FOR UPDATE clause 133
PICTURE (PIC) clause in COBOL types 41
N precompilation
accessing host application servers through Db2 Connect
NULL 144
SQL value accessing multiple servers 144
indicator variables 54 C/C++ 75
null-terminated character form 33 consistency tokens 149
null-terminator 33 dynamic SQL statements 10
212 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
precompilation (continued) REXX language (continued)
embedded SQL applications 144 applications (continued)
flagger utility 144 host variables 105
FORTRAN 15 bind files 186
time stamps 149 comments 116
PRECOMPILE command connecting to databases 31
embedded SQL applications cursor identifiers 5
accessing multiple database servers 146 data types 47
building from command line 187 disconnecting from databases 137
C/C++ 187 embedded SQL statements 5, 116, 185
overview 143 host variables
UNSAFENULL options 203 naming 105
PREPARE statement referencing 105
arbitrary statement processing 126 indicator variables 110
embedded initializing variables 130
Dynamic preparation and execution 201 LOB file reference declarations 109
overview 10 LOB host variables 108, 110
preprocessor functions LOB locator declarations 108
SQL precompiler 77 predefined variables 105
procedures registering routines 107
CALL statement 128 restrictions 15, 105
parameters running applications 185
types 128 SQLDB2 API 107
SQLDBS API 107
SQLEXEC API 107
Q stored procedures
qualification operator in C/C++ 75 overview 130
queryopt precompile/bind option Windows applications 186
code page considerations 154 ROLLBACK statement
embedded SQL application
RELEASE option 200
R routines
build files 160
REAL SQL data type
rows
C/C++ 33
grouping in buffered insert 110
COBOL 41
retrieving
FORTRAN 45
multiple 133
REXX 47
using SQLDA 121
REAL*2 FORTRAN SQL data type 45
second retrieval
REAL*4 FORTRAN SQL data type 45
methods 131
REAL*8 FORTRAN SQL data type 45
row order 132
REBIND command
RUNSTATS command
rebinding 154
statistics collection 13
rebinding
runtime services
process 154
multiple threads effect on latches 16
REBIND command 154
REDEFINES clause
COBOL 96 S
repeatable read (RR)
re-retrieving data 131 SAA1 LANGLEVEL precompile option 33
restrictions samples
buffered inserts 114 IBM COBOL 171
result codes 30 savepoints
RESULT REXX predefined variable 105 buffered inserts 112
return codes SELECT statement
declaring SQLCA 30 buffered inserts 110
REXX language declaring SQLDA 118
APIs describing after allocating SQLDA 121
SQLDB2 15 EXECUTE statement 10
SQLDBS 15 retrieving
SQLEXEC 15 data a second time 131
applications multiple rows 133
embedded SQL (building) 185 updating retrieved data 133
embedded SQL (running) 185 variable-list 126
semaphores 19
Index 213
serialization SQLCA structure (continued)
data structures 18 include files
SQL statement execution 16 C/C++ applications 24
SET CURRENT PACKAGESET statement 146, 159 COBOL applications 26
short data type FORTRAN applications 28
C/C++ 33 multithreading 18
short int data type 33 overview 136
signal handlers predefined variable 105
overview 137 SQLCODE field 136
SMALLINT data type SQLSTATE field 136
C/C++ 33 SQLWARN1 field 54
COBOL 41 warnings 54
FORTRAN 45 SQLCA_92 include file
REXX 47 COBOL applications 26
special registers FORTRAN applications 28
CURRENT EXPLAIN MODE 153 SQLCA_CN include file 28
CURRENT EXPLAIN SNAPSHOT 153 SQLCA_CS include file 28
CURRENT PATH 153 SQLCHAR structure
CURRENT QUERY OPTIMIZATION 153 passing data with 124
SQL SQLCLI include file 24
authorization for embedded SQL 9 SQLCLI1 include file 24
include files SQLCODE
C/C++ applications 24 overview 30, 136
COBOL applications 26 SQLCODES include file
FORTRAN applications 28 C/C++ applications 24
SQL data types COBOL applications 26
embedded SQL applications FORTRAN applications 28
C/C++ 33 SQLDA
COBOL 41 creating 122
FORTRAN 45 declaring 118
overview 52 declaring sufficient SQLVAR entities 120
REXX 47 determining statement type 126
SQL statements include files
C/C++ syntax 2 C/C++ applications 24
COBOL syntax 4 COBOL applications 26
dynamic 1, 9 FORTRAN applications 28
embedded 1, 9 multithreading 18
exception handlers 137 passing data 124
FORTRAN syntax 3 prepared statements 10
INCLUDE 30 preparing statements using minimum structure 119
interrupt handlers 137 SQLDACT include file 28
preparing using minimum SQLDA structure 119 SQLDB2 API
REXX syntax 5 registering for REXX 107
saving end user requests 127 sqldbchar data type
serializing execution 16 C/C++ embedded SQL applications
signal handlers 137 64
static 1, 9 equivalent column type 33
SQL_WCHART_CONVERT preprocessor macro 65 SQLDBS API 107
SQL1252A include file SQLE819A include file
COBOL applications 26 C/C++ applications 24
FORTRAN applications 28 COBOL applications 26
SQL1252B include file FORTRAN applications 28
COBOL applications 26 SQLE819B include file
FORTRAN applications 28 C/C++ applications 24
SQLADEF include file 24 COBOL applications 26
SQLAPREP include file FORTRAN applications 28
C/C++ applications 24 SQLE850A include file
COBOL applications 26 COBOL applications 26
FORTRAN applications 28 FORTRAN applications 28
SQLCA (SQL communication area) SQLE850B include file
error reporting in buffered insert 110 COBOL applications 26
incomplete insert when error occurs 110 FORTRAN applications 28
SQLCA structure SQLE859A include file 24
declaring 30 SQLE859B include file 24
214 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
SQLE932A include file SQLUV include file 24
C/C++ applications 24 SQLUVEND include file 24
COBOL applications 26 SQLVAR entities
FORTRAN applications 28 declaring sufficient number 118, 120
SQLE932B include file SQLWARN
C/C++ applications 24 overview 136
COBOL applications 26 SQLXA include file 24
FORTRAN applications 28 static SQL
sqleAttachToCtx API comparison to dynamic SQL 11
multiple contexts 16 host variables 49, 50
SQLEAU include file retrieving data 130
C/C++ applications 24 storage
COBOL applications 26 allocating to hold rows 121
FORTRAN applications 28 declaring sufficient SQLVAR entities 118
sqleBeginCtx API stored procedures
multiple contexts 16 REXX applications 130
sqleDetachFromCtx API structure arrays
multiple contexts 16 C 85, 86, 198, 201
sqleEndCtx API success codes 30
multiple contexts 16 symbols
sqleGetCurrentCtx API C/C++ language restrictions
multiple contexts 16 77
sqleInterruptCtx API
multiple contexts 16
SQLENV include file
T
C/C++ applications 24 tables
COBOL applications 26 fetching rows 134
FORTRAN applications 28 names
SQLETSD include file 26 resolving unqualified 159
SQLException resolving unqualified names 159
embedded SQL applications 134 target partitions
SQLEXEC REXX API behavior without buffered insert 112
processing SQL statements 5 threads
registering 107 multiple
restrictions 15 embedded SQL applications 16, 19
SQLEXT include file 24 recommendations 18
sqlint64 C/C++ data type 33 UNIX applications 19
SQLISL predefined variable 105 TIME data types
SQLJACB include file 24 C/C++ 33
SQLMON include file COBOL 41
C/C++ applications 24 FORTRAN 45
COBOL applications 26 REXX 47
FORTRAN applications 28 time stamps
SQLMONCT include file 26 precompiler-generated 149
SQLMSG predefined variable 105 TIMESTAMP data type
SQLRDAT predefined variable 105 C/C++ 33
SQLRIDA predefined variable 105 COBOL 41
SQLRODA predefined variable 105 FORTRAN 45
SQLSTATE REXX 47
include files transaction logs
C/C++ applications 24 buffered inserts 112
COBOL applications 26 truncation
FORTRAN applications 28 host variables 54
overview 136 indicator variables 54
SQLSYSTM include file 24 typed parameter markers 127
SQLUDF include file
C/C++ applications
24 U
SQLUTBCQ include file 26
unique keys
SQLUTBSQ include file 26
unique key violation, buffered inserts 110
SQLUTIL include file
UNIX
C/C++ applications 24
C applications
COBOL applications 26
building 167
FORTRAN applications 28
Index 215
UNIX (continued) X
Micro Focus COBOL applications 182
USAGE clause in COBOL types 41 XML
utilities C/C++ applications
binding 156 executing XQuery expressions 114
ddcspkgn 156 COBOL applications 114
utility APIs declarations
include files embedded SQL applications 52
C/C++ applications 24 XMLQUERY function 16
COBOL applications 26 XQuery expressions 16, 114
FORTRAN applications 28 XML data retrieval
C applications 57
COBOL applications 57
V XML data type
VARBINARY data type host variables in embedded SQL applications 52
embedded SQL applications 75 identifying in SQLDA 53
host variables 74 XML encoding
VARCHAR data type overview 52
C/C++ XQuery statements
details 33 declaring host variables in embedded SQL applications
FOR BIT DATA substitute 76 52
COBOL 41
conversion to C/C++ 33
embedded SQL 198
FORTRAN 45
REXX 47
VARGRAPHIC data type
C/C++ conversion
33
COBOL 41
FORTRAN 45
REXX 47
variables
REXX 105
SQLCODE 61, 90, 100
SQLSTATE 61, 90, 100
Visual Basic .NET
batch files 160
W
warnings
truncation 54
wchar_t data type
C/C++ embedded SQL applications
64
WCHARTYPE precompiler option
data types available with NOCONVERT and CONVERT
options 33
details 65
Windows
C/C++ applications
building 168
compiler options 166
link options 166
COBOL applications
building 183
compiler options 176
link options 176
Micro Focus COBOL applications
building 184
compiler options 177
link options 177
216 IBM Db2 V11.5: Developing embedded SQL and XQuery database applications
IBM®