想写一个c语言链接mysql数据库的demo,但是因为在mac的环境下十分的不方便,走了不少的坑,这里记录一下,帮助其他小伙伴。
1、mac下安装libmysqlclient
brew install mysql
2、建立软连接
sudo ln -s /usr/local/mysql/lib/libmysqlclient.21.dylib /usr/local/lib/libmysqlclient.21.dylib
上面这两步很重要,之前一直没有进行第一步,所以进行第二步的时候mac又一直提示没有权限,试了好多办法,最后执行了第一步安装了libmysqlclient再执行第二步就可以了。
3、编写c程序
#include <stdio.h> #include <mysql.h> int main() { MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; char *server = "localhost"; char *user = "root"; char *password = "li980314"; char *database = "news"; char *query = "SELECT * FROM `news`"; int t, r; conn = mysql_init(NULL); if(!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { printf("Error connecting to database:%s\n", mysql_error(conn)); } else { printf("Connected...\n"); } t = mysql_query(conn, query); if(t) { printf("Error making query:%s\n", mysql_error(conn)); } else { printf("Query made...\n"); res = mysql_use_result(conn); if(res) { while((row = mysql_fetch_row(res)) != NULL) { //printf("num = %d\n", mysql_num_fields(res)); //列数 for(t = 0; t < mysql_num_fields(res); t++) { printf("%8s ", row[t]); } printf("\n"); } } mysql_free_result(res); } mysql_close(conn); return 0; }
4、编译
gcc -I /usr/local/mysql/include/ -L /usr/local/mysql/lib/ mysql.c -o mysql.out -lmysqlclient
5、运行