IBM Books

Embedded SQL Programming Guide


Programming Considerations

Special host language programming considerations are discussed in the following pages. Included is information on language restrictions, host-language-specific include files, embedding SQL statements, host variables, and supported data types for host variables.

Language Restrictions

The following sections describe the C/C++ language restrictions.

Macro Expansion

Do not use C preprocessor constructs such as, macros, #ifdefs, or symbol substitutions in the host variable declare section or in any SQL statements. You can use these constructs elsewhere in your application. The SQL precompiler does not handle preprocessor functions such as macro processing or symbol substitution, and does not support conditional precompilation (#ifdefs). The following example demonstrates incorrect placement of the C preprocessor constructs:

     #define NAME_LENGTH 20 
     EXEC SQL BEGIN DECLARE SECTION; 
       char name [NAME_LENGTH];    /* incorrect placement of macro */ 
     EXEC SQL END DECLARE SECTION; 
     #ifdef PRODUCTION   /* careful - both statements will be precompiled */ 
     EXEC SQL SELECT NAME INTO :name FROM PRODUCTION.PAYROLL 
       WHERE ID = 10; 
     #else 
     EXEC SQL SELECT NAME INTO :name FROM TESTING.PAYROLL 
       WHERE ID = 10; 
     #endif

Input and Output Files

By default, the input file can have the following extensions:

.sqc
For C files on either platform.
.sqC
For C++ files on case sensitive platforms (like AIX).
.sqx
For C++ files on case insensitive platforms (like OS/2).

The corresponding default output files have the following extensions:

.c
For C files on any platform.
.C
For C++ files on case sensitive platforms (like AIX).
.cxx
For C++ files on case insensitive platforms (like OS/2).
.cpp
For C++ files for the Borland C++ compiler on OS/2 or Windows 3.1.

You can use the OUTPUT precompile option to override the name and path of the output modified source file. If you use the TARGET C or TARGET CPLUSPLUS precompile option, the input file does not need a particular extension.

Including Files

There are two methods for including files: the EXEC SQL INCLUDE statement and the #include macro. The precompiler will ignore the #include, and only process files included with the EXEC SQL INCLUDE statement.

To locate files included using EXEC SQL INCLUDE, the DB2 C/C++ precompiler searches the current directory first, then the directories specified by the DB2INCLUDE environment variable. Consider the following examples:

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 as usual.

To help relate compiler errors back to the original source the precompiler generates ANSI #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 precompiler output. 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 wish to use behaves unexpectedly, use the NOLINEMACRO option (used with db2 PREP) when precompiling. This will prevent the #line macros from being generated.

Trigraph Sequences

Some characters from the C or C++ character set are not available on all keyboards. These characters can be entered into a C or C++ source program using a sequence of three characters called a trigraph. Trigraphs are not recognized in SQL statements. The precompiler recognizes the following trigraphs within host variable declarations:

Trigraph
Definition
??(
Left bracket '['
??)
Right bracket ']'
??<
Left brace '{'
??>
Right brace '}'

The remaining trigraphs listed below may occur elsewhere in a C or C++ source program:

Trigraph
Definition
??=
Hash mark '#'
??/
Back slash '\'
??'
Caret '^'
??!
Vertical Bar '|'
??-
Tilde '~'

C++ Type Decoration Consideration

When writing a stored procedure or a UDF using C++, you may want to consider declaring the procedure or UDF as:

     extern "C" ...procedure or function declaration...

The extern "C" prevents type decoration of the function name by the C++ compiler. Without this declaration, you have to include all the type decoration for the function name when you call the stored procedure, or issue the CREATE FUNCTION statement.

Include Files

The host-language-specific include files (header files) for C and C++ have the file extension .h. The include files that are intended to be used in your applications, are described below.

SQL (sql.h)
This file includes language-specific prototypes for the binder, precompiler, and error message retrieval APIs. It also defines system constants.

SQLADEF (sqladef.h)
This file contains function prototypes used by precompiled C and C++ applications.

SQLAPREP (sqlaprep.h)
This file contains definitions required to write your own precompiler.

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.

SQLCLI (sqlcli.h)
This file contains the function prototypes and constants needed to write a simple Call Level Interface (DB2 CLI) application. The functions in this file are common to both X/Open Call Level Interface and ODBC Core Level.

SQLCLI1 (sqlcli1.h)
This file contains the function prototypes and constants needed to write a Call Level Interface (DB2 CLI) that makes use of the more advanced features in DB2 CLI. Many of the functions in this file are common to both X/Open Call Level Interface and ODBC Level 1. In addition, this file also includes X/Open-only functions and DB2-specific functions.

This file includes both sqlcli.h and sqlext.h (which contains ODBC Level2 API definitions).

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.

SQLEAU (sqleau.h)
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.

SQLENV (sqlenv.h)
This file defines language-specific calls for the database environment APIs, and the structures, constants, and return codes for those interfaces.

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.

SQLE819A (sqle819a.h)
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.h)
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.h)
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.

SQLE850B (sqle850b.h)
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 037 (EBCDIC US English) binary collation. This file is used by the CREATE DATABASE API.

SQLE932A (sqle932a.h)
If the code page of the database is 932 (ASCII Japanese), this sequence sorts character strings that are not FOR BIT DATA according to the host CCSID 5035 (EBCDIC Japanese) binary collation. This file is used by the CREATE DATABASE API.

SQLE932B (sqle932b.h)
If the code page of the database is 932 (ASCII Japanese), this sequence sorts character strings that are not FOR BIT DATA according to the host CCSID 5026 (EBCDIC Japanese) binary collation. This file is used by the CREATE DATABASE API.

SQLJACB (sqljacb.h)
This file defines constants, structures and control blocks for the DB2 Connect interface.

SQLMON (sqlmon.h)
This file defines language-specific calls for the database system monitor APIs, and the structures, constants, and return codes for those interfaces.

SQLSTATE (sqlstate.h)
This file defines constants for the SQLSTATE field of the SQLCA structure.

SQLSYSTM (sqlsystm.h)
This file contains the platform-specific definitions used by the database manager APIs and data structures.

SQLUDF (sqludf.h)
This file defines constants and interface structures for writing User Defined Functions (UDFs). For more information on this file, see "The UDF Include File: sqludf.h".

SQLUTIL (sqlutil.h)
This file defines the language-specific calls for the utility APIs, and the structures, constants, and codes required for those interfaces.

SQLUV (sqluv.h)
This file defines structures, constants, and prototypes for the asynchronous Read Log API, and APIs used by the table load and unload vendors.

SQLUVEND (sqluvend.h)
This file defines structures, constants and prototypes for the APIs to be used by the storage management vendors.

SQLXA (sqlxa.h)
This file contains function prototypes and constants used by applications that use the X/Open XA Interface.

Embedding SQL Statements

Embedded SQL statements consist of the following three elements:

Element
Correct Syntax
Statement initializer
EXEC SQL
Statement string
Any valid SQL statement
Statement terminator
semicolon (;).

For example:

     EXEC SQL SELECT col INTO :hostvar FROM table;

The following rules apply to embedded SQL statements:

Host Variables

Host variables are C or C++ language variables that are referenced within SQL statements. They allow an application to pass input data to and receive output data from the database manager. After the application is precompiled, host variables are used by the compiler as any other C/C++ variable. Obey the rules described in the following sections when naming, declaring, and using host variables.

Naming Host Variables

The SQL precompiler identifies host variables by their declared name. The following rules apply:

Declaring Host Variables

An SQL declare section must be used to identify host variable declarations. This alerts the precompiler to any host variables that can be referenced in subsequent SQL statements.

The C/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. Using typedefs for host variable types is not allowed, and host variables cannot be embedded in structures. You can declare C++ class data members as host variables. For more information on classes, see "Using Class Data Members as Host Variables".

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.

Figure 26 shows the syntax for declaring numeric host variables in C or C++.

Figure 26. Syntax for Numeric Host Variables in C or C++

                                         (1)                               
 >>--.----------.--.----------.--.-float-----------------.---------------> 
     |-auto-----|  |-const----|  |        (2)            |                 
     |-extern---|  '-volatile-'  |-double----------------|                 
     |-static---|                |        (3)            |                 
     '-register-'                '-.-long-----.--.-----.-'                 
                                   |       (4)|  '-int-'                   
                                   '-short----'                            
                                                                           
    <-,--------------------------------------------------<                 
 >----.-------------------------.--varname--.----------.----;----------->< 
      | <---------------------< |           '-=--value-'                   
      '---.-*-.--.----------.---'                                          
          '-&-'  |-const----|                                              
                 '-volatile-'                                              
                                                                           
 NOTES:                                                                    
 (1)  REAL (SQLTYPE 480), length 4                                         
 (2)  DOUBLE (SQLTYPE 480), length 8                                       
 (3)  INTEGER (SQLTYPE 496)                                                
 (4)  SMALLINT (SQLTYPE 500)                                               

Figure 27 shows the syntax for declaring fixed and null-terminated character host variables in C or C++.

Figure 27. Form 1: Syntax for Fixed and Null-terminated Character Host Variables in C/C++

>>--.----------.--.----------.--.----------.--char----------------------> 
    |-auto-----|  |-const----|  '-unsigned-'                              
    |-extern---|  '-volatile-'                                            
    |-static---|                                                          
    '-register-'                                                          
                                                                          
   <-,------------------------------<                                     
>----.-| CHAR |-----.--.----------.----;------------------------------->< 
     '-| C String |-'  '-=--value-'                                       
                                                                          
CHAR:                                                                     
                                        (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)                              

Figure 28 shows the syntax for declaring variable length character host variables in C or C++.

Figure 28. Form 2: Syntax for Variable Length Character Host Variables in C/C++

>>--.----------.--.----------.--struct--.-----.-------------------------> 
    |-auto-----|  |-const----|          '-tag-'                           
    |-extern---|  '-volatile-'                                            
    |-static---|                                                          
    '-register-'                                                          
                                                                          
                                                                 (1)      
>--{--short--.-----.--var1--;--.----------.--char--var2--[number]-----;---}-->
             '-int-'           '-unsigned-'                               
                                                                          
   <-,------------------------------------------------<                   
>----.-------------------------.--varname--| Values |----;------------->< 
     | <---------------------< |                                          
     '---.-*-.--.----------.---'                                          
         '-&-'  |-const----|                                              
                '-volatile-'                                              
                                                                          
VALUES:                                                                   
|--.------------------------------.-------------------------------------| 
   '-=--{--value-1--,--value-2--}-'
                                                                          
NOTE:                                                                     
(1)  In FORM 2, the value of [number] determines if the host variable is
     VARCHAR (SQLTYPE 448) or LONG VARCHAR (SQLTYPE 456).                 

Notes:

  1. Although the database manager converts character data to either form 1 or form 2 whenever possible, form 1 corresponds to column types CHAR or VARCHAR while form 2 corresponds to column types VARCHAR and LONG VARCHAR.

  2. If form 1 is used with a length specifier [n], the length must be no greater than 4000, and the string contained by the variable should be null-terminated.

  3. If form 2 is used, the length specifier must be no greater than 32 700.

  4. In form 2, var1 and var2 must be simple variable references (no operators), and cannot be used as host variables (varname is the host variable).

  5. varname can be a simple variable name or it can include operators, such as *varname. See "Pointer Data Types" for more information.

  6. The precompiler determines the SQLTYPE and SQLLEN of all host variables. If a host variable appears in an SQL statement with an indicator variable, the SQLTYPE is assigned to be the base SQLTYPE plus one, for the duration of that statement.

  7. The precompiler permits some declarations which are not syntactically valid in C or C++. Refer to your compiler documentation if in doubt of a particular declaration syntax.

Indicator Variables

Indicator variables should be declared as a short data type.

Graphic Host Variable Declarations in C or C++

Graphic host variable declarations can take one of three forms:

For details on using graphic host variables, see "Handling Graphic Host Variables".

Figure 29 shows the syntax for declaring a graphic host variable using the single-graphic form and the null-terminated graphic form.

Figure 29. Syntax for Graphic Declaration (Single-Graphic Form and Null-Terminated Graphic Form)

                                            (1) 
>>--.----------.--.----------.--.-sqldbchar----.------------------------> 
    |-auto-----|  |-const----|  |         (2)  |                          
    |-extern---|  '-volatile-'  '-wchar_t------'                          
    |-static---|                                                          
    '-register-'                                                          
                                                                          
   <-,------------------------------<                                     
>----.-| CHAR |-----.--.----------.----;------------------------------->< 
     '-| C String |-'  '-=--value-'                                       
                                                                          
CHAR:                                                                     
                                        (3)                               
|--.-------------------------.--varname---------------------------------| 
   | <---------------------< |                                            
   '---.-*-.--.----------.---'                                            
       '-&-'  |-const----|                                                
              '-volatile-'                                                
                                                                          
C STRING:                                                                 
                                                           (4)            
|--.-varname------------------------------------.--[length]-------------|
   '-(--.-------------------------.--varname--)-'                         
        | <---------------------< |                                       
        '---.-*-.--.----------.---'                                       
            '-&-'  |-const----|                                           
                   '-volatile-'                                           
NOTES:                                                               
(1)  To determine which of the two graphic types should be used, see 
     "Selecting the wchar_t or sqldbchar Data Type".     
(2)  To determine which of the two graphic types should be used, see 
     "Selecting the wchar_t or sqldbchar Data Type".     
(3)  GRAPHIC (SQLTYPE 468), Length 1                                 
(4)  Null-terminated graphic string (SQLTYPE 400)                    

Notes:

  1. The single-graphic form declares a fixed-length graphic string host variable of length 1 with SQLTYPE of 468 or 469.

  2. value is an initializer. A wide-character string literal (L-literal) should be used if WCHARTYPE CONVERT precompiler option is used.

  3. length must be a constant that is greater than or equal to 1 and not greater than the maximum length of VARGRAPHIC which is 2 000.

  4. Null-terminated graphic strings are handled differently depending on the value of the standards level precompile option setting. See "Null-terminated Strings" for details.

Figure 30 shows the syntax for declaring a graphic host variable using the VARGRAPHIC structured form.

Figure 30. Syntax for Graphic Declaration (VARGRAPHIC Structured Form)

>>--.----------.--.----------.--struct--.-----.------------------------->
    |-auto-----|  |-const----|          '-tag-'                          
    |-extern---|  '-volatile-'                                           
    |-static---|                                                         
    '-register-'                                                         
                                                                         
                                            (1)                          
>--{--short--.-----.--var-1--;--.-sqldbchar----.--var-2--[length]--;--}->
             '-int-'            |         (2)  |                         
                                '-wchar_t------'                         
                                                                         
   <-,--------------------------------------------<                      
>----.-------------------------.--| Variable |--;----------------------><
     | <---------------------< |                                         
     '---.-*-.--.----------.---'                                         
         '-&-'  |-const----|                                             
                '-volatile-'                                             
                                                                         
VARIABLE:                                                                
|--variable-name--.------------------------------.----------------------|
                  '-=--{--value-1--,--value-2--}-'
 
NOTES:                                                               
(1)  To determine which of the two graphic types should be used, see 
     "Selecting the wchar_t or sqldbchar Data Type".                                                                          
(2)  To determine which of the two graphic types should be used, see 
     "Selecting the wchar_t or sqldbchar Data Type".     

Notes:

  1. length must be a constant that is greater than 1 and not greater than the maximum length of LONG VARGRAPHIC which is 16350.

  2. var-1 and var-2 must be simple variable references (no operators) and cannot be used as host variables.

  3. value-1 and value-2 are initializers for var-1 and var-2. value-1 must be an integer and value-2 should be a wide-character string literal (L-literal) if WCHARTYPE CONVERT precompiler option is used.

  4. The struct tag can be used to define other data areas, but these cannot be used as host variables.

  5. The value of length determines if the host variable is VARGRAPHIC (SQLTYPE 464) or LONG VARGRAPHIC (SQLTYPE 472).

LOB Data Declarations in C or C++

Figure 31 shows the syntax for declaring large object (LOB) host variables in C or C++.

Figure 31. Syntax for Large Object (LOB) Host Variables in C/C++

>>--.----------.--.----------.--SQL TYPE IS--.-BLOB---.-----------------> 
    |-auto-----|  |-const----|               |-CLOB---|                   
    |-extern---|  '-volatile-'               '-DBCLOB-'                   
    |-static---|                                                          
    '-register-'                                                          
                                                                          
>--(length-.---.-)------------------------------------------------------> 
           |-K-|                                                          
           |-M-|                                                          
           '-G-'                                                          
                                                                          
   <-,--------------------------------------------------------<           
>----.-------------------------.--variable-name--| LOB Data |----;----->< 
     | <---------------------< |                                          
     '---.-*-.--.----------.---'                                          
         '-&-'  |-const----|                                              
                '-volatile-'                                              
                                                                          
LOB DATA:                                                                 
|--.-------------------------------.------------------------------------| 
   |-={init-len,"init-data"}-------|
   |-=SQL_BLOB_INIT("init-data")---|                                      
   |-=SQL_CLOB_INIT("init-data")---|                                      
   '-=SQL_DBCLOB_INIT("init-data")-'                                      

Notes:

  1. The SQL TYPE IS clause is needed in order 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. For BLOB and CLOB  1 <= lob-length <= 2 147 483 647.

  3. For DBCLOB  1 <= lob-length <= 1 073 741 823.

  4. SQL TYPE IS, BLOB, CLOB, DBCLOB, K, M, G may be in mixed case.

  5. The maximum length allowed for the initialization string, "init-data", is 4000 bytes (the same as the existing limit on C/C++ strings within the precompiler).

  6. The initialization length, init-len, must be a numeric constant (i.e. it cannot include K, M, or G).

  7. A length for the LOB must be specified; that is, the following declaration is not permitted:
         SQL TYPE IS BLOB my_blob;
    

  8. If the LOB is not initialized within the declaration, then no initialization will be done within the precompiler generated code.

  9. 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.

  10. The precompiler generates a structure tag which can be used to cast to the host variable's type.

BLOB Example:

Declaration:

     static Sql Type is Blob(2M) my_blob=SQL_BLOB_INIT("mydata");

Results in the generation of the following structure:

     static struct my_blob_t { 
           unsigned long    length; 
           char             data[2097152]; 
      } my_blob=SQL_BLOB_INIT("mydata");

CLOB Example:

Declaration:

      volatile sql type is clob(125m) *var1, var2 = {10, "data5data5"};

Results in the generation of the following structure:

      volatile struct var1_t { 
           unsigned long    length; 
           char             data[131072000]; 
      } * var1, var2 = {10, "data5data5"};

DBCLOB Example:

Declaration:

      SQL TYPE IS DBCLOB(30000) my_dbclob1;

Precompiled with the WCHARTYPE NOCONVERT option, results in the generation of the following structure:

     struct my_dbclob1_t { 
          unsigned long    length; 
          sqldbchar        data[30000]; 
     } my_dbclob1;

Declaration:

      SQL TYPE IS DBCLOB(30000) my_dbclob2 = SQL_DBCLOB_INIT(L"mydbdata");

Precompiled with the WCHARTYPE CONVERT option, results in the generation of the following structure:

     struct my_dbclob2_t { 
          unsigned long    length; 
          wchar_t          data[30000]; 
     } my_dbclob2 = SQL_DBCLOB_INIT(L"mydbdata");

LOB Locator Declarations in C or C++

Figure 32 shows the syntax for declaring large object (LOB) locator host variables in C or C++.

Figure 32. Syntax for Large Object (LOB) Locator Host Variables in C/C++

>>--.----------.--.----------.--SQL TYPE IS--.-BLOB_LOCATOR---.---------> 
    |-auto-----|  |-const----|               |-CLOB_LOCATOR---|           
    |-extern---|  '-volatile-'               '-DBCLOB_LOCATOR-'           
    |-static---|                                                          
    '-register-'                                                          
                                                                          
   <-,-----------<                                                        
>----| Options |------------------------------------------------------->< 
                                                                          
OPTIONS:                                                                  
|--.-------------------------------------------------------------.------| 
   | <---------------------<                                     |        
   '---.-*-.--.----------.----variable-name--.--------------.--;-'        
       '-&-'  |-const----|                   '-= init-value-'             
              '-volatile-'                                                

Notes:

  1. SQL TYPE IS, BLOB_LOCATOR, CLOB_LOCATOR, DBCLOB_LOCATOR may be in mixed case.

  2. init-value permits the initialization of pointer and reference locator variables. Other types of initialization will have no meaning.

CLOB Locator Example (other LOB locator type declarations are similar):

Declaration:

     SQL TYPE IS CLOB_LOCATOR my_locator;

Results in the generation of the following declaration:

     long my_locator;

File Reference Declarations in C or C++

Figure 33 shows the syntax for declaring file reference host variables in C or C++.

Figure 33. Syntax for File Reference Host Variables in C/C++

>>--.----------.--.----------.--SQL TYPE IS--.-BLOB_FILE---.------------> 
    |-auto-----|  |-const----|               |-CLOB_FILE---|              
    |-extern---|  '-volatile-'               '-DBCLOB_FILE-'              
    |-static---|                                                          
    '-register-'                                                          
                                                                          
   <-,-----------<                                                        
>----| Options |------------------------------------------------------->< 
                                                                          
OPTIONS:                                                                  
|--.-------------------------------------------------------------.------| 
   | <---------------------<                                     |        
   '---.-*-.--.----------.----variable-name--.--------------.--;-'        
       '-&-'  |-const----|                   '-= init-value-'             
              '-volatile-'                                                

Note:

CLOB File Reference Example (other LOB file reference type declarations are similar):

Declaration:

     static volatile SQL TYPE IS BLOB_FILE my_file;

Results in the generation of the following structure:

     static volatile struct { 
          unsigned long    name_length; 
          unsigned long    data_length; 
          unsigned long    file_options; 
                   char    name[255]; 
     } my_file;

Initializing Host Variables

In C++ declare sections, you cannot initialize host variables using parentheses. The following example shows the correct and incorrect methods of initialization in a declare section:

     EXEC SQL BEGIN DECLARE SECTION; 
       short my_short_2 = 5;       /* correct   */ 
       short my_short_1(5);        /* incorrect */ 
     EXEC SQL END DECLARE SECTION;

Null-terminated Strings

C/C++ null-terminated strings have their own SQLTYPE (460/461 for character and 468/469 for graphic).

C/C++ null-terminated strings are handled differently depending on the value of the LANGLEVEL precompiler option. If a host variable of one of these SQLTYPEs and declared length n is specified within an SQL statement, and the number of bytes (for character types) or double-byte characters (for graphic types) of data is k, then:

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 as defined above. When specified in any other SQL context, a host variable of SQLTYPE 468 with length n is treated as a VARGRAPHIC data type with length n as defined above.

Pointer Data Types

Host variables may be declared as pointers to specific data types with the following restrictions:

Using Class Data Members as Host Variables

You can declare class data members as host variables (but not classes or objects themselves). The following example illustrates the method to use:

Figure 34. Example of Declaring Class Data Members as Host Variables

    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). This means that no SQLDA optimization will be done by the database manager. (This is true whenever pointer host variables are involved in SQL statements.)

The following example shows how you might directly use class data members which you have declared as host variables, in an SQL statement.

Figure 35. Example of Using Class Data Members Directly in an SQL Statement

    class STAFF
    { 
        . 
        . 
        public: 
        . 
        . 
           short int hire( void ) 
           { 
             EXEC SQL INSERT INTO staff ( name,id,salary ) 
               VALUES ( :staff_name, :staff_id, :staff_salary ); 
             staff_in_db = (sqlca.sqlcode == 0);
             return sqlca.sqlcode; 
           } 
   }; 

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 example in Figure 34), 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.

Figure 36. Example of Using Class Data Members Indirectly in an SQL Statement

     short int STAFF::asWellPaidAs( STAFF otherGuy ) 
     { 
         EXEC SQL BEGIN DECLARE SECTION; 
           short &otherID = otherGuy.staff_id 
           double otherSalary; 
         EXEC SQL END DECLARE SECTION; 
         EXEC SQL SELECT SALARY INTO :otherSalary 
           FROM STAFF WHERE id = :otherID; 
           if( sqlca.sqlcode == 0 ) 
              return staff_salary >= otherSalary; 
           else 
              return 0; 
     }

Using Qualification and Member Operators

You cannot use the C++ scope resolution operator '::', nor the C/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 desired scoped variable, and then used inside the SQL statement to refer to it. The following example shows the correct method to use:

     EXEC SQL BEGIN DECLARE SECTION; 
       char (& localName)[20] = ::name; 
     EXEC SQL END DECLARE SECTION; 
     EXEC SQL 
       SELECT name INTO :localName FROM STAFF 
       WHERE name = 'Sanders'; 

Handling Graphic Host Variables

To handle graphic data in C or C++ applications, use host variables based on either the wchar_t C/C++ data type or the sqldbchar data type provided by DB2. You can assign these types of host variables to columns of a table that are GRAPHIC, VARGRAPHIC, or DBCLOB. For example, you can update or select DBCS data from GRAPHIC or VARGRAPHIC columns of a table.

There are three valid forms for a graphic host variable:

Multi-byte Character Encoding

Some character encoding schemes, particularly those from east Asian countries require multiple bytes to represent a character. This external representation of data is called the multi-byte character code representation of a character and includes double-byte characters (characters represented by two bytes). Graphic data in DB2 consists of double-byte characters.

To manipulate character strings with double-byte characters, it may be convenient for an application to use an internal representation of data. This internal representation is called the wide-character code representation of the double-byte characters and is the format customarily used in the wchar_t C/C++ data type. There are ANSI C and X/OPEN Portability Guide 4 (XPG4) conformant subroutines available to process wide-character data and to convert data in wide-character format to and from multi-byte format.

Note that although an application can process character data in either multi-byte format or wide-character format, interaction with the database manager is done with DBCS (multi-byte) character codes only. That is, data is stored in and retrieved from GRAPHIC columns in DBCS format. The WCHARTYPE precompiler option is provided to allow application data in wide-character format to be converted to/from multi-byte format when it is exchanged with the database engine.

Selecting the wchar_t or sqldbchar Data Type

While the size and encoding of DB2 graphic data is constant from one platform to another for a particular code page, the size and internal format of the ANSI C or C++ wchar_t data type depends on which compiler you use and which platform you are on. The sqldbchar data type, however, is defined by DB2 to be two 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. For more information on UCS-2 data, see "Japanese and Traditional-Chinese EUC Code Set Considerations".

You can define all DB2 C graphic host variable types using either wchar_t or sqldbchar. You must use wchar_t if you build your application using the WCHARTYPE CONVERT precompile option (as described in "The WCHARTYPE Precompiler Option"). If you build your application with the WCHARTYPE NOCONVERT precompile option, you should use sqldbchar for maximum portability between different DB2 client and server platforms. You may use wchar_t with WCHARTYPE NOCONVERT, but only on platforms where wchar_t is defined as two bytes in length.

If you incorrectly use either wchar_t or sqldbchar in host variable declarations, you will receive an SQLCODE 15 (no SQLSTATE) at precompile time.

The WCHARTYPE Precompiler Option

Using the WCHARTYPE precompiler option, you can specify which graphic character format you want to use in your C/C++ application. This option provides you with the flexibility to choose between having your graphic data in multi-byte format or in wide-character format. There are two possible values for the WCHARTYPE option:

CONVERT
If you select the WCHARTYPE CONVERT option, character codes are converted between the graphic host variable and the database manager. For graphic input host variables, the character code conversion from wide-character format to multi-byte DBCS character format is performed before the data is sent to the database manager, using the ANSI C function wcstombs(). For graphic output host variables, the character code conversion from multi-byte DBCS character format to wide-character format is performed before the data received from the database manager is stored in the host variable, using the ANSI C function mbstowcs().

The advantage to using WCHARTYPE CONVERT is that it allows your application to fully exploit the ANSI C mechanisms for dealing with wide-character strings (L-literals, 'wc' string functions, etc.) without having to explicitly convert the data to multi-byte format before communicating with the database manager. The disadvantage is that the implicit conversions may have an impact on the performance of your application at run time, and may increase memory requirements.

If you select WCHARTYPE CONVERT, declare all graphic host variables using wchar_t instead of sqldbchar.

If you want WCHARTYPE CONVERT 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.
Note:The WCHARTYPE CONVERT precompile option is not currently supported in programs running on the DB2 Windows 3.1 client. For those programs, use the default (WCHARTYPE NOCONVERT).

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 multi-byte format when interfacing with the database manager.

If you select WCHARTYPE NOCONVERT, declare all graphic host variables using the sqldbchar type for maximum portability to other DB2 client/server platforms.

See the Command Reference for more information.

Other guidelines you need to observe are:

Notes:

  1. If you precompile C applications using the WCHARTYPE CONVERT option, DB2 validates the applications' graphic data on both input and output as the data is passed through the conversion functions. If you do not use the CONVERT option, no conversion of graphic data, and hence no validation occurs. In a mixed CONVERT/NOCONVERT environment, this may cause problems if invalid graphic data is inserted by a NOCONVERT application and then fetched by a CONVERT application. This data fails the conversion with an SQLCODE -1421 (SQLSTATE 22504) on a FETCH in the CONVERT application.

  2. The WCHARTYPE CONVERT precompile option is not currently supported for programs running on the DB2 Windows 3.1 client. In this case, use the default WCHARTYPE NOCONVERT option.

Japanese or Traditional-Chinese EUC Considerations

If your application code page is Japanese or Traditional-Chinese EUC, you can access GRAPHIC columns at a database server by using either the CONVERT or the NOCONVERT option, and wchar_t or sqldbchar graphic host variables, or input/output SQLDAs. In this section, DBCS format refers to the UCS-2 encoding scheme for EUC data. Consider the following cases:

To minimize conversions you can either use the NOCONVERT option and handle the conversions in your application, or not use GRAPHIC columns. Do not assign IBM-eucJP/IBM-eucTW CS0 (7-bit ASCII) and IBM-eucJP CS2 (Katakana) data to graphic host variables either after conversion to UCS-2 (if NOCONVERT is specified) or by conversion to the wide character format (if CONVERT is specified). This is because characters in both of these EUC code sets become single-byte when converted from UCS-2 to PC DBCS.

For general EUC application development guidelines, see "Japanese and Traditional-Chinese EUC Code Set Considerations".

Supported SQL Data Types

Certain predefined C and C++ data types correspond to the database manager column types. Only these C/C++ data types can be declared as host variables.

Table 16 shows the C/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.

Table 16. SQL Data Types Mapped to C/C++ Declarations
SQL Column Type1 C/C++ Data Type SQL Column Type Description
 
SMALLINT 
(500 or 501) 

 
short 
short int 

16-bit signed integer
 
INTEGER 
(496 or 497) 

 
long 
long int 

32-bit signed integer
 
REAL2
(480 or 481) 

float Single-precision floating point
 
DOUBLE3
(480 or 481) 

double Double-precision floating point
 
DECIMAL(p,s) 
(484 or 485) 

No exact equivalent; use double Packed decimal

(Consider using the CHAR and DECIMAL functions to manipulate packed decimal fields as character data.)

 
CHAR(1) 
(452 or 453) 

char Single character
 
CHAR(n) 
(452 or 453) 

No exact equivalent; use char[n+1] where n is large enough to hold the data
1<=n<=254
Fixed-length character string
 
VARCHAR(n) 
(448 or 449) 

struct tag { 
   short int; 
   char[n] 
   } 
  
1<=n<=4 000

Non null-terminated varying character string with 2-byte string length indicator
Alternately use char[n+1] where n is large enough to hold the data
1<=n<=4 000
null-terminated variable-length character string
Note:Assigned an SQL type of 460/461.
 
LONG VARCHAR 
(456 or 457) 

 
struct tag { 
   short int; 
   char[n] 
   } 
  
4 001<=n<=32 700

Non null-terminated varying character string with 2-byte string length indicator
CLOB(n) 
(408 or 409)

sql type is 
   clob(n) 
  
1<=n<=2 147 483 647

Non null-terminated varying character string with 4-byte string length indicator
CLOB locator variable4 
(964 or 965)

sql type is 
   clob_locator

Identifies CLOB entities residing on the server
CLOB file reference variable4
(808 or 809)

sql type is 
   clob_file

Descriptor for file containing CLOB data
BLOB(n) 
(404 or 405)

sql type is 
   blob(n) 
  
1<=n<=2 147 483 647

Non null-terminated varying binary string with 4-byte string length indicator
BLOB locator variable4 
(960 or 961)

sql type is 
   blob_locator

Identifies BLOB entities on the server
BLOB file reference variable4 
(804 or 805)

sql type is 
   blob_file

Descriptor for the file containing BLOB data
DATE 
(384 or 385)

null-terminated character form Allow at least 11 characters to accommodate the null-terminator.
VARCHAR structured form Allow at least 10 characters.
TIME 
(388 or 389)

null-terminated character form Allow at least 9 characters to accommodate the null-terminator.
VARCHAR structured form Allow at least 8 characters.
TIMESTAMP 
(392 or 393)

null-terminated character form Allow at least 27 characters to accommodate the null-terminator.
VARCHAR structured form Allow at least 26 characters.
Note:The following data types are only available in the DBCS or EUC environment when precompiled with the WCHARTYPE NOCONVERT option.
GRAPHIC(1) 
(468 or 469)

sqldbchar Single double-byte character
GRAPHIC(n) 
(468 or 469)

No exact equivalent; use sqldbchar[n+1] where n is large enough to hold the data
1<=n<=127
Fixed-length double-byte character string
VARGRAPHIC(n) 
(464 or 465)

struct tag { 
   short int; 
   sqldbchar[n] 
   } 
  
1<=n<=2 000

Non null-terminated varying double-byte character string with 2-byte string length indicator
Alternately use char[n+1] where n is large enough to hold the data
1<=n<=2 000
null-terminated variable-length double-byte character string
Note:Assigned an SQL type of 400/401.
LONG VARGRAPHIC 
(472 or 473)

struct tag { 
   short int; 
   sqldbchar[n] 
   } 
  
2 001<=n<=16 350

Non null-terminated varying double-byte character string with 2-byte string length indicator
Note:The following data types are only available in the DBCS or EUC environment when precompiled with the WCHARTYPE CONVERT option.
GRAPHIC(1) 
(468 or 469)

wchar_t
  • Single wide character (for C-type)
  • Single double-byte character (for column type)

GRAPHIC(n) 
(468 or 469)

No exact equivalent; use wchar_t [n+1] where n is large enough to hold the data
1<=n<=127
Fixed-length double-byte character string
VARGRAPHIC(n) 
(464 or 465)

struct tag { 
   short int; 
   wchar_t [n] 
   } 
 
1<=n<=2 000

Non null-terminated varying double-byte character string with 2-byte string length indicator
Alternately use char[n+1] where n is large enough to hold the data
1<=n<=2 000
null-terminated variable-length double-byte character string
Note:Assigned an SQL type of 400/401.
LONG VARGRAPHIC 
(472 or 473)

struct tag { 
   short int; 
   wchar_t [n] 
   } 
  
2 001<=n<=16 350

Non null-terminated varying double-byte character string with 2-byte string length indicator
Note:The following data types are only available in the DBCS or EUC environment.
DBCLOB(n) 
(412 or 413)

sql type is 
   dbclob(n) 
  
1<=n<=1 073 741 823

Non null-terminated varying double-byte character string with 4-byte string length indicator
DBCLOB locator variable4 
(968 or 969)

sql type is 
   dbclob_locator

Identifies DBCLOB entities residing on the server
DBCLOB file reference 
variable4
(812 or 813)

sql type is 
   dbclob_file

Descriptor for file containing DBCLOB data
Notes:
  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. These are the values that would appear 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
    • DOUBLE PRECISION
  4. This is not a column type but a host variable type.

The following is a sample SQL declare section with host variables declared for supported SQL data types.

   EXEC SQL BEGIN DECLARE SECTION; 
   ... 
        short     age = 26;               /* SQL type  500 */ 
        short     year;                   /* SQL type  500 */ 
        long      salary;                 /* SQL type  496 */ 
        long      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[5764]; 
                 } 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  808 */ 
        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  804 */ 
        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  812 */
        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 */ 
        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 */ 
   ... 
   EXEC SQL END DECLARE SECTION; 

The following are additional rules for supported C/C++ data types:

FOR BIT DATA

The standard C or C++ string type 460 should not be used 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.

SQLSTATE and SQLCODE Variables

When using the LANGLEVEL precompile option with a value of SQL92E, the following two declarations may be included as host variables:

  EXEC SQL BEGIN DECLARE SECTION;
    char  SQLSTATE[6] 
    long  SQLCODE; 
    .
    .
    .
  EXEC SQL END DECLARE SECTION;

If neither of these is specified, the SQLCODE declaration is assumed during the precompile step. Note that when using this option, the INCLUDE SQLCA statement should not be specified.

In an application that is made up of multiple source files, the SQLCODE and SQLSTATE variables may be defined in the first source file as above. Subsequent source files should modify the definitions as follows:

   extern long SQLCODE;                                              
   extern char SQLSTATE[6];


[ Top of Page | Previous Page | Next Page | Table of Contents | Index ]

[ DB2 List of Books | Search the DB2 Books ]