DelphiFAQ Home Search:
General :: Databases :: mysql
General information about mysql - how to get around the differences between version 3.33 an 4, how to do stuff that you think you need a nested query for etc.

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

Stub to connect from a C program to mysql

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");
 }
 

Generated 12:00:32 on Sep 23, 2018