DelphiFAQ Home Search:

Stub to connect from a C program to mysql

 

commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.

Question:

I need a code stub to connect from a C program to mysql. I have never used the mysql C API before.

Answer:

The following should get you started. The source code is 'loader.c'.

Compile it with

gcc loader.c -o loader -I /usr/local/mysql/include -L /usr/local/mysql/lib -l mysqlclient

If you get error messages, check where your mysql is installed. Make sure that mysqlclient is on the lib search path.

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


int mysql_exec_sql(MYSQL *mysql,const char *create_definition) {
  return mysql_real_query(mysql,create_definition,strlen(create_definition));
}


int main() {
  MYSQL *mysql=NULL;
  MYSQL_RES *result;
  MYSQL_ROW row;
  char sQuery[1000];
  unsigned int num_fields;
  int i;

  if((mysql=mysql_init(mysql))==NULL) {
    printf("\nFailed to initate MySQL connection");
    exit(1);
  }

  if (!mysql_real_connect(mysql,"127.0.0.1","root","","qos",0,NULL,0)) {
    printf( "Failed to connect to MySQL: Error: %s\n", mysql_error(mysql));
    exit(1);
  }

  printf("Logged on to database sucessfully");

  strcpy(sQuery, "select count(*) from traffic");

  if(mysql_exec_sql(mysql,sQuery)==0) {
    result = mysql_store_result(mysql);
    // are there any rows??
    if (result) {
      num_fields = mysql_num_fields(result);
      while ((row = mysql_fetch_row(result))) {
        for(i = 0; i < num_fields; i++) {
          printf("[%s] ", row[i]);
        }
        printf("\n");
      }
      mysql_free_result(result);
     }
  }

  mysql_close(mysql);

  printf("\nDone.\n");
}

Comments:

 

 

Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option.
 
It seems that you are
from Washington, US .

Info/ Feedback on this

Show city and country
Show country only
Hide my location
Leave your comment here:
Please type in the code:
photo Add a picture:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity. The owner of this web site reserves the right to delete such material.