Click here to Skip to main content
15,610,907 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, i'm new in C++ and using the ODBC Api from Microsoft.
My question is how i retrieve the result of:
SQLExecDirect(hstmt, "Select Count(*) From Table", SQL_NTS);

It is a little confuse to me the use of the ODBC Api.

[no name] 20-Oct-14 15:23pm
Member 11086796 20-Oct-14 15:37pm    
Thanks for answer, I have already read the msdn, but I didn't understood it, so if you could post here an example code, i would be very grateful.
[no name] 20-Oct-14 15:46pm    
And the problem with the sample code provided by the documentation would be...?
PIEBALDconsult 20-Oct-14 16:56pm    
I think you now need SQLFetch, but it's been a few months since I was looking at the ODBC API.
PIEBALDconsult 20-Oct-14 23:37pm    
When I was dabbling in ODBC a few months back it was with the following book:
which I had bought back in 1999. The information is still relevent.

1 solution

ODBC is a kind of API that is more easily understood by example.

#include <stdio.h>
#include <sql.h>
#include <sqlext.h>
int main() {
    SQLHENV henv;  SQLHDBC hdbc;  SQLHSTMT hstmt;  SQLRETURN rc;
    /* allocate handles and connect */
    SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);
    SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
    rc = SQLConnect(hdbc, "dsn", SQL_NTS, "user", SQL_NTS, "pwd", SQL_NTS);
    if (!SQL_SUCCEEDED(rc)) { /* couldn't connect, process error, free resources */ }
    /* create a cursor and execute a statement */
    SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
    rc = SQLExecDirect(hstmt, "Select Count(*) From Table", SQL_NTS);
    if (!SQL_SUCCEEDED(rc)) { /* couldn't exec sql, process error, free resources */ }
    /* fetch the result: here we expect single row with single column */
    rc = SQLFetch(hstmt);
    if (!SQL_SUCCEEDED(rc)) { /* couldn't fetch row, process error, free resources */ }
    /* extract data from the fetched row */
    SQLINTEGER indicator;  long count;
    rc = SQLGetData(hstmt, 1, SQL_C_LONG, &count, sizeof(count), &indicator);
    if (!SQL_SUCCEEDED(rc)) { /* couldn't convert to int, process error, free resources */ }
    if (indicator == SQL_NULL_DATA) { /* unexpected NULL, process error, free resources */ }
    printf("count = %ld\n", count);
    /* free resources: close the cursor */
    SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
    /* disconnect from db */
    SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
    SQLFreeHandle(SQL_HANDLE_ENV, henv);
    return 0;

Here is a compressed tutorial from EasySoft.[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900