List:General Discussion« Previous MessageNext Message »
From:Sasha Pachev Date:May 5 1999 5:05pm
Subject:Re: C API - pls help
View as plain text  
"Naveen Yawanarajah (GTP)" wrote:
> 
> Hi List,
> 
> I'm at a COMPLETE LOSS.
> 
> Can anyone post a small C program that connects to a DB,
> carries out an SQL query or two (perhaps an INSERT and a SELECT)
> and then disconnects? This will help me get started, as I have no
> idea what .h files to #include, or even how to make an initial
> connection to mysql. I can use the mysqld in command-line type
> situations, but haven't had any luck locating an example c program.
> 
> I also need to know what how to compile and link the program so
> that it correctly links in the mysqlclient library.
> 
> Any help will be greatly appreciated.
> 
> Naveen

This is my first mysql C program I used to make sure
everying is working:

------------------cut here -----------------

#include <mysql.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

void check_error(MYSQL* mysql)
 {
  if(mysql_error(mysql)[0] != 0)
   {
    printf("Error: %s\n", mysql_error(mysql));
    mysql_close(mysql);
    exit(1);
   }
 }


int main(int c, char** argv)
 {
  MYSQL dbh;
  MYSQL_RES *res;
  int num_rows, num_fields;
  int i, j;
  MYSQL_ROW row;
  int *field_len_arr;

  puts("Connecting");

  mysql_connect(&dbh, "localhost", "scott", "tiger");
  check_error(&dbh);

  puts("Selecting the database");

  mysql_select_db(&dbh, "test_www");
  check_error(&dbh);

  puts("Running the query");

  mysql_query(&dbh, "select * from age_wage");
  check_error(&dbh);

  puts("Storing the result");

  res = mysql_store_result(&dbh);
  puts("Checking for error");
  check_error(&dbh);

  if(res == NULL)
   {
    puts("Error: res == NULL");
    mysql_close(&dbh);
    exit(1);
   }

  puts("getting num_rows");
  num_rows = mysql_num_rows(res);
  puts("getting num_fields");
  num_fields = mysql_num_fields(res);

  for(i = 0; i < num_rows; i++)
   {
    row = mysql_fetch_row(res);
    /*puts("getting field_len_arr"); */
    field_len_arr = mysql_fetch_lengths(res);

    if(field_len_arr == NULL)
     {
      puts("NULL field_len_arr");
      continue;
     }
   /*printf("num_rows = %d, num_fields = %d,
field_len_arr = %p\n", 
   num_rows, num_fields, field_len_arr);
   */
   printf("Fields: ");

    for(j = 0; j < num_fields; j++)
    {
     /*printf(" %d", field_len_arr[j]); */
     printf(" %s", row[j]);
    }

    printf("\n");

   }
  
  mysql_free_result(res);
  mysql_close(&dbh);
 }





----------cut here ---------------------------

-- 
Sasha Pachev
http://www.sashanet.com/ (home)
http://www.direct1.com/ (work)
Thread
C API - pls helpGTP)5 May
  • Re: C API - pls helpPaul DuBois5 May
  • Re: C API - pls helpSasha Pachev5 May