This example is a modified version of the example contained in the X/Open SQL CLI document. It shows the execution of interactive SQL statements, and follows the flow described in Chapter 2. "Writing a DB2 CLI Application".
/* From CLI sample samputil.c */
/* ... */
/* print_results */
SQLRETURN print_results( SQLHANDLE hstmt ) {
SQLCHAR colname[32] ;
SQLSMALLINT coltype ;
SQLSMALLINT colnamelen ;
SQLSMALLINT nullable ;
SQLUINTEGER collen[MAXCOLS] ;
SQLSMALLINT scale ;
SQLINTEGER outlen[MAXCOLS] ;
SQLCHAR * data[MAXCOLS] ;
SQLCHAR errmsg[256] ;
SQLRETURN rc ;
SQLSMALLINT nresultcols, i ;
SQLINTEGER displaysize ;
rc = SQLNumResultCols( hstmt, &nresultcols ) ;
CHECK_HANDLE( SQL_HANDLE_STMT, hstmt, rc ) ;
for ( i = 0; i < nresultcols; i++ ) {
SQLDescribeCol( hstmt,
( SQLSMALLINT ) ( i + 1 ),
colname,
sizeof(colname),
&colnamelen,
&coltype,
&collen[i],
&scale,
NULL
) ;
/* get display length for column */
SQLColAttribute( hstmt,
( SQLSMALLINT ) ( i + 1 ),
SQL_DESC_DISPLAY_SIZE,
NULL,
0,
NULL,
&displaysize
) ;
/*
Set column length to max of display length,
and column name length. Plus one byte for
null terminator.
*/
collen[i] = max( displaysize,
strlen( ( char * ) colname )
) + 1 ;
printf( "%-*.*s",
( int ) collen[i],
( int ) collen[i],
colname
) ;
/* allocate memory to bind column */
data[i] = ( SQLCHAR * ) malloc( ( int ) collen[i] ) ;
/* bind columns to program vars, converting all types to CHAR */
SQLBindCol( hstmt,
( SQLSMALLINT ) ( i + 1 ),
SQL_C_CHAR,
data[i],
collen[i],
&outlen[i]
) ;
}
printf( "\n" ) ;
/* display result rows */
while ( SQLFetch( hstmt ) != SQL_NO_DATA ) {
errmsg[0] = '\0' ;
for ( i = 0; i < nresultcols; i++ ) {
/* Check for NULL data */
if ( outlen[i] == SQL_NULL_DATA )
printf( "%-*.*s",
( int ) collen[i],
( int ) collen[i],
"NULL"
) ;
else { /* Build a truncation message for any columns truncated */
if ( outlen[i] >= collen[i] ) {
sprintf( ( char * ) errmsg + strlen( ( char * ) errmsg ),
"%d chars truncated, col %d\n",
( int ) outlen[i] - collen[i] + 1,
i + 1
) ;
}
/* Print column */
printf( "%-*.*s",
( int ) collen[i],
( int ) collen[i],
data[i]
) ;
}
} /* for all columns in this row */
printf( "\n%s", errmsg ) ; /* print any truncation messages */
} /* while rows to fetch */
/* free data buffers */
for ( i = 0; i < nresultcols; i++ ) {
free( data[i] ) ;
}
return( SQL_SUCCESS ) ;
} /* end print_results */