/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <windows.h>
#include <sql.h>
#include <sqlext.h>

char *constr = "Driver={IBM DB2 ODBC DRIVER};Database=Test;Hostname=localhost;Port=50000;Protocol=TCPIP;Uid=xxxx;Pwd=xxxx;";
char *sqlstr = "SELECT f2,COUNT(*) AS n FROM t1 WHERE f1 > 1 GROUP BY f2";

#define CHECK(stat, func) if((stat!=SQL_SUCCESS)&&(stat!=SQL_SUCCESS_WITH_INFO)) \
                          { \
                              printf("Error in " func "\n"); \
                              exit(EXIT_FAILURE); \
                          }

int main()
{
   SQLHENV env;
   SQLHDBC con;
   SQLHSTMT stmt;
   SQLRETURN stat;
   char outconstr[1024];
   int outconlen;
   char f2[50];
   int f2len;
   long int n;
   int nlen;
   stat = SQLAllocEnv(&env);
   CHECK(stat, "AllocEnv");
   stat = SQLAllocConnect(env, &con);
   CHECK(stat, "AllocConnect");
   stat = SQLDriverConnect(con, NULL,
                           (SQLCHAR *)constr, (SQLSMALLINT)strlen(constr),
                           (SQLCHAR *)outconstr, (SQLSMALLINT)sizeof(outconstr),
                           (SQLSMALLINT *)&outconlen, SQL_DRIVER_COMPLETE);
   CHECK(stat, "DriverConnect");
   stat = SQLAllocStmt(con, &stmt);
   CHECK(stat, "AllocStmt");
   stat = SQLExecDirect(stmt, (SQLCHAR *)sqlstr, strlen(sqlstr));
   CHECK(stat, "ExecDirect");
   stat = SQLBindCol(stmt, 1, SQL_C_CHAR, f2, sizeof(f2),(SQLINTEGER *)&f2len);
   CHECK(stat, "BindCol");
   stat = SQLBindCol(stmt, 2, SQL_C_LONG, &n, sizeof(n), (SQLINTEGER *)&nlen);
   CHECK(stat, "BindCol");
   for(;;)
   {
      stat = SQLFetch(stmt);
      if((stat!=SQL_SUCCESS)&&(stat!=SQL_SUCCESS_WITH_INFO)) break;
      f2[f2len] = '\0';
      printf("%s %d\n", f2, n);
   }
   SQLCloseCursor(stmt);
   SQLFreeStmt(stmt, SQL_DROP);
   SQLDisconnect(con);
   SQLFreeConnect(con);
   SQLFreeEnv(env);  
   return EXIT_SUCCESS;
}
