今天在自己的Ubuntu系统下安装了mysql,安装后就想赶快用C语言写个测试代码,测试一下它的C语言API的用法,我在网上看了看,就吧网上的一段代码复制一下去编译,发现找不到mysql_init的定义,也找不到mysql.h 这个文件,上网查了查,原来安装MYSQL的时候没有把相应的头文件和库放到系统里,还需要安装开发包,也就是安装libmysqlclient15-dev, 用sudo apt-get install libmysqlclient15-dev 安装后,代码就能编译通过,代码如下:
//test.c
#include <string.h>
#include <stdio.h>
#include <mysql/mysql.h>
int main()
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char server[20]={};
strcpy(server,"localhost");
char user[20];
strcpy(user,"root");
char password[20]={};
strcpy(password,"zhuguihua");
char database[20]={};
strcpy(database,"mysql");
conn=mysql_init(NULL);
if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0))
{
fprintf(stderr,"%s/n",mysql_error(conn));
exit(1);
}
if(mysql_query(conn,"show tables"))
{
fprintf(stderr,"%s/n",mysql_error(conn));
exit(1);
}
res=mysql_use_result(conn);
printf("mysql tables in mysql database:/n");
while((row=mysql_fetch_row(res))!=NULL)
printf("%s /n",row[0]);
mysql_free_result(res);
mysql_close(conn);
return 0;
}
gcc编译命令: gcc -o test test.c -llibmysqlclient