/* Simple ODBC example for Linux
   Arguments: datasource (name of your System or User DSN)
              UserID
              password
   Example:   ODBCexample datasource UserID password
   Rochester, MN, July 2005 */
#include <sql.h>
#include <stdio.h>
#include <stdlib.h>

/* Simple query to DB table very likely to exist. Takes first i5/OS "member" */
char querystring[] = "SELECT * FROM VIAGGIFAM.PWKCXM WHERE WKXSCX='KU'";

void
die (char *reason, SQLRETURN code)
{
  if (code != 0)
     {
       printf ("Error code: %d\n", code);
     }
  printf ("Failure because: %s\n", reason);
  exit (1);
}
int
main (int argc, char *argv[])
{
#define MAX_CONNECTIONS 5
  char field1[255]; /*receives values from table row fetch */
  char field2[255];
  char field3[255];
  SQLINTEGER retfld1;
  /* For completelness. */
  SQLINTEGER retfld2; /* For this example, NULL for SQLBindCol */
  SQLINTEGER retfld3; /* would be enough     */
  SQLHENV henv;
  SQLHDBC hdbc[MAX_CONNECTIONS]; /* For multiple connections */
  SQLHSTMT statement;
  SQLRETURN sqe = 0;
  SQLRETURN res = 0;
  /* allocate environment */
  if (SQLAllocEnv (&henv))
     die ("Alloc Environment", 0);
  /* allocate connection */
  if ((sqe = SQLAllocConnect (henv, &hdbc[0])))
     die ("Allocate Connect", sqe);
  /* connect to data base */
  if ((sqe = SQLConnect (hdbc[0], argv[1], SQL_NTS,
           argv[2], SQL_NTS, argv[3], SQL_NTS)))
     die ("Connect", sqe);
  /* allocate statement(s) */
  if (SQLAllocStmt (hdbc[0], &statement))
     die ("Alloc stmt", 0);
  /* Do query */
  if ((sqe = SQLExecDirect (statement, querystring, SQL_NTS)))
     die ("exec direct", sqe);
  /* Bind coming SQLFetch operations to fields */
  if ((sqe = SQLBindCol (statement, 1, SQL_CHAR, field1, 255, &retfld1)))
     die ("Bind field 1", sqe);
  if ((sqe = SQLBindCol (statement, 2, SQL_CHAR, field2, 255, &retfld2)))
     die ("Bind field 2", sqe);
  if ((sqe = SQLBindCol (statement, 3, SQL_CHAR, field3, 255, &retfld3)))
    die ("Bind field 3", sqe);
  /* While loop to fetch all records */
  res = SQLFetch (statement);
  /* field1,2,3 take new values each time */
  while (SQL_SUCCEEDED (res))
    {       /* Create tab separated values */
      printf ("%s\t%s\t%s\n", field1, field2, field3);
      res = SQLFetch (statement); /* next record */
    }
  /* end actual processing */
  /* free statement(s) pretty completely  */
  if (SQLFreeStmt (statement, SQL_DROP))
    die ("Free Statement with Drop", 0);
  /* close connection */
  if ((sqe = SQLDisconnect (hdbc[0])))
    die ("Disconnect ", sqe);
  if ((sqe = SQLFreeConnect (hdbc[0])))
    die ("Connection closed", sqe);
  /* free environment */
  if (SQLFreeEnv (henv))
    die ("Free Environment", 0);
  printf ("Success!\n");
  return 0;
}


