10. Understanding ODBC Connectivity : ODBC Programming : Fetched Data : SQLGetData() and SQLBindCol()--Bind Fetched Data
 
Share this page                  
SQLGetData() and SQLBindCol()--Bind Fetched Data
The previous SQLFetch() example fetches rows from the database, but does not make the data available to the application. The functions SQLGetData() and SQLBindCol() bind the fetched data to variables in the application. SQLGetData() binds the variables after the fetch; SQLBindCol() binds the variables before the fetch. SQLGetData() and SQLBindCol() can be used separately or together, although it is somewhat redundant to do both.
The following example expands the SQLFetch() example to show the use of SQLGetData() and SQLBindCol():
RETCODE rc = SQL_SUCCESS;
SQLCHAR model[21] = "\0";
SQLINTEGER orind = SQL_NTS;
SQLINTEGER orind1 = SQL_NTS;
 
/*
** Execute the select query.
*/
SQLExecDirect( hstmt, "select model from cars", SQL_NTS );
 
/*
** Bind the column to be fetched.
*/
SQLBindCol( hstmt,   /* Statement handle */
    1,               /* Column Number */
    SQL_C_CHAR,      /* C type of variable */
    model,           /* The fetched data */
    20,              /* Maximum length */
    &orind );        /* Status or length indicator */
 
/*
** Fetch the data in a loop.
*/
while ( TRUE )
{
    rc = SQLFetch( hstmt );
 
    /*
    ** Break out of the loop if end-of-data is reached.
    */
    if (rc == SQL_NO_DATA_FOUND)
    {
        printf("End of data.\n" );
        break;
    }
    /*
    ** Break out of the loop if an error is found.
    */
    if ( !SQL_SUCCEEDED( rc ) )
    {
        printf("Error! status is %d\n", rc );
        break;
    }
    /*
    ** Re-bind the data to be fetched (redundant in this
    ** case).
    */
    SQLGetData( hstmt,  /* Statement handle */
        1,              /* Column number */
        SQL_C_CHAR,     /* C type of variable */
        model,          /* The fetched data */
        20,             /* Maximum length */
        &orind1 );      /* Status or length indicator */
 
    printf("model of car: %s\n", model );
}
The above example works, but would work just as well if only SQLBindCol() or SQLGetData() were called. Both are included in the example to show how they are used. Note that SQLBindCol() is called only once and serves to bind data for all successive fetches. SQLGetData() is called after every fetch. SQLGetData() is called in this way to fetch variable-length data, such as large objects.