About nixCraft

Topics

Howto: Connect MySQL server using C program API under Linux or UNIX

Posted by Vivek Gite [Last updated: October 8, 2007]

From my mailbag:

How do I write a C program to connect MySQL database server?

MySQL database does support C program API just like PHP or perl.

The C API code is distributed with MySQL. It is included in the mysqlclient library and allows C programs to access a database.

Many of the clients in the MySQL source distribution are written in C. If you are looking for examples that demonstrate how to use the C API, take a look at these clients. You can find these in the clients directory in the MySQL source distribution.

Requirements

Make sure you have development environment installed such as gcc, mysql development package etc. Following is the list summarize the list of packages to compile program:

Sample C Program

Following instructions should work on any Linux distro or UNIX computer. Here is the small program that connects to mysql server and list tables from mysql database.(download link):

/* Simple C program that connects to MySQL Database server*/
#include <mysql.h>
#include <stdio.h>

main() {
   MYSQL *conn;
   MYSQL_RES *res;
   MYSQL_ROW row;

   char *server = "localhost";
   char *user = "root";
   char *password = "PASSWORD"; /* set me first */
   char *database = "mysql";

   conn = mysql_init(NULL);

   /* Connect to database */
   if (!mysql_real_connect(conn, server,
         user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   /* send SQL query */
   if (mysql_query(conn, "show tables")) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   res = mysql_use_result(conn);

   /* output table name */
   printf("MySQL Tables in mysql database:\n");
   while ((row = mysql_fetch_row(res)) != NULL)
      printf("%s \n", row[0]);

   /* close connection */
   mysql_free_result(res);
   mysql_close(conn);
}

How do I compile and link program against MySQL libs?

MySQL comes with a special script called mysql_config. It provides you with useful information for compiling your MySQL client and connecting it to MySQL database server. You need to use following two options.
Pass --libs option - Libraries and options required to link with the MySQL client library.

$ mysql_config --libs
Output:

-L/usr/lib64/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib64 -lssl -lcrypto

Pass --cflags option - Compiler flags to find include files and critical compiler flags and defines used when compiling the libmysqlclient library.
$ mysql_config --cflags
Output:

-I/usr/include/mysql -g -pipe -m64 -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing

You need to pass above option to GNU C compiler i.e. gcc. So to compile above program, enter:
$ gcc -o output-file $(mysql_config --cflags) mysql-c-api.c $(mysql_config --libs)
Now execute program:
$ ./output-file
Output:

MySQL Tables in mysql database:
columns_priv
db
func
help_category
help_keyword
help_relation
help_topic
host
tables_priv
time_zone
time_zone_leap_second
time_zone_name
time_zone_transition
time_zone_transition_type
user 

References:

E-mail this to a Friend    Printable Version

Is your site working? Monitor Your Web Site 24/7. Get SMS alerts on server downtime. Free 30-day trial including 20 SMS!

You may also be interested in other helpful articles:

Discussion on This Article:

  1. Jonathan Arnold Says:

    One thing to be aware of though with the mysql library - there is licensing involved. It was complicated enough that our company backed off from MySQL and went with SQLite.

  2. vivek Says:

    Jonathan,

    You have raised an excellent point.

    MySQL dual Licensing policy is bit dangerous; if you are giving out GPL code it can be done with GPL; otherwise it force commercial vendor under its own terms and condition.

    PGSQL or SQLite seems to good alternative.

    Appreciate your post!

  3. david Says:

    I’m no C guru, but I think there’s a typo. shouldn’t you run:

    ./output-file

    or compile with:

    -o output.file

    Or, am I missing something?

  4. vivek Says:

    David,

    Thanks for the heads up!

  5. debakanta sandha Says:

    i want to connect mysql from c program in linux mandriva 2007.i am not being able to do it as mysql.h is not there in mandriva 2007

  6. vivek Says:

    Just install mysql-devel package

  7. John Matthews Says:

    How do you specify the socket file?

  8. vivek Says:

    Use mysql_real_connect() and set host to NULL socket to NULL or 0

    mysql_real_connect(&mysql, 0, username, password, dbname, 0, 0, 0 ); 

    See API doc for more help!

  9. Edwind Says:

    how i do a makefile that compile me the .c?

    it has to find the result of mysql_config –libs and –cflags and put it in the gcc -o line

    thx in advance

  10. Walther Says:

    Hi Edwind,

    I’m not big on c-fu, but you should “vi Makefile” in the directory where you have your .c program and in the Makefile, you should type something along the lines of:

    MYSQLCFLAGS=`mysql_config –cflags`
    MYSQLLIBS=`mysql_config –libs`
    datafoxclient:
    $(CC) -I/usr/include/mysql -o datafoxclient $(MYSQLCFLAGS) datafoxclient.c $(MYSQLLIBS)
    clean:
    rm -f datafoxclient

    some of the c-fu gurus would probably tell you that my Makefile is broken and not that good! But, hey, it works for me :)

    hope that helps :)

  11. anil Says:

    i want c code for FTP server and client.

  12. bedjo Says:

    any scaffolding for C available ? so i don’t have to
    code add/edit/delete bla bla bla etc ?

    thx

  13. siva Says:

    ./output-file output not created while compile mysql-c-api.c in gcc as specified in procedure
    plz anyone help me

  14. semarsuper Says:

    Combining your script there with memcached C API (http://danga.com/memcached/apis.bml) will also boost the performance, instead of directly querying to mysqld.

    Rgds,

    semarsuper

  15. Saiful Islam Says:

    i m facing a error message when wanna run output file-
    “error while loading shared libraries: libmysqlclient.so.15: cannot open shared object file: No such file or directory”

    would anyone help me to over come this prob.

    thanks
    Saiful

  16. Skatox Says:

    Excelent Bro! thanks for the info. It helped me a lot.

  17. shiva Says:

    i hav followed same procedure which is given above for executing n i m getting an error message when wanna run output file-
    “Access denied for user ‘root’@'localhost’ (using password: YES)” Can anyone tell me how to fix this prob. Pleeeeeeeeeeeeease

  18. tomato Says:

    shiva, if you have problems of this level, you shouldn’t be programming.

  19. champ Says:

    I encountered with problems about it, but when I see your site and apply what you said, I could finally succeed it.

    Thanks a lot..

  20. zackaria Says:

    a have 2 table or more, how to make connect n operation in c.

  21. kishore Says:

    hi,thanks for the code which you gave but i am getting some errors.i tried running the code on ubuntu8.04,when i execute the 1st statement –\”$ mysql_config –libs\” i get the output as -Wl,-Bsymbolic-functions -L/usr/lib/mysql -lmysqlclient
    and when i execut the 2nd statement i get the output as -I/usr/include/mysql -DBIG_JOINS=1 -fPIC

    i am not able to get the output as mentioned in the post.Can anyone please help me??
    Also can anyone tell me what is the output file in the 3rd statement.

    thankyou :)

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Tags: , , , , , , , , ,

Copyright © 2004-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.