Howto: Connect MySQL server using C program API under Linux or UNIX
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:
- mysql: MySQL client programs and shared library
- mysqlclient: Backlevel MySQL shared libraries (old libs)
- mysql-devel: Files for development of MySQL applications (a must have)
- mysql-server: Mysql server itself
- gcc, make and other development libs: GNU C compiler
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:
- MySQL C API - A must read - official MySQL C API documentation
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:
- Recover MySQL root password
- MySQL Proxy Load balancing and Failover Tutorial
- Save time use MySQL auto completion for database or table names
- MySQL create an Anonymous or limited access only account
- How to MySQL backup and data recovery with mysql-zrm
Discussion on This Article:
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!
Tags: c api, c program, development libs, gcc, gnu c compiler, linux c connect mysql, mysql client, mysql database server, mysql development, shared library



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.
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!
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?
David,
Thanks for the heads up!
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
Just install mysql-devel package
How do you specify the socket file?
Use mysql_real_connect() and set host to NULL socket to NULL or 0
See API doc for more help!
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
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
i want c code for FTP server and client.
any scaffolding for C available ? so i don’t have to
code add/edit/delete bla bla bla etc ?
thx
./output-file output not created while compile mysql-c-api.c in gcc as specified in procedure
plz anyone help me
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
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
Excelent Bro! thanks for the info. It helped me a lot.
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
shiva, if you have problems of this level, you shouldn’t be programming.
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..
a have 2 table or more, how to make connect n operation in c.
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