#include <stdio.h>
#include "sql.h"

/*----------------------------------------------------------------*/
/*  Example of bind by number					                        */
/*----------------------------------------------------------------*/

SQLTCUR cur = 0;		/* SQLBASE cursor number  */
SQLTRCD rcd = 0;		/* SQLBASE return code	  */

void failure(char *p);
int strscn(char *p, char c);

int main( void ) {

FILE*     fp; 		/* file pointer 	  */
SQLTDAP   cp; 		/* character pointer	  */
SQLTDAL   length;	/* length		  */
SQLTBNN   bnn;		/* bind number		  */
SQLTNBV   nbv;		/* # of bind variables	  */
char	  line[80];	/* input line		  */

static	  char	    ctbcom[] =		/* CREATE TABLE command   */
"CREATE TABLE X (A INTEGER, B CHAR(10), C CHAR(30), D REAL)";

static	  char	    inscom[] =		/* INSERT command	  */
"INSERT INTO X(A, B, C, D) VALUES (:1, :2, :3, :4)";

  /*
  ** CONNECT TO THE DATABASE
  */
  if (rcd = sqlcnc(&cur, "SQLBASE", 0, NULL))
    failure("CONNECT");

  /*
  ** CREATE THE TABLE
  */
  if (sqlcex(cur, ctbcom, 0))
    failure("CREATE TABLE");

  /*
  ** COMPILE THE INSERT COMMAND
  */
  if (sqlcom(cur, inscom, 0))
    failure("INSERT COMPILE");

  /*
  ** INSERT THE DATA
  */
  if (!(fp = fopen("data", "r")))	/* open input file	  */
    failure("FILE OPEN");

  while (fgets(line, sizeof(line), fp)) /* read the input	  */
  {
    line[strlen(line) - 1] = 0; 	/* remove new line char   */

    sqlnbv(cur, &nbv);	/* OPTIONAL: could hard code a value of 4 */

    for (cp = line, bnn = 1;		/* scan the line	  */
	         bnn <= nbv; bnn++)
    {
      length = strscn(cp, ','); 	/* locate comma 	  */
      sqlbnn(cur, bnn, cp, length, 0, SQLPBUF);
      cp += length;			/* locate end		  */
      if (*cp == ',')			/* comma?		  */
	      cp++;
    }

    if (sqlexe(cur))			/* insert row		  */
      failure("INSERT EXECUTE");
  }

  /*
  ** DISCONNECT FROM THE DATABASE
  */
  if (rcd = sqldis(cur))
  {
    cur = 0;
    failure("DISCONNECT");
  }

  return(0);
}

int strscn(char *p, char c) {

char*  cp; 		/* character pointer	  */

  for (cp = p; *cp && *cp != c; cp++);	/* scan string		  */
  return (int)(cp - p); 		/* return position	  */
}

void failure(char *p) {

SQLTEPO   epo;		/* error position	  */
char      errmsg[SQLMERR];

    sqlrcd(cur, &rcd);			/* get the error	  */
    sqlepo(cur, &epo);			/* get error position	  */
    sqlerr(rcd,(SQLTDAP)&errmsg);
    sqldis(cur);

  printf("Failure on %s rcd=%d, epo=%d\n%s\n",p,rcd,epo,errmsg);
  exit(1);
}

