SQL Characteristic Functions

C API's

How to compile the program:



gcc -L/usr/local/lib/mysql -I/usr/local/include/mysql -o select select.c   -lmysqlclient
*/



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

int
main (char **args)
{
  MYSQL_RES *result;
  MYSQL_ROW row;
  MYSQL_FIELD *fields;
  MYSQL *connection, mysql;
  int state, nfields, i;
  char *qbuf;

  qbuf = (char *) malloc (sizeof (char) * 1000);
  if (qbuf == NULL)
    {
      fprintf (stderr, "Out of memory. Exiting!
");
      exit (1);
    }


  mysql_init (&mysql);
  connection =
    mysql_real_connect (&mysql, "localhost", "UserName", "Password",
"Database", 0, 0, 0);

  if (connection == NULL)
    {
      printf ("%s
", mysql_error (&mysql));
      return 1;
    }



  strcpy (qbuf, "select name, ");
  strcat (qbuf, " sum(score*(1-abs(sign(exam-1)))) as exam1, ");
  strcat (qbuf, " sum(score*(1-abs(sign(exam-2)))) as exam2, ");
  strcat (qbuf, " sum(score*(1-abs(sign(exam-3)))) as exam3, ");
  strcat (qbuf, " sum(score*(1-abs(sign(exam-4)))) as exam4 ");
  strcat (qbuf, " from exams group by name ");

  if (mysql_query (connection, qbuf))
    {
      fprintf (stderr, "Query failed (%s)
", mysql_error (connection));
      exit (1);
    }




  result = mysql_store_result (connection);
  printf ("Rows: %d
", mysql_num_rows (result));
  printf ("Cols: %d
", mysql_num_fields (result));
  nfields = mysql_num_fields (result);

  /* precess field names */
  fields = mysql_fetch_fields (result);
  for (i = 0; i < nfields; i++)
    {
      printf ("%s	", fields[i].name);
    }
  printf ("
");
  /* process each row in the result set */
  while ((row = mysql_fetch_row (result)) != NULL)
    {
      for (i = 0; i < nfields; i++)
{
  printf ("%s	", row[i]);
}
      printf ("
");
    }

  mysql_free_result (result);
  mysql_close (connection);

}


Data