2. Embedded SQL for C : Dynamic Programming for C : The SQLVAR Array : Pointer Usage with C Variables
 
Share this page                  
Pointer Usage with C Variables
In order to fill an element of the sqlvar array, you must set the type information and assign a valid address to sqldata. The address can be that of a dynamically allocated data area or a legal variable address. The address should always be cast to a pointer to a character (char *), as that is the base type of the sqldata field.
For example, the following fragment sets the type information and points at a dynamically allocated 4-byte integer and an 8-byte nullable floating-point variable.
Example: Pointer usage
/* Assume sqlda is a pointer to a dynamically allocated SQLDA */
sqlda->sqlvar[0].sqltype = IISQ_INT_TYPE;
sqlda->sqlvar[0].sqllen = sizeof(long);
sqlda->sqlvar[0].sqldata = (char *)calloc(1,
       sizeof(long));
sqlda->sqlvar[0].sqlind = (short *)0;
sqlda->sqlvar[1].sqltype = -IISQ_FLT_TYPE;
sqlda->sqlvar[1].sqllen = sizeof(double);
sqlda->sqlvar[1].sqldata = (char *)calloc(1,
       sizeof(double));
sqlda->sqlvar[1].sqlind = (short *)calloc(1,
       sizeof(short));
You can replace the three calls to the calloc allocation routine by references to program variables, such as:
...
sqlda->sqlvar[0].sqldata = (char *)&long_var;
...
sqlda->sqlvar[1].sqldata = (char *)&double_var;
sqlda->sqlvar[1].sqlind = (short *)&short_var;
Of course, in the latter case, it is appropriate to maintain a pool of available variables to use, such as arrays of differently typed variables.
When pointing at character data, you should allocate sqllen bytes plus one for the null, as in:
/* Assume 'sqltype' and 'sqllen' are set by DESCRIBE */
sqlda->sqlvar[0].sqltype = IISQ_CHA_TYPE;
sqlda->sqlvar[0].sqllen = some length;
sqlda->sqlvar[0].sqldata = (char*)calloc(1,sqlda-sqlvar[0].sqllen + 1);
When pointing at varchar data, you should allocate sqllen bytes plus two (or sizeof(short)) for the 2-byte length field. For example:
sqlda->sqlvar[0].sqltype = IISQ_VCH_TYPE;
sqlda->sqlvar[0].sqllen = 50;
sqlda->sqlvar[0].sqldata = (char *)calloc(1,
    sizeof(short) + 50);
You may also set the SQLVAR to point to a data handler for large object columns. For details, see Advanced Processing (see page Advanced Processing) in this chapter.