环境:阿里云主机 centos 7.3 64位
1.从Mysql官网下载代码包(linux generic版)
- mysql-connector-c-6.1.2-linux-glibc2.5-x86_64.tar.gz,
- 相应的devel:mysql-connector-c-devel-6.1.2-1.linux_glibc2.5.x86_64.rpm(不安这个会报缺少头文件的错误,也可直接用yum install mysql-devl安装)
2.安装mysql-connector-c-devel-6.1.2-1.linux_glibc2.5.x86_64:
rpm -ivh mysql-connector-c-devel-6.1.2-1.linux_glibc2.5.x86_64.rpm
rpm -ql mysql-connector-c-devel-6.1.2-1.linux_glibc2.5.x86_64.rpm #查看安装位置
3.安装mysql-connector-c-6.1.2-linux-glibc2.5-x86_64.tar
tar -xvf mysql-connector-c-6.1.2-linux-glibc2.5-x86_64.tar.gz
cd mysql-connector-c-6.1.2-linux-glibc2.5-x86_64
#创建头文件以及库目录
mkdir /usr/include/mysql
mkdir /usr/lib64/mysql
#复制到目录下
cp lib/* /usr/lib64/mysql/
cp include/* /usr/include/mysql/
#为系统添加库目录路径
vim /etc/ld.so.conf
/usr/lib64/mysql #添加在最后并保存退出
ldconfig #加载新添加的路径
4.编写客户端程序
//client.c
#include <stdio.h>
#include "mysql.h"
int main()
{
MYSQL sql;
mysql_init(&sql); //初始化MYSQL结构体
if (&sql==NULL)
{
printf("init errorn");
return 1;
}
//连接失败就打印具体的错误信息
//用户为root@localhost, 密码是12345, 数据库是test
if(NULL==mysql_real_connect(&sql,"localhost","root","12345","test",0,NULL,0))
{
printf("connect errorn");
printf("error:%d: %sn",mysql_errno(&sql),mysql_error(&sql));
return 1;
}
printf("connect successn");
mysql_close(&sql);
return 0;
}
5.编译并运行
gcc -I/usr/include/mysql -L/usr/lib64/mysql -lmysqlclient -o client client.c
#-I指定include目录,-L指定lib目录,-l不加会报client.c:(.text+0x17): undefined reference to #`mysql_init'等变量未定义的错误
./client
#如果提示connect success则成功