当前位置: 首页 > 图文教程 > 数据库 > MYSQL > Linux下mysql的C API简单使用
使用mysql的C API 可以轻松的连接mysql
#include <stdio.h> #include <stdlib.h> #include "/usr/include/mysql/mysql.h" int main(int argc, char** argv) { MYSQL *my_conn; MYSQL_RES *res; MYSQL_ROW row; my_conn=mysql_init(NULL); if(!mysql_real_connect(my_conn,"localhost","root","123","test",0,NULL,0)) { printf("Connect Error!\n"); exit(1); } if(mysql_query(my_conn,"select * from songfei")) { printf("Query Error!\n"); exit(1); } res=mysql_use_result(my_conn); printf("The result is:\n"); while((row=mysql_fetch_row(res))!=NULL) { printf("%s %s\n",row[0],row[1]); } mysql_free_result(res); mysql_close(my_conn); return 0; }
编译和连接程序
MySQL中有一个特殊的脚本,叫做mysql_config. 它会为你编译MySQL客户端,并连接到MySQL服务器提供有用的信息.你需要使用下面两个选项.
1. –libs 选项 - 连接MySQL客户端函数库所需要的库和选项.
$ mysql_config –libs
输出:
-L/usr/lib64/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib64 -lssl -lcrypto
2. –cflags 选项 - 使用必要的include文件的选项等等.
$ mysql_config –cflags
输出:
-I/usr/include/mysql -g -pipe -m64 -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing
你需要将上面两个选项加入到对源文件的编译命令中. 所以,要编译上面的程序,要使用下面的命令:
$ gcc -o output-file $(mysql_config –cflags) mysql_test.c $(mysql_config –libs)
评论 (0) All