Connect to a MySQL DB using language C Linux

May 18, 2011

测试程序test.c:

#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");
    } 
    else 
    {
        printf("Init fails!\n");
    }
    return 0;
}

首先确认本机当前师父含有mysql.h这个头文件:

locate mysql.h

如果没有找到这个文件说明mysql安装的时候没有安装libmysqlclientXX-dev软件包,要调用mysql的C语言的api需要这个软件包,如果没有安装的话:

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/libmysqlclient.so.16
#先在/usr/include/mysql中的mysql.h,然后使用libmysqlclient.so.16这个动态链接库

或者是

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

Comments

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

    Avatar

Get In Touch With Us ...