Linux下C语言连接MySQL

相对于Window下的设置,Linux要简单的很多。

1. 示例程序

$ vi mysql-c-api.c #include <stdio.h> #include "mysql/mysql.h" int main(){ MYSQL mysql; mysql_init(&mysql); mysql_options(&mysql,MYSQL_OPT_COMPRESS,0); mysql_options(&mysql,MYSQL_INIT_COMMAND,"SET autocommit=0"); if (!mysql_real_connect(&mysql,"10.2.3.4","user","passwd","database",0,NULL,0)) { fprintf(stderr, "Failed to connect to database: Error: %sn", mysql_error(&mysql)); } return 0; }

2. 编译命令

在MySQL编译后的二进制文件中,有一个很有用的二进制文件“mysql_config”(一般和mysql命令在同一个目录下),我们可以通过这个程序找到需要的头文件和连接库:

$ gcc -o a.out $(mysql_config --cflags) mysql-c-api.c $(mysql_config --libs) $ ./a.out

2 responses to “Linux下C语言连接MySQL”

  1. 有时候,Include有时候需要改为:
    #include “mysql.h”

  2. 收藏!

Leave a Reply

Your email address will not be published. Required fields are marked *