Bootstrap

使用MariaDB数据库管理系统

前言:本博客仅作记录学习使用,部分图片出自网络,如有侵犯您的权益,请联系删除

一、数据库管理系统

数据库是指按照某些特定结构来存储数据资料的数据仓库;

数据库管理系统是一种能够对数据库中存放的数据进行建立、修改、删除、查找、维护等操作的软件程序;

MariaDB当前由开源社区进行维护,是MySQL的分支产品,几乎完全兼容MySQL。MariaDB与MySQL具有高度的兼容性,具有库二进制奇偶校验的直接替换功能,与Mysql API和命令均保持一致。并且MariaDB还自带了一个新的存储引擎Aria,用来替代MyISAM,与MySQL一样好用。

二、初始化mariaDB服务

安装部署MariaDB数据库主程序及服务端程序;

 [root@Linux ~]# yum install mariadb mariadb-server

安装完成后,启动服务并加入开机自启项中;

 [root@Linux ~]# systemctl start mariadb
 [root@Linux ~]# systemctl enable mariadb

在确认MariaDB数据库软件程序安装完毕后并成功启动后不要立即使用。为了确保数据库的安全性和正常运转,先对数据库进行初始化操作;

  • 设置root管理员在数据库中的密码值; (注意,该密码并非root管理员在系统中的密码,这里的密码值默认应该为空,可直接按回车键)
  • 设置root管理员在数据库中的专有密码;
  • 删除匿名账户,并使用root管理员从远程登录数据库,以确保数据库上运行的业务的安全性
  • 删除默认的测试数据库,取消测试数据库的一系列访问权限;
  • 刷新授权列表,让初始化的设定立即生效。

下面进行操作;

 [root@Linux ~]# mysql_secure_installation 
 ​
 NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
       SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!
 ​
 In order to log into MariaDB to secure it, we'll need the current
 password for the root user.  If you've just installed MariaDB, and
 you haven't set the root password yet, the password will be blank,
 so you should just press enter here.
 ​
 Enter current password for root (enter for none): # 输入管理员原始密码,默认为空
 OK, successfully used password, moving on...
 ​
 Setting the root password ensures that nobody can log into the MariaDB
 root user without the proper authorisation.
 ​
 Set root password? [Y/n] Y  # 设置管理员密码           
 New password: # 输入新的密码
 Re-enter new password: # 再次输入密码
 Password updated successfully!
 Reloading privilege tables..
  ... Success!
 ​
 ​
 By default, a MariaDB installation has an anonymous user, allowing anyone
 to log into MariaDB 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? [Y/n] y  # 删除匿名账户
  ... Success!
 ​
 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? [Y/n] y # 禁止管理员从远程登录
  ... Success!
 ​
 By default, MariaDB 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? [Y/n] y  # 删除测试数据库及其访问权限
  - Dropping test database...
  ... Success!
  - Removing privileges on test database...
  ... Success!
 ​
 Reloading the privilege tables will ensure that all changes made so far
 will take effect immediately.
 ​
 Reload privilege tables now? [Y/n] y # 刷新授权表,让初始化后的设定立即生效
  ... Success!
 ​
 Cleaning up...
 ​
 All done!  If you've completed all of the above steps, your MariaDB
 installation should now be secure.
 ​
 Thanks for using MariaDB!

在很多生产环境中都要使用站库分离的技术(即网站和数据库不在同一个服务器上),若要让root管理员远程访问数据库,在上面的初始化操作中设置允许策略;还需要设置防火墙放行对数据库服务程序的访问请求,数据库服务程序默认会占用3306端口,在防火墙策略中服务名称统一叫作mysql;

 [root@Linux ~]# firewall-cmd --permanent --add-service=mysql              
 [root@Linux ~]# firewall-cmd --reload 

准备就绪;首次登录MariaDB数据库;管理数据库的命令为mysql,其中"-u"参数用来指定以root管理员身份登录、"-p"参数用来验证该用户在数据库中的密码值;

 [root@Linux ~]# mysql -u root -p
 Enter password: 
 Welcome to the MariaDB monitor.  Commands end with ; or \g.
 Your MariaDB connection id is 17
 Server version: 10.3.39-MariaDB MariaDB Server
 ​
 Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
 ​
 Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
 ​
 MariaDB [(none)]> 

初次使用数据库管理工具,可以输入help命令查看MariaDB能做的操作,语句的用法和MySQL一模一样;

 MariaDB [(none)]> help
 ​
 General information about MariaDB can be found at
 http://mariadb.org
 ​
 List of all MySQL commands:
 Note that all text commands must be first on line and end with ';'
 ?         (\?) Synonym for `help'.
 clear     (\c) Clear the current input statement.
 connect   (\r) Reconnect to the server. Optional arguments are db and host.
 delimiter (\d) Set statement delimiter.
 edit      (\e) Edit command with $EDITOR.
 ego       (\G) Send command to mysql server, display result vertically.
 exit      (\q) Exit mysql. Same as quit.
 go        (\g) Send command to mysql server.
 help      (\h) Display this help.
 nopager   (\n) Disable pager, print to stdout.
 notee     (\t) Don't write into outfile.
 pager     (\P) Set PAGER [to_pager]. Print the query results via PAGER.
 print     (\p) Print current command.
 prompt    (\R) Change your mysql prompt.
 quit      (\q) Quit mysql.
 rehash    (\#) Rebuild completion hash.
 source    (\.) Execute an SQL script file. Takes a file name as an argument.
 status    (\s) Get status information from the server.
 system    (\!) Execute a system shell command.
 tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
 use       (\u) Use another database. Takes database name as argument.
 charset   (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
 warnings  (\W) Show warnings after every statement.
 nowarning (\w) Don't show warnings after every statement.
 ​
 For server side help, type 'help contents'

执行数据库命令时,都需要在命令后面用分号(;)结尾;下面执行如下命令查看数据库管理系统中当前都有哪些数据库;

 MariaDB [(none)]> show databases;
 +--------------------+
 | Database           |
 +--------------------+
 | information_schema |
 | mysql              |
 | performance_schema |
 +--------------------+
 3 rows in set (0.001 sec)

接下来使用数据库命令将root管理员在数据库管理系统中的密码值修改为linux。这样退出后再尝试登录,如果还坚持输入原先的密码,则将提示访问失败。

 MariaDB [(none)]> set password = password('linux');
 Query OK, 0 rows affected (0.000 sec)
 ​
 MariaDB [(none)]> exit
 Bye
 [root@Linux ~]# mysql -u root -p
 Enter password:  # 输入旧密码报错
 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
 [root@Linux ~]# mysql -u root -p
 Enter password: # 输入新密码成功登录
 Welcome to the MariaDB monitor.  Commands end with ; or \g.
 Your MariaDB connection id is 20
 Server version: 10.3.39-MariaDB MariaDB Server
 ​
 Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
 ​
 Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

三、管理用户以及授权

创建多个专用的数据库管理账户,然后在分配合理的权限,以满足他们的工作需求;"CREATE USER 用户名@主机名 IDENTIFIED BY '密码';"格式创建数据库管理账户。

MariaDB [(none)]> create user luke@localhost identified by 'linux';
Query OK, 0 rows affected (0.001 sec)

创建的账户信息可以使用select命令语句来查询。下面命令査询的是账户luke的主机名称、账户名称以及经过加密的密码值信息;

MariaDB [(none)]> 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
MariaDB [mysql]> select host,user,password from user where user="luke";
+-----------+------+-------------------------------------------+
| host      | user | password                                  |
+-----------+------+-------------------------------------------+
| localhost | luke | *6F3CAE7C3BBB2A5B5D933738682953BC21AEBEE7 |
+-----------+------+-------------------------------------------+
1 row in set (0.000 sec)

不过,luke只是一个普通用户,没有任何权限;

MariaDB [mysql]> exit
Bye
[root@Linux ~]# mysql -u luke -p
Enter password: 

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.000 sec)

数据库管理系统所使用的命令一般都比较复杂;以grant命令为例;grant命令用于为账户进行授权,其常见格式如如下;在使用qrant命令时需要写上要赋予的权限、数据库及表单名称,以及对应的账户及主机信息;其实,只要理解了命令中每个字段的功能含义,也就不觉得命令复杂难懂了;

命令作用
GRANT 权限 ON 数据库.表单名称 TO 用户名@主机名对某个特定数据库中的特定表单给予授权
GRANT 权限 ON 数据库.* TO 用户名@主机名对某个特定数据库中的所有表单给予授权
GRANT 权限 ON *.* TO 用户名@主机名所有数据库及所有表单给予授权
GRANT 权限1,权限2 ON 数据库.* TO 用户名@主机名某个数据库中的所有表单给予多个授权
GRANT ALL PRIVILEGES ON *.* TO 用户名@主机名所有数据库及所有表单给予全部授权(需谨慎操作)

用户的授权工作需要管理员来执行;针对mysql数据库中的user表单向账户luke授于查询、更新、删除以及插入等权限;

[root@Linux ~]# mysql -u root -p
Enter password: 

MariaDB [(none)]> GRANT SELECT,UPDATE,DELETE,INSERT ON mysql.user TO luke@localhost;
Query OK, 0 rows affected (0.000 sec)

操作完成,再次查看一下账户luke的权限;

MariaDB [(none)]> SHOW GRANTS FOR luke@localhost;
+----------------------------------------------------------------------------------+
| Grants for luke@localhost                                                        |
+----------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `luke`@`localhost` IDENTIFIED BY PASSWORD '*6F3CAE7C3BBB2A5B5D933738682953BC21AEBEE7' |
| GRANT SELECT, INSERT, UPDATE, DELETE ON `mysql`.`user` TO `luke`@`localhost`     |
+----------------------------------------------------------------------------------+
2 rows in set (0.000 sec)

显示账户luke已经拥有了权限;在切换到账户luke,此时就能看到mysql数据库了,而且还能看到表单user;

[root@Linux ~]# mysql -u luke -p
Enter password: 

MariaDB [(none)]> SHOW databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
+--------------------+
2 rows in set (0.000 sec)

MariaDB [(none)]> use mysql;
Database changed

MariaDB [mysql]> SHOW tables;
+-----------------+
| Tables_in_mysql |
+-----------------+
| user            |
+-----------------+
1 row in set (0.000 sec)

MariaDB [mysql]> exit
Bye

OK,接下来学习数据库内容的修改方法。切换回root,移除刚才的权限;

[root@Linux ~]# mysql -u root -p
Enter password: 

MariaDB [(none)]> REVOKE SELECT,UPDATE,DELETE,INSERT ON mysql.user FROM luke@localhost;
Query OK, 0 rows affected (0.000 sec)

可以看到,除了移除授权命令(revoke)与授权命令(grant)不同外,其余部分都是一致的;再次查看luke账户的权限;

MariaDB [(none)]> SHOW GRANTS FOR luke@localhost;
+----------------------------------------------------------------------------------+
| Grants for luke@localhost                                                        |
+----------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `luke`@`localhost` IDENTIFIED BY PASSWORD '*6F3CAE7C3BBB2A5B5D933738682953BC21AEBEE7'                                        |
+----------------------------------------------------------------------------------+
1 row in set (0.000 sec)

不再需要某个用户时,直接使用DROP命令进行删除;

MariaDB [(none)]> DROP user luke@localhost;
Query OK, 0 rows affected (0.000 sec)

四、创建数据库与表单

在MariaDB数据库管理系统中,一个数据库可以存放多个数据表,数据表单是数据库中最重要最核心的内容;用于创建数据库的命令及作用如下;

命令用法作用
CREATE database 数据库名称;创建新的数据库
DESCRIBE 表单名称;描述表单
UPDATE 表单名称 SET attribute=新值 WHERE attribute > 原始值;更新表单中的数据
USE 数据库名称;指定使用的数据库
SHOW databases;显示当前已有的数据库
SHOW tables;显示当前数据库中的表单
SELECT * FROM 表单名称;从表单中选中某个记录值
DELETE FROM 表单名 WHERE attribute=值;从表单中删除某个记录值

建立数据库是管理数据的起点;现在尝试建立一个名为Linuxprobe的数据库,然后再查看数据库列表;

MariaDB [(none)]> CREATE DATABASE linuxprobe;
Query OK, 1 row affected (0.000 sec)

MariaDB [(none)]> SHOW databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| linuxprobe         |
| mysql              |
| performance_schema |
+--------------------+
4 rows in set (0.001 sec)

MariaDB与MySQL同属关系型数据库(Relational Database Management System),“关系型”数据库有些类似于表格的概念,一个关系型数据库由一个或多个表格/表单组成

表头代表每一列的名称代表具有相同数据类型的数据集合代表用来描述事物的具体信息代表行的具体信息,每个值均与该列的其他数据类型相同;代表用来识别某个特定事物的方法,在当前列中具有唯一性。

比如在刚刚的库中创建表单mybook,然后进行表单的初始化,即定义存储数据内容的结构;下面定义3个字段项;长度为15个字符型字段name用来存放图书名称;整型字段price和pages分别存储图书的价格和页数;

MariaDB [(none)]> use linuxprobe;
Database changed
MariaDB [linuxprobe]> CREATE TABLE mybook (name char(15),price int,page int);
Query OK, 0 rows affected (0.007 sec)

MariaDB [linuxprobe]> DESCRIBE mybook;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| name  | char(15) | YES  |     | NULL    |       |
| price | int(11)  | YES  |     | NULL    |       |
| page  | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.001 sec)

五、管理表单及数据

使用INSERT命令向mybook数据表单中插一条图书信息;在命令中写清表单名称以及对应的字段项;

我们在使用select命令查询表单内容时,需要加上想要查询的字;如果想查看表单中的所有内容,则可以使用星号(*)通配符来显示;

MariaDB [linuxprobe]> INSERT INTO mybook(name,price,page) VALUES('linuxprobe','60','518');
Query OK, 1 row affected (0.001 sec)

MariaDB [linuxprobe]> SELECT * from mybook;
+------------+-------+------+
| name       | price | page |
+------------+-------+------+
| linuxprobe |    60 |  518 |
+------------+-------+------+
1 row in set (0.000 sec)

修改方法:使用update命令进行修改

MariaDB [linuxprobe]> UPDATE mybook SET price=55;
Query OK, 1 row affected (0.001 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [linuxprobe]> SELECT name,price FROM mybook;
+------------+-------+
| name       | price |
+------------+-------+
| linuxprobe |    55 |
+------------+-------+
1 row in set (0.000 sec)

可用where命令进行指定某一条进行修改,例如再插入两条书籍信息:

MariaDB [linuxprobe]> INSERT INTO mybook(name,price,page) VALUES('linuxcool','85','300');
Query OK, 1 row affected (0.001 sec)

MariaDB [linuxprobe]> INSERT INTO mybook(name,price,page) VALUES('linuxdown','105','500');
Query OK, 1 row affected (0.001 sec)

然后仅修改名称为linuxcool的书籍价格为60元,不影响其他书籍;

MariaDB [linuxprobe]> UPDATE mybook SET price=60 where name='linuxcool';
Query OK, 1 row affected (0.001 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [linuxprobe]> select * from mybook;
+------------+-------+------+
| name       | price | page |
+------------+-------+------+
| linuxprobe |    55 |  518 |
| linuxcool  |    60 |  300 |
| linuxdown  |   105 |  500 |
+------------+-------+------+
3 rows in set (0.000 sec)

可使用delete命令删除某个数据表单中的内容;

MariaDB [linuxprobe]> DELETE FROM mybook;
Query OK, 3 rows affected (0.001 sec)

MariaDB [linuxprobe]> SELECT * FROM mybook;
Empty set (0.000 sec)

在数据越来越多的情况下,若我们只想查看其价格大于某个数值的图书时,又该如何定义查询语句呢?先使用insert插入命令依次插入4条信息:

MariaDB [linuxprobe]> INSERT INTO mybook(name,price,page) VALUES('linxuprobe1','30','518');
Query OK, 1 row affected (0.001 sec)

MariaDB [linuxprobe]> INSERT INTO mybook(name,price,page) VALUES('linxuprobe2','50','518');
Query OK, 1 row affected (0.001 sec)

MariaDB [linuxprobe]> INSERT INTO mybook(name,price,page) VALUES('linxuprobe3','80','518');
Query OK, 1 row affected (0.001 sec)

MariaDB [linuxprobe]> INSERT INTO mybook(name,price,page) VALUES('linxuprobe4','100','518');
Query OK, 1 row affected (0.001 sec)

结合使用select与where命令让查询结果更加精准;其中,where命令是在数据库中进行匹配查询的条件命令。通过设置查询条件,就可以仅查找出符合该条件的数据。下面列出where命令中常用的查询参数以及作用;

参数作用
=相等
<>或!=不相等
>大于
<小于
>=大于或等于
<=小于或等于
BETWEEN在某个范围内
LIKE搜索一个例子
IN在列中搜索多个值

示例:分别在mybook表单中查找出价格大于75元或价格不等于80元的图书;

MariaDB [linuxprobe]> SELECT * FROM mybook WHERE price>75;
+-------------+-------+------+
| name        | price | page |
+-------------+-------+------+
| linxuprobe3 |    80 |  518 |
| linxuprobe4 |   100 |  518 |
+-------------+-------+------+
2 rows in set (0.001 sec)

MariaDB [linuxprobe]> SELECT * FROM mybook WHERE price!=80;
+-------------+-------+------+
| name        | price | page |
+-------------+-------+------+
| linxuprobe1 |    30 |  518 |
| linxuprobe2 |    50 |  518 |
| linxuprobe4 |   100 |  518 |
+-------------+-------+------+
3 rows in set (0.000 sec)

匹配的条件越多,获得信息就越精准。在WHERE命令的后面追加AND操作符,可以进行多次匹配。例如找到这本价格为30元,页数为518的书籍名称;

MariaDB [linuxprobe]> SELECT * from mybook WHERE price=30 AND page=518;
+-------------+-------+------+
| name        | price | page |
+-------------+-------+------+
| linxuprobe1 |    30 |  518 |
+-------------+-------+------+
1 row in set (0.000 sec)

六、数据库的备份及恢复

mysqldump命令用于备份数据库数据,格式为"mysaldump [参数] 数据库名称]”。其中参数与mysql命令大致相同,-u参数用于定义登录数据库的账户名称,-p参数代表密码提示符。下面将linuxprobe数据库中的内容导出成一个文件,并保存到root管理员的家目录中;

[root@Linux ~]# mysqldump -u root -p linuxprobe > /root/linuxprobeDB.dump
Enter password: # 输入管理员的数据库密码

然后进入MariaDB数据库管理系统,彻底删除linuxprobe数据库,这样mybook数据表单也将被彻底删除。然后重新建立linuxprobe数据库;

[root@Linux ~]# mysql -u root -p
Enter password: 

MariaDB [(none)]> SHOW databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.000 sec)

MariaDB [(none)]> CREATE DATABASE linuxprobe;
Query OK, 1 row affected (0.000 sec)

接下来进行数据恢复;使用输入重定向符把刚刚备份的数据库文件导入到mysql命令中,然后执行该命令。接下来登录到MariaDB数据库,就又能看到linuxprobe数据库以及mybook数据表单了。数据库恢复成功!

[root@Linux ~]# mysql -u root -p linuxprobe < /root/linuxprobeDB.dump
Enter password: 
[root@Linux ~]# mysql -u root -p
Enter password: 

MariaDB [(none)]> use linuxprobe;
Database changed

MariaDB [linuxprobe]> SHOW tables;
+----------------------+
| Tables_in_linuxprobe |
+----------------------+
| mybook               |
+----------------------+
1 row in set (0.000 sec)

MariaDB [linuxprobe]> describe mybook;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| name  | char(15) | YES  |     | NULL    |       |
| price | int(11)  | YES  |     | NULL    |       |
| page  | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.001 sec)

致谢

在此,我要对所有为知识共享做出贡献的个人和机构表示最深切的感谢。同时也感谢每一位花时间阅读这篇文章的读者,如果文章中有任何错误,欢迎留言指正。 

学习永无止境,让我们共同进步!!

;