linux cpp连接并查询mysql

linux C API连接并查询mysql5.7.9

Posted by Liangjf on April 9, 2019

linux C API连接并查询mysql5.7.9

开发环境:

  • ubuntu16.04
  • mysql5.7.9
  • 原生C API
  • VIM

配置远程连接

配置mysql允许远程连接的方法默认情况下,mysql只允许本地登录,如果要开启远程连接,则需要修改/etc/mysql/my.conf文件。

一、修改/etc/mysql/my.conf

找到bind-address = 127.0.0.1这一行 改为bind-address = 0.0.0.0即可

二、为需要远程登录的用户赋予权限

  • 1、新建用户远程连接mysql数据库

      grant all on *.* to admin@'%' identified by '123456' with grant option; 
      flush privileges;
    
    • 允许任何ip地址(%表示允许任何ip地址)的电脑用admin帐户和密码(123456)来访问这个mysql server。注意admin账户不一定要存在。
  • 2、支持root用户允许远程连接mysql数据库

      grant all privileges on *.* to 'root'@'%' identified by '123456' with grant option;
      flush privileges;
    

修改完后重启mysql服务

sudo systemctl restart mysqld

演示连接demo

github源码地址

编译运行

  • 查找依赖的头文件 mysql_config --include

  • 建立.so库的软连接,供可执行文件调用 sudo ln -s /usr/local/mysql/lib/libmysqlclient.so.20 /usr/lib/

  • 编译 gcc -o test_mysql test_mysql.c -I/usr/local/mysql/include -L/usr/local/mysql/lib/ -lmysqlclient

  • 结果 ``` liangjf@ubuntu:~/study/mysql$ ./test_mysql
    共9个记录,每个记录3字段 id name phone

1 aaa 7774090 2 abc 7774099 3 acb 7794099 4 bcb 8794099 5 bcc 8894099 6 qwe 8494099 7 azq 6544099 8 njhu 8544099 9 ert 1544099 ```

出现的问题:

fatal error: mysql/plugin_auth_common.h

查找是有这个问题,但是编译失败,证明是编译时指定的mysql/include路径错误了

liangjf@ubuntu:~/study/mysql$ sudo find / -name plugin_auth_common.h
/usr/local/mysql-5.7.9-linux-glibc2.5-x86_64/include/mysql/plugin_auth_common.h
/usr/local/mysql-5.6.27-linux-glibc2.5-x86_64/include/mysql/plugin_auth_common.h

一开始我用的是第三个路径,这个路径是错的,后来用了第一个路径就ok了。

出现一大叠错误,看起来就是连接mysqlclient库失败了。失败的原因肯定是指定的路径有问题。

liangjf@ubuntu:~/study/mysql$ sudo find / -name libmysqlclient.so
/usr/local/mysql-5.7.9-linux-glibc2.5-x86_64/lib/libmysqlclient.so
/usr/local/mysql-5.6.27-linux-glibc2.5-x86_64/lib/libmysqlclient.so
/usr/lib64/mysql/libmysqlclient.so

最初我用的路径是/usr/lib64/mysql/,后来选用/usr/local/mysql-5.7.9-linux-glibc2.5-x86_64/lib/就编译ok了。

执行可执行文件失败。

liangjf@ubuntu:~/study/mysql$ ./test_connect 
./test_connect: error while loading shared libraries: libmysqlclient.so.20: cannot open shared object file: No such file or directory

编译时可以找到动态库,而执行时木有,是因为我的mysql的lib是单独安装,没有加进去环境变量中。两种解决办法:

  • /usr/local/mysql-5.7.9-linux-glibc2.5-x86_64/lib/加入环境变量中
  • /usr/local/mysql-5.7.9-linux-glibc2.5-x86_64/lib/libmysqlclient.so.20拷贝到/usr/lib中。因为这个路径是可执行文件去自动查找动态库的路径。