CENTOS上的网络安全工具(七)MYSQL也不能少

        为了能够在程序中倒腾不少安全工具生成的数据,弄一个简单一点的数据库也是必不可少的。相对于在Windows下面使用MSDB,Excel之类,Mysql可能是在Linux下最常用的吧。

一、CENTOS8上安装mysql

        学习在CENTOS8上安装mysql,我主要参考了这篇文章,相比其它在CENTOS7上来说,安装过程要简单很多,直接使用了@mysql模组:        

        1. 安装@mysql模组

        直接使用模组化安装的好处是不用考虑Centos内嵌mariadb的影响,不用各种先卸载后安装的操作,看起来就不太安全的样子。

[root@bogon share]# yum install -y @mysql
上次元数据过期检查:13:57:44 前,执行于 2022年05月23日 星期一 08时14分07秒。
依赖关系解决。
==========================================================================================================================
 软件包                             架构           版本                                           仓库               大小
==========================================================================================================================
安装组/模块包:
 mysql-server                       x86_64         8.0.26-1.module_el8.4.0+915+de215114           appstream          25 M
安装依赖关系:
 mariadb-connector-c-config         noarch         3.1.11-2.el8_3                                 appstream          15 k
 mecab                              x86_64         0.996-1.module_el8.4.0+589+11e12751.9          appstream         393 k
 mysql                              x86_64         8.0.26-1.module_el8.4.0+915+de215114           appstream          12 M
 mysql-common                       x86_64         8.0.26-1.module_el8.4.0+915+de215114           appstream         134 k
 mysql-errmsg                       x86_64         8.0.26-1.module_el8.4.0+915+de215114           appstream         598 k
 protobuf-lite                      x86_64         3.5.0-15.el8                                   appstream         149 k
安装模块配置档案:
 mysql/server                                                                                                            
启用模块流:
 mysql                                             8.0                                                                   

事务概要
==========================================================================================================================
安装  7 软件包

总下载:38 M
安装大小:195 M
下载软件包:
(1/7): mecab-0.996-1.module_el8.4.0+589+11e12751.9.x86_64.rpm                             2.5 MB/s | 393 kB     00:00    
(2/7): mysql-common-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm                       2.1 MB/s | 134 kB     00:00    
(3/7): mysql-errmsg-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm                       2.6 MB/s | 598 kB     00:00    
(4/7): mysql-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm                              8.0 MB/s |  12 MB     00:01    
(5/7): protobuf-lite-3.5.0-15.el8.x86_64.rpm                                              2.7 MB/s | 149 kB     00:00    
(6/7): mysql-server-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm                       7.6 MB/s |  25 MB     00:03    
(7/7): mariadb-connector-c-config-3.1.11-2.el8_3.noarch.rpm                               3.7 kB/s |  15 kB     00:03    
--------------------------------------------------------------------------------------------------------------------------
总计                                                                                      8.3 MB/s |  38 MB     00:04     
运行事务检查
事务检查成功。
运行事务测试
事务测试成功。
运行事务
  准备中  :                                                                                                           1/1 
  安装    : mariadb-connector-c-config-3.1.11-2.el8_3.noarch                                                          1/7 
  安装    : mysql-common-8.0.26-1.module_el8.4.0+915+de215114.x86_64                                                  2/7 
  安装    : mysql-8.0.26-1.module_el8.4.0+915+de215114.x86_64                                                         3/7 
  安装    : mysql-errmsg-8.0.26-1.module_el8.4.0+915+de215114.x86_64                                                  4/7 
  安装    : protobuf-lite-3.5.0-15.el8.x86_64                                                                         5/7 
  安装    : mecab-0.996-1.module_el8.4.0+589+11e12751.9.x86_64                                                        6/7 
  运行脚本: mecab-0.996-1.module_el8.4.0+589+11e12751.9.x86_64                                                        6/7 
  运行脚本: mysql-server-8.0.26-1.module_el8.4.0+915+de215114.x86_64                                                  7/7 
  安装    : mysql-server-8.0.26-1.module_el8.4.0+915+de215114.x86_64                                                  7/7 
  运行脚本: mysql-server-8.0.26-1.module_el8.4.0+915+de215114.x86_64                                                  7/7 
ValueError: /var/log/mysql(/.*)? 的文件上下文已定义

  验证    : mariadb-connector-c-config-3.1.11-2.el8_3.noarch                                                          1/7 
  验证    : mecab-0.996-1.module_el8.4.0+589+11e12751.9.x86_64                                                        2/7 
  验证    : mysql-8.0.26-1.module_el8.4.0+915+de215114.x86_64                                                         3/7 
  验证    : mysql-common-8.0.26-1.module_el8.4.0+915+de215114.x86_64                                                  4/7 
  验证    : mysql-errmsg-8.0.26-1.module_el8.4.0+915+de215114.x86_64                                                  5/7 
  验证    : mysql-server-8.0.26-1.module_el8.4.0+915+de215114.x86_64                                                  6/7 
  验证    : protobuf-lite-3.5.0-15.el8.x86_64                                                                         7/7 

已安装:
  mariadb-connector-c-config-3.1.11-2.el8_3.noarch            mecab-0.996-1.module_el8.4.0+589+11e12751.9.x86_64         
  mysql-8.0.26-1.module_el8.4.0+915+de215114.x86_64           mysql-common-8.0.26-1.module_el8.4.0+915+de215114.x86_64   
  mysql-errmsg-8.0.26-1.module_el8.4.0+915+de215114.x86_64    mysql-server-8.0.26-1.module_el8.4.0+915+de215114.x86_64   
  protobuf-lite-3.5.0-15.el8.x86_64                          

完毕!
[root@bogon share]# 

        2. 启动mysql服务

        安装完成后启动mysql服务,确保服务状态是active(running)就好。

[root@bogon share]# systemctl start mysqld.service 
[root@bogon share]# systemctl status mysqld.service 
● mysqld.service - MySQL 8.0 database server
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; disabled; vendor preset: disabled)
   Active: active (running) since Mon 2022-05-23 22:23:13 EDT; 14s ago
  Process: 40121 ExecStartPost=/usr/libexec/mysql-check-upgrade (code=exited, status=0/SUCCESS)
  Process: 39992 ExecStartPre=/usr/libexec/mysql-prepare-db-dir mysqld.service (code=exited, status=0/SUCCESS)
  Process: 39967 ExecStartPre=/usr/libexec/mysql-check-socket (code=exited, status=0/SUCCESS)
 Main PID: 40074 (mysqld)
   Status: "Server is operational"
    Tasks: 38 (limit: 11046)
   Memory: 485.9M
   CGroup: /system.slice/mysqld.service
           └─40074 /usr/libexec/mysqld --basedir=/usr

5月 23 22:23:09 bogon systemd[1]: Starting MySQL 8.0 database server...
5月 23 22:23:09 bogon mysql-prepare-db-dir[39992]: Initializing MySQL database
5月 23 22:23:13 bogon systemd[1]: Started MySQL 8.0 database server.

        3.设置mysql安全选项

        执行mysql_secure_installation

        (1)  VALIDATE PASSWORD COMPONENT can be used to test passwords and improve security. It checks the strength of password and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?

        这个我选择NO,毕竟我只是在自己的虚拟机局域网上安装用于编程而已,增强安全性可能带来不可预知的兼容问题,这个一对永恒矛盾。所以,在没有更多需求的情况下,咱就不探求这个选项了。

        (2)New passworld和Re-Enter new passworld。设置访问密码

        (3)By default, a MySQL installation has an anonymous user,allowing anyone to log into MySQL without having to have  a user account created for them. This is intended only for testing, and to make the installation go a bit smoother.You should remove them before moving into a production environment.

        Remove anonymous users? (Press y|Y for Yes, any other key for No) : 

        匿名访问,这个必须回答yes,毕竟最基本的安全还是需要的。

        (4)Normally, root should only be allowed to connect from 'localhost'. This ensures that someone cannot guess at the root password from the network. 

        Disallow root login remotely? (Press y|Y for Yes, any other key for No) : 

        因为我的测试环境全部使用root用户,甚至连code都弄到了root上,所以必须选No

        (5)By default, MySQL comes with a database named 'test' that anyone can access. This is also intended only for testing, and should be removed before moving  into  a  production  environment.
        Remove test database and access to it? (Press y|Y for Yes, any other key for No) : No

        我还打算拿这个测试数据库测试下代码,留着吧

        (6)Reloading the privilege tables will ensure that all changes made so far will take effect immediately.

        Reload privilege tables now? (Press y|Y for Yes, any other key for No) : 

        立即生效?那必须的。Yes。这样就可以使用Mysql了。

二、CENTOS8上mysql的离线安装

        1. 准备离线安装包        

        由于@mysql模组yumdownloader没有办法解析,所以我们智能在install的过程中使用downloadonly将其下载下来。

[root@bogon share]# yum install --downloadonly --destdir=/home/pig/share @mysql -y
上次元数据过期检查:13:55:04 前,执行于 2022年05月23日 星期一 08时14分07秒。
依赖关系解决。
==========================================================================================================================
 软件包                             架构           版本                                           仓库               大小
==========================================================================================================================
安装组/模块包:
 mysql-server                       x86_64         8.0.26-1.module_el8.4.0+915+de215114           appstream          25 M
安装依赖关系:
 mariadb-connector-c-config         noarch         3.1.11-2.el8_3                                 appstream          15 k
 mecab                              x86_64         0.996-1.module_el8.4.0+589+11e12751.9          appstream         393 k
 mysql                              x86_64         8.0.26-1.module_el8.4.0+915+de215114           appstream          12 M
 mysql-common                       x86_64         8.0.26-1.module_el8.4.0+915+de215114           appstream         134 k
 mysql-errmsg                       x86_64         8.0.26-1.module_el8.4.0+915+de215114           appstream         598 k
 protobuf-lite                      x86_64         3.5.0-15.el8                                   appstream         149 k
安装模块配置档案:
 mysql/server                                                                                                            
启用模块流:
 mysql                                             8.0                                                                   

事务概要
==========================================================================================================================
安装  7 软件包

总下载:38 M
安装大小:195 M
YUM将仅会从事务下载软件包。
下载软件包:
(1/7): mariadb-connector-c-config-3.1.11-2.el8_3.noarch.rpm                               245 kB/s |  15 kB     00:00    
(2/7): mysql-common-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm                       1.6 MB/s | 134 kB     00:00    
(3/7): mecab-0.996-1.module_el8.4.0+589+11e12751.9.x86_64.rpm                             2.3 MB/s | 393 kB     00:00    
(4/7): mysql-errmsg-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm                       2.2 MB/s | 598 kB     00:00    
(5/7): protobuf-lite-3.5.0-15.el8.x86_64.rpm                                              1.8 MB/s | 149 kB     00:00    
(6/7): mysql-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm                              5.3 MB/s |  12 MB     00:02    
(7/7): mysql-server-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm                       6.9 MB/s |  25 MB     00:03    
--------------------------------------------------------------------------------------------------------------------------
总计                                                                                      8.7 MB/s |  38 MB     00:04     
完毕!
下载的软件包保存在缓存中,直到下次成功执行事务。
您可以通过执行 'yum clean packages' 删除软件包缓存。

        这样,在我们指定的文件夹下,就多了7个文件(可能和系统已安装组件相关而不一样)

         记得这一步需要在安装之前做,如果在安装之后,yum会告诉你都装好了,啥也不用干。另外,也要记得下载后赶紧搬走,不然安装完成后,yum会认为事务已完成,会将刚缓存好的rpm全部删除。

        2. 离线安装

        由于yumdownloader并不支持@mysql模组,所以有关的依赖关系使用yum也无法建立,即使我们使用createrepo,也无法在离线环境中直接使用yum install @mysql安装,只能使用rpm命令依序安装:

mariadb-connector-c-config-3.1.11-2.el8_3.noarch.rpm          mysql-errmsg-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm
mecab-0.996-1.module_el8.4.0+589+11e12751.9.x86_64.rpm        mysql-server-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm
mysql-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm         protobuf-lite-3.5.0-15.el8.x86_64.rpm
mysql-common-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm

        (1)mariadb-connector-c-config-3.1.11-2.el8_3.noarch.rpm 

[root@bogon share]# rpm -ivh mariadb-connector-c-config-3.1.11-2.el8_3.noarch.rpm 
Verifying...                          ################################# [100%]
准备中...                          ################################# [100%]
正在升级/安装...
   1:mariadb-connector-c-config-3.1.11################################# [100%]

        (2)mecab-0.996-1.module_el8.4.0+589+11e12751.9.x86_64.rpm 

[root@bogon share]# rpm -ivh mecab-0.996-1.module_el8.4.0+589+11e12751.9.x86_64.rpm 
Verifying...                          ################################# [100%]
准备中...                          ################################# [100%]
正在升级/安装...
   1:mecab-0.996-1.module_el8.4.0+589+################################# [100%]

        (3)protobuf-lite-3.5.0-15.el8.x86_64.rpm

[root@bogon share]# rpm -ivh protobuf-lite-3.5.0-15.el8.x86_64.rpm
Verifying...                          ################################# [100%]
准备中...                          ################################# [100%]
正在升级/安装...
   1:protobuf-lite-3.5.0-15.el8       ################################# [100%]

        (4)mysql-common-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm

[root@bogon share]# rpm -ivh mysql-common-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm
Verifying...                          ################################# [100%]
准备中...                          ################################# [100%]
正在升级/安装...
   1:mysql-common-8.0.26-1.module_el8.################################# [100%]

        (5)mysql-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm 

[root@bogon share]# rpm -ivh mysql-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm 
Verifying...                          ################################# [100%]
准备中...                          ################################# [100%]
正在升级/安装...
   1:mysql-8.0.26-1.module_el8.4.0+915################################# [100%]

        (6)mysql-errmsg-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm

[root@bogon share]# rpm -ivh mysql-errmsg-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm
Verifying...                          ################################# [100%]
准备中...                          ################################# [100%]
正在升级/安装...
   1:mysql-errmsg-8.0.26-1.module_el8.################################# [100%]

        (7)mysql-server-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm

[root@bogon share]# rpm -ivh mysql-server-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm
Verifying...                          ################################# [100%]
准备中...                          ################################# [100%]
正在升级/安装...
   1:mysql-server-8.0.26-1.module_el8.################################# [100%]
ValueError: /var/log/mysql(/.*)? 的文件上下文已定义

        会出现一个警告,不管它也没事,因为这个上下文确实已经存在了

三、VSCODE和mysql的连接

        1.安装插件        

        VSCODE和mysql连接,需要下载一个数据库管理的插件。目前比较好用的是这个:

         再次啰嗦一句,VSCODE允许同名插件,所以要认准作者。其它的插件我也尝试了几个,个人感觉确实没有这个直观好用。  另外,本地插件和远程插件是不一样的,如下图,我的VSCODE本地并未安装MySQL插件——因为本地确实没有装Windows版本的mysql。            

        2. 配置数据库连接

        装好插件后,在CODE左边的工具栏上会出现数据库配置的图标,由于我们目前只使用了mysql,所以只涉及到传统的database图标。选择,并使用右上角的+号添加数据库连接:       

         配置窗口里只有标注*号的项目才是必须填写的(也就是说必须填对的),其它项目可以视情填写。例如名称那一栏,我可以起一个自己喜欢好记的名字,但是服务器的IP就必须得填对了。

         点击连接——嗯,出错了:Host '' is not allowed to connect to this MySQL server。

        3.放开服务器权限

        提示很明确,事实是服务器上的mysql没有放开远程登陆权限,也就是只允许localhost登陆。这个权限配置在mysql数据库的user表中,对应用户root的host项目,通过查询可知,该项目允许root登陆的只有localhost,将这一项update为%即可:

[root@bogon extensions]# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 8.0.26 Source distribution

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select host from user where user="root";
+-----------+
| host      |
+-----------+
| localhost |
+-----------+
1 row in set (0.00 sec)

mysql> update user set host='%' where user='root';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> flush privileges;
Query OK, 0 rows affected (0.02 sec)

mysql> exit;
Bye

        4. 可惜不是免费的

        对比 一下这张截图和之前的,明显的区别在于本地模式下,该插件是提供交互式客户端的,这无疑要方便很多;而远程模式,不是free账户所支持的。

        所以如果习惯的话,还是考虑直接mysql -u -p命令行吧,其实也能用,不要钱的都是香的。 

         四、使用c++访问mysql

        使用c++访问mysql,首先肯定是包含mysql.h文件了。按照之前的配置,我们的VSCODE当前是这样的:

         显然,智能解析配置找不到mysql.h头文件。一般来说,原因有2,一是智能解析路径配置问题,二是没有装mysql开发包。在服务器的/usr/include下找找,果然是没有的:

[root@bogon include]# ls /usr/include -l|grep "mysql"
[root@bogon include]# 
[root@bogon include]# 

        所以我们先来解决第二个问题。

      1.Mysql开发包安装

        同样,先下载离线包准备后期离线安装:

[root@bogon share]# yumdownloader --resolve mysql-devel
上次元数据过期检查:4:10:33 前,执行于 2022年05月23日 星期一 23时22分16秒。
(1/14): pcre2-utf16-10.32-2.el8.x86_64.rpm                                                 48 kB/s | 229 kB     00:04    
(2/14): libsepol-devel-2.9-3.el8.x86_64.rpm                                               613 kB/s |  87 kB     00:00    
(3/14): keyutils-libs-devel-1.5.10-9.el8.x86_64.rpm                                        73 kB/s |  48 kB     00:00    
(4/14): libverto-devel-0.3.0-5.el8.x86_64.rpm                                             291 kB/s |  18 kB     00:00    
(5/14): zlib-devel-1.2.11-17.el8.x86_64.rpm                                               555 kB/s |  58 kB     00:00    
(6/14): mysql-devel-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm                       274 kB/s | 155 kB     00:00    
(7/14): mysql-libs-8.0.26-1.module_el8.4.0+915+de215114.x86_64.rpm                        6.5 MB/s | 1.4 MB     00:00    
(8/14): krb5-devel-1.18.2-14.el8.x86_64.rpm                                               1.2 MB/s | 560 kB     00:00    
(9/14): libselinux-devel-2.9-5.el8.x86_64.rpm                                             240 kB/s | 200 kB     00:00    
(10/14): libcom_err-devel-1.45.6-4.el8.x86_64.rpm                                         584 kB/s |  39 kB     00:00    
(11/14): libkadm5-1.18.2-14.el8.x86_64.rpm                                                248 kB/s | 187 kB     00:00    
(12/14): pcre2-utf32-10.32-2.el8.x86_64.rpm                                                25 kB/s | 220 kB     00:08    
(13/14): pcre2-devel-10.32-2.el8.x86_64.rpm                                               1.8 MB/s | 605 kB     00:00    
(14/14): openssl-devel-1.1.1k-6.el8.x86_64.rpm                                            174 kB/s | 2.3 MB     00:13    
[root@bogon share]# 

        执行完毕后,可以看到usr下已经有了mysql相关的头文件

[root@bogon share]# ls -l /usr/include|grep "mysql"
drwxr-xr-x.  3 root root    282 5月  24 03:36 mysql
[root@bogon share]# 

        2. includepath设置

        装好开发包,回到VSCODE,错误标识仍然没有删除。因为相关路径我们并没有包含到智能解析的设置里面。

        打开c/c++插件的扩展设置(具体方法参考上一篇文章的第四部分),将/usr/include路径设置为包含路径。        

        嗯,再回头看看,错误应该解决了。

         3.构造测试数据库

        编写测试代码之前,先得弄个测试数据库。这个在本地上使用插件时非常简单;但是远程嘛,因为要收费嘛,只好用命令行了:

[root@bogon share]# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 32
Server version: 8.0.26 Source distribution

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> CREATE DATABASE testdb;
Query OK, 1 row affected (0.04 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| testdb             |
+--------------------+
5 rows in set (0.00 sec)

mysql> create table user(
    -> uid int(32) primary key auto_increment,
    -> uname varchar(32),
    -> age int(32),
    -> ddress varchar(256)
    -> );
Query OK, 0 rows affected, 2 warnings (0.07 sec)

mysql> desc user;
+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| uid    | int          | NO   | PRI | NULL    | auto_increment |
| uname  | varchar(32)  | YES  |     | NULL    |                |
| age    | int          | YES  |     | NULL    |                |
| ddress | varchar(256) | YES  |     | NULL    |                |
+--------+--------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

mysql> insert into user (uid,uname,age,ddress) values (1,"bear",20,"fortress");
Query OK, 1 row affected (0.02 sec)

mysql> insert into user (uid,uname,age,ddress) values (2,"fish",50,"river");
Query OK, 1 row affected (0.00 sec)

mysql> select * from user;
+-----+-------+------+----------+
| uid | uname | age  | ddress   |
+-----+-------+------+----------+
|   1 | bear  |   20 | fortress |
|   2 | fish  |   50 | river    |
+-----+-------+------+----------+
2 rows in set (0.00 sec)

mysql> quit;
Bye



        好了,现在我们有了一个名为testdb的库,其中有一个名为user的表。表中包含两行数据。

        4.编写测试代码       

         因为测试嘛,所以代码也可以简单点,就查两行数,主要的sql部件都有了:

#include <iostream>
#include "mysql/mysql.h"

using namespace std;

int main()
{
	MYSQL mysql;
	mysql_init(&mysql);
	
	if(!mysql_real_connect(&mysql,"192.168.232.131","root","","testdb",3306,0,0)){
		cout<<"连接失败"<<mysql_errno(&mysql)<<endl;
		return -1;
	}
	MYSQL_RES *res = nullptr;
	MYSQL_ROW row;

	if(mysql_real_query(&mysql,"select * from user",sizeof("select * from user"))){
		cout<<"查询失败"<<mysql_errno(&mysql)<<endl;
		return -1;
	}

	res = mysql_store_result(&mysql);
	if(res==nullptr){
		cout<<"获取结果失败"<<mysql_errno(&mysql)<<endl;
		return -1;
	}

	while (row = mysql_fetch_row(res)){
		for(unsigned int i=0;i<<res->field_count;i++){
			cout<<row[i]<<"\t";
		}
		cout<<endl;
	}

	mysql_free_result(res);
	mysql_close(&mysql);

	return 0;
}

        5.配置编译参数       

        然而结果是不幸的,因为虽然智能补全知道include在哪,编译器并不知道,还需要我们去设置编译参数。        

         Mysql的编译参数设置,虽然一般只需要指定头文件和lib文件的包含路径,但自己去找还是比较麻烦的,我们可以借助mysql_config工具提示一下:

[root@bogon pigpro]# mysql_config --libs
-L/usr/lib64/mysql -lmysqlclient -lpthread -ldl -lz -lssl -lcrypto -lresolv -lm -lrt
[root@bogon pigpro]# mysql_config --cflags
-I/usr/include/mysql -m64 

        可知头文件参数为“-I/usr/include/mysql”;库文件参数为“-L/usr/lib64/mysql”,其余的参数也不是都需要的,-lmysqlclient -lpthread 估计是得带上。 首先在本地机器上编译能够通过:

[root@bogon pigpro]# g++ test.cpp -o test.exe -I/usr/include/mysql -L/usr/lib64/mysql -lmysqlclient -lpthread 
[root@bogon pigpro]# ls
test.cpp  test.exe

       然后根据这个我们来编辑task.json文件。

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ 生成活动文件",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
                "-I/usr/include/mysql",
                "-L/usr/lib64/mysql",
                "-lmysqlclient",
                "-lpthread"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "调试器生成的任务。"
        }
    ],
    "version": "2.0.0"
}

        记住一定不要照搬我的参数,而要通过mysql_config根据自己的系统情况生成正确的参数。

#include <iostream>
#include "mysql/mysql.h"

using namespace std;

int main()
{
	MYSQL mysql;
	mysql_init(&mysql);
	
	if(!mysql_real_connect(&mysql,"192.168.232.131","root","*******","testdb",3306,0,0)){
		cout<<"连接失败"<<mysql_errno(&mysql)<<endl;
		return -1;
	}
	MYSQL_RES *res = nullptr;

	if(mysql_real_query(&mysql,"select * from user",sizeof("select * from user"))){
		cout<<"查询失败"<<mysql_errno(&mysql)<<endl;
		return -1;
	}

	res = mysql_store_result(&mysql);
	if(res==nullptr){
		cout<<"获取结果失败"<<mysql_errno(&mysql)<<endl;
		return -1;
	}

	for(unsigned int i=0;i<res->row_count;i++){
		MYSQL_ROW row = mysql_fetch_row(res);
		for(unsigned int i=0;i<res->field_count;i++){
			cout<<row[i]<<"\t";
		}
		cout<<endl;
	}

	mysql_free_result(res);
	mysql_close(&mysql);

	return 0;
}

         然后运行,成功!

五、Python访问Mysql数据库

        1.Python环境的准备

        Python环境的配置相对C++来说要简单不少,至少对现阶段我的python水平而言——不涉及过于高深的技术,估计也就碰不到麻烦的问题。

        (1)首先是确保目标机上的python可用。

        CENTOS8自带python3,所以执行程序及安装第三方包都得带个“3”:

         (2)VSCODE这边需要下载python extension pack组件

        直接装这个打包版的就好,一气儿都装全了,本地和远程的安装方法和上文也一样。

         (3)PyMySql包的安装

        如果目标机连在网上就比较简单,直接pip3 install pymysql就行了。如果目标机离线,则需要在能够上网的机器上先用pip3下载一下:

[root@bogon share]# pip3 download pymysql
Collecting pymysql
  Using cached https://files.pythonhosted.org/packages/4f/52/a115fe175028b058df353c5a3d5290b71514a83f67078a6482cff24d6137/PyMySQL-1.0.2-py3-none-any.whl
  Saved ./PyMySQL-1.0.2-py3-none-any.whl
Successfully downloaded pymysql
[root@bogon share]# ls
PyMySQL-1.0.2-py3-none-any.whl  test.py
[root@bogon share]# 

        然后在目标机上直接pip3 install下载的文件就好:

[root@bogon share]# pip3 install PyMySQL-1.0.2-py3-none-any.whl 

        (4)python访问mysql数据库

        要说写起来的简便程度上,还是python:

import pymysql

hostname = "192.168.232.131"
username = "root"
passwordstr = "********"
dbnamestr = "testdb"
tablename = "user"

conn = pymysql.connect(host=hostname,user=username,password=passwordstr,database=dbnamestr)
cursor = conn.cursor()
sql=f"SELECT * FROM user"
cursor.execute(sql)

results = cursor.fetchall()
for row in results:
    for item in row:
        print("{0!s}r".format(item),end=" ")
    print("")
conn.close()

        运行结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值