/*
** example1.c
** simple code to fetch data
**
** Klaus Thiele (kth@oblib.teuto.de) - June '95
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sql.h>
#include <errsql.h>

int failure( SQLTCUR csr, char *msg );

int main( void ) {

SQLTCUR   csr;        /* the Cursor                          */
SQLTROW   nrr;        /* number of rows in result-set        */
SQLTDAP   stmt;       /* SQL Statement                       */

char      nr[5];
char      name[46];
int       age;
double    money;
char      flag;

   /* connect cursor to local database */
   if( sqlcnc(&csr, "SQLBASE/SYSADM/SYSADM", 0, NULL) ) {
         printf("CONNECT failed.\n");
         return( 1 );
   } else
      printf("Connection Established\n");

   /* set result set mode */
   if( sqlsrs( csr ) )
      failure( csr, "sqlsrs" );

   /* setup statement */
   stmt = "SELECT NR, NAME, AGE, MONEY, FLAG FROM PERSDAT "
                 "WHERE NAME LIKE :1 "
                 "ORDER BY AGE DESC";

   /* compile statement */
   if( sqlcom(csr, stmt, 0) )
      failure(csr, "COMPILE");

   /* set bind variable */
   if( sqlbnn(csr, 1, name, 0, 0, SQLPSTR) )
      failure( csr, "BIND" );

   /* set select buffer */
   if( sqlssb(csr, 1, SQLPSTR, nr, sizeof(nr), 0, SQLNPTR, SQLNPTR) ||
       sqlssb(csr, 2, SQLPSTR, name, sizeof(name), 0, SQLNPTR, SQLNPTR) ||
       sqlssb(csr, 3, SQLPSIN, (SQLTDAP)&age, sizeof(age), 0, SQLNPTR, SQLNPTR) ||
       sqlssb(csr, 4, SQLPDOU, (SQLTDAP)&money, sizeof(money), 0, SQLNPTR, SQLNPTR) ||
       sqlssb(csr, 5, SQLPSCH, (SQLTDAP)&flag, sizeof(flag), 0, SQLNPTR, SQLNPTR) )
      failure( csr, "SET BUFFER" );

   /* initialize the bind-variable */
   strcpy( name, "%Thiele%" );

   /* execute the statement */
   if( sqlexe(csr) )
      failure(csr, "EXECUTE");

   /* get # of rows in result set */
   if( sqlnrr(csr, &nrr) )
      failure(csr, "SQLNRR");

   printf("Number of rows: %ld\n", nrr);


   /* fetch rows */
   while( sqlfet(csr) == 0 )
      printf("sqlfet: %s - %s, %d, %.2f, %c\n", nr, name, age, money, flag);


   /* disconnect cursor */
   if( sqldis(csr) )
      printf("DISCONNECT failed\n");
   else
      printf("Disconnect Performed\n");

   return(0);
}

int failure( SQLTCUR csr, char *msg ) {

SQLTRCD rcd;
char    errmsg[SQLMERR];

   sqlrcd(csr, &rcd);
   sqlerr(rcd, errmsg);
   printf("Failure on %s\n", msg);
   printf("[%d]: %s\n", rcd, errmsg);
   sqldis(csr);

   exit( 1 );
}
