Connect to a MySQL DB using language C Linux

May 18, 2011


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

int main(int argc, char **argv)
    MYSQL mysql_conn; /* Connection handle */

    if (mysql_init(&mysql_conn) != NULL) 
        printf("Init succeeds!\n");
        printf("Init fails!\n");
    return 0;


locate mysql.h


sudo apt-get install libmysqlclient16-dev

安装成功后会在/usr/include/下创建名为mysql的文件夹,此时即可编译test.c,需要特别注意的是:实际调用mysql的api时侯不但需要调用mysql.h 头文件,而且需要与之对应的动态链接库。 以下是摘自The MySQL C API的一段话:

When you write a MySQL client program in C, you’ll need a C compiler, obviously. The examples shown here use gcc.You’ll also need the following in addition to your own source files:

  • The MySQL header files
  • The MySQL client library

The MySQL header files and client library constitute client programming support. They may be installed on your system already. Otherwise, you need to obtain them. If MySQL was installed from a source or binary distribution, client programming support should have been installed as part of that process. If >MySQL was installed from RPM files, this support won’t be present unless you installed the developer RPM. If you need to install the MySQL header files and library, see Appendix A.


gcc test.c -I /usr/include/mysql /usr/lib/


gcc -o test  -I /usr/include/mysql -lmysqlclient company_query.c 
# -lmysqlclient特指使用mysqlclient库编译程序
Posted by admin lmysqlclient , mysql , C


  1. 我遇到一个问题,就是怎么把这些加到makefile中?


Get In Touch With Us ...