Mysql Select
2002-01-05 20:51:01
Category: c:database
Description: How to do a simple connection and select with mysql
Author: detour
Viewed: 7824
Rating: (64 votes)


/* mysqlclient.c written by detour@metalshell.com
 * 
 * This example will connect to a mysql database and select
 * all rows from your table
 *
 * Note: When compiling you need to include libmysqlclient.so
 *       assuming that libmysqlclient.so is in /usr/lib use
 *         gcc -o mysqlclient mysqlclient.c -lmysqlclient
 *
 *       If you have libmysqlclient.a or you get a compression
 *       error use
 *         gcc -o mysqlclient mysqlclient.c -lz /path/to/libmysqlclient.a
 *
 * http://www.metalshell.com/
 *
 */
 
#include <stdio.h>
#include <stdlib.h>
/* Your mysql.h may be located differently */
#include "/usr/local/mysql/include/mysql.h"
 
#define table "yourtable"
#define host "localhost"
#define user "user"
#define pass "pass"
#define db "database"
 
int main() {
  MYSQL mysql;
  MYSQL_RES *res;
  MYSQL_ROW row;
 
  int i=0;
  char query[50];
 
  /* make connection to the database */
  if(!(mysql_connect(&mysql,host,user,pass)))
    {
      fprintf(stderr,"mysql_connect() Failed: %s\n",mysql_error(&mysql));
      exit(1);
    }
 
  /* the database we will use */
  if(mysql_select_db(&mysql,db))
    {
      fprintf(stderr,"mysql_select_db() Failed: %s\n", mysql_error(&mysql));
      exit(1);
    }
 
  /* Setup the query */
  sprintf(query,"select * from %s", table);
  if(mysql_query(&mysql,query))
    {
      fprintf(stderr,"mysql_query() Failed: %s\n", mysql_error(&mysql));
      exit(1);
    }
 
  /* store the result from our query */
  res = mysql_store_result(&mysql);
 
  /* fetch each row from our result and print it */
  while((row = mysql_fetch_row(res))) {
    for(i=0;i<mysql_num_fields(res);i++)
      printf("%s\n",row[i]);
  }
 
  /* clean up */
  mysql_free_result(res);
  mysql_close(&mysql);
 
}