Installation and use of mariadb in Linux

1. The relationship between mariadb and MySQL:

​MySQL and MariaDB are both open source database technologies. MySQL is the most widely adopted open source database. It is the primary relational database for many applications and business products. MariaDB is a modified version of MySQL. MariaDB was created by MySQL's original development team due to licensing and distribution issues after MySQL was acquired by Oracle Corporation. Since the acquisition, MySQL and MariaDB have gone through different developments. However, MariaDB adopts MySQL's data and table definition files and also uses the same client protocol, client API, ports, and sockets.

1.1. Similarities:

Since MariaDB is a fork of MySQL, the two relational database management systems have many similarities. For example, MariaDB preserves MySQL's structure, naming conventions, and data definition files. Additionally, it supports all MySQL connectors, connections, and ports. So the MySQL client package works fine in MariaDB.

ACID compliance Atomicity, consistency, isolation, and durability (ACID) are the four core principles that ensure the reliability of database transactions. Both MySQL and MariaDB adhere to these principles. Both databases maintain data accuracy and integrity by following ACID.
SQL compatibility MySQL and MariaDB are relational databases that organize data into tables. MariaDB and MySQL both use SQL to manage and query data. You can use many of the same commands across these systems.
open source software As open source relational database management systems, MySQL and MariaDB are the result of a collaborative effort by the developer community. The source code for both is available to the public. There is a fully open source version of the MySQL database, released under the General Public License (GPL). It also has a paid enterprise version that comes with additional features and support. MariaDB is fully open source on GitHub.
safety MySQL and MariaDB provide similar basic security features. They provide encryption capabilities, access control mechanisms, user authentication and authorization capabilities, and SSL/TLS support. They also allow for granular access control, allowing you to provide different permission levels to different users.

1.2. Main differences:

MySQL MariaDB
JSON MySQL stores JSON reports as binary objects. MariaDB stores JSON reports in strings. MariaDB's JSON data type is an alias for LONGTEXT.
Oracle Database Compatibility MySQL has high compatibility, but does not support PL/SQL. MariaDB is highly compatible and supports PL/SQL since version 10.3.
Speed ​​and performance MySQL is slightly slower than MariaDB when it comes to replication and querying. MariaDB is slightly faster than MySQL in terms of replication and querying.
Function MySQL supports super read-only functions, dynamic columns, and data masks. MariaDB supports invisible columns and temporary table spaces.
Authentication MySQL Yes validate_password Set. MariaDB has three password validator components.
encryption MySQL database uses InnoDB and AES to encrypt data at rest. MariaDB supports temporary log encryption and binary log encryption.
storage engine MySQL has fewer storage engines than MariaDB. MariaDB has more storage engines than MySQL, and multiple engines can be used in a table.
license There are two versions of MySQL: MySQL Enterprise Edition and GPL Edition. MariaDB is fully licensed under the GPL.
Thread Pool MySQL Enterprise Edition comes with a thread pool. MariaDB can manage over 200,000 connections simultaneously, more than MySQL.

2. Install MariaDB

2.1. Use the command to install mariadb

yum -y install mariadb-server mariadb

When complete appears, the download is complete.

Start the mariadb service and make it start automatically at boot

systemctl start mariadb
systemctl enable mariadb
systemctl status mariadb

2.2. mariadb initialization

Enter the command to initialize mariadb

mysql_secure_installation

Enter the current password. There is no password for the first installation, just press Enter.

Whether to set a new password for root, select y

Enter new password and confirm

Whether to remove anonymous users, optional, recommended y

Whether to deny remote login, it is recommended to select n

Whether to delete the test library, you can choose at will

Reload permission table: y

3. Basic operations of mariadb database

mysql -uroot -p

Enter the password you just set and enter the database

3.1. Users

Create a local user named admin with a password of 123

create user shihk@localhost identified by '123';

Grant this user all permissions

GRANT ALL PRIVILEGES ON my_database.* TO 'shihk'@'localhost';

View all users

SELECT host,user,select_priv FROM mysql.user;    ————select_priv为是否存在可查询权限

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-5NGIGp59-1692667071699)(https://yw-linux-1318457786.cos.ap-nanjing.myqcloud.com /QQ%E6%88%AA%E5%9B%BE20230815142431.png)]

delete users

DROP USER 'username'@'host';    ————username为用户名称,————host为本地访问,可以更改为%,意为任意访问

3.2. Database

Create test database

CREATE DATABASE test;

Enter the test database

use test;

Delete database

DROP DATABASE IF EXISTS 'database';    ————database为数据库名称,'IF EXISTS'指在删除前检查数据库是否存在

3.3. Data table

Create data tables s001, s002, and set the id to the primary field and auto-increment (AUTO_INCREMENT PRIMARY KEY).

CREATE TABLE s001 (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50),
    age INT
);
CREATE TABLE s002 (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50),
    age INT
);

Query all tables that exist in the database

show tables;

Delete data table

DROP TABLE '数据表';
3.3.1. Basic operations of data tables
#插入数据    ————INSERT INTO 数据表 (字段名,字段名……) VALUES( ),( ),( )……;
INSERT INTO s002 (name, age) VALUES ('Dlice', 30), ('Eob', 22), ('Farol', 28);
#查询数据    ————SELECT 字段 FROM 数据表;  查询全部字段用'*'
SELECT * FROM s002;

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-splitelh-1692667071699)(https://yw-linux-1318457786.cos.ap-nanjing.myqcloud.com /QQ%E6%88%AA%E5%9B%BE20230816142419.png)]

Related query of the contents of multiple tables

#SELECT column1, column2, ... FROM table1
 ->UNION
 ->SELECT column1, column2, ... FROM table2;
#column1, column2, ... 表示要选择的列,table1 和 table2 分别是要查询的表,全部查询用'*'。
#查询表s001,s002中name和age列内容
SELECT name,age FROM s001 UNION SELECT name,age FROM s002;

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-kiO4nG8I-1692667071699)(https://yw-linux-1318457786.cos.ap-nanjing.myqcloud.com /QQ%E6%88%AA%E5%9B%BE20230816144956.png)]

#删除数据    ————DELETE FROM 数据库 WHERE 字段 = ' ';
DELETE FROM s002 WHERE id = 3;

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-0GW0MKMS-1692667071699)(https://yw-linux-1318457786.cos.ap-nanjing.myqcloud.com /QQ%E6%88%AA%E5%9B%BE20230816142653.png)]

3.3.2. Primary and foreign key settings

​ Create table s003 and set the int type field id, which is an auto-incrementing main field; the int type field s002_id is a foreign key, bind the id in s002, so that s002 deletes data, and s003 is also deleted simultaneously.

CREATE TABLE s003 (
    id INT AUTO_INCREMENT PRIMARY KEY,
    s002_id INT,
    other_column VARCHAR(50),
    FOREIGN KEY (s002_id) REFERENCES s002(id) ON DELETE CASCADE
);

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-xIqsZCcX-1692667071700)(https://yw-linux-1318457786.cos.ap-nanjing.myqcloud.com /QQ%E6%88%AA%E5%9B%BE20230817085648.png)]

3.4. Stored procedures and triggers

3.4.1. Stored procedure settings

Create a stored procedure so that when data is inserted into s002, s003 is inserted at the same time

#存储过程的前提是两表之间有主外键关系
DELIMITER //
CREATE PROCEDURE InsertIntoS002AndS003(IN name_val VARCHAR(50), IN age_val INT)
BEGIN
    DECLARE new_id INT;

    INSERT INTO s002 (name, age) VALUES (name_val, age_val);

    SET new_id = LAST_INSERT_ID();

    INSERT INTO s003 (s002_id, other_column) VALUES (new_id, CONCAT('Data for s002_id ', new_id));
END;
//

Use stored procedures

CALL InsertIntoS002AndS003('name', age);

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-QwlBM9FB-1692667071700)(https://yw-linux-1318457786.cos.ap-nanjing.myqcloud.com /QQ%E6%88%AA%E5%9B%BE20230817113350.png)]

ps: Stored procedures are similar to functions in programming languages ​​and need to be actively called.

3.4.2. Trigger settings

Create a trigger. When data is inserted into s004, s005 is inserted at the same time.

DELIMITER //
CREATE TRIGGER InsertIntoS005OnS004Insert

#insert意为在表s004插入后触发,修改为updata,删除为delete
AFTER INSERT ON s004
#设定触发范围(每插入一行都触发)
FOR EACH ROW
BEGIN
    INSERT INTO s005 (s004_id, other_info)
    VALUES (NEW.id, CONCAT('Other info for Item ', NEW.id));
END;
//
DELIMITER ;

Insert data test

INSERT INTO s004 (name, description) VALUES ('Item 1', 'Description for Item 1');

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-ZqX6lQd7-1692667071700)(https://yw-linux-1318457786.cos.ap-nanjing.myqcloud.com /QQ%E6%88%AA%E5%9B%BE20230817113559.png)]

3.4.3. Summary

The difference between triggers and stored procedures:

  1. Execution time

    Trigger: Automatically executed before and after a specific database operation without manual invocation. It is usually used for data integrity, auditing and other requirements.

    Stored procedure: Manually called and executed at any time as needed. It is usually used to encapsulate business logic and complex data operations.

  2. 用途

    Triggers: used to handle data-level constraints, associated operations, audit records, etc.

    Stored procedures: used to perform customized business logic, data operations, data conversion, etc.

  3. reusability:

    Triggers: usually target specific tables and operations, and are difficult to reuse in multiple places.

    Stored procedures: can be called in multiple places, providing better reusability.

​ Generally speaking, triggers are suitable for maintaining integrity and triggering operations at the data level. Stored procedures can refer to functions in programming languages ​​and are more suitable for executing business logic and encapsulating reusable operations.

4. Back up the database

4.1. Write the database backup script back-up-db.sh

#!/bin/bash


#备份地址(需要先创建指定目录)
backupdir=/root/sql/crontab/db/logs
#备份文件后缀时间
time=_`date +%Y_%m_%d_%H_%M_%S`
dbfile=db${time}.sql
dbuser=root
dbpassword=123


#-h 后面跟随mariadb服务端的ip地址
mysql -e "show databases;" -h192.168.18.150 -u${dbuser} -p${dbpassword}| grep -Ev "Database|information_schema|performance_schema|mysql|test" | xargs mysqldump -h192.168.18.150 -u${dbuser} -p${dbpassword} --databases > ${backupdir}/${dbfile}

#以下为单独手动备份
#mysqldump -h192.168.18.150 --port=3306 -uroot -p123 --lock-tables=0 --all-databases > /root/db-`date "+%Y-%m-%d-%H-%M-%S"`.sql

#删除7天之前的备份文件
find $backupdir -name "db*.sql" -type f -mtime +7 -exec rm -rf {} \; > /dev/null 2>&1

echo ${dbfile}" ok"

Grant executable permission to script

chmod +x back-up-db.sh

4.2. Grant database user permissions

Enter the mariadb database (select the user to enter after -u)

mysql -uroot -p

Grant this user access on 192.168.18.150

GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.18.150' IDENTIFIED BY '123' WITH GRANT OPTION;

Exit the database after refreshing permissions

FLUSH PRIVILEGES;
exit

Execute the back-up-db.sh script

./back-up-db.sh

Shows that the database backup has been created successfully

5. Set up scheduled tasks

Change vim default editor

export VISUAL=vim

Edit scheduled tasks

#crontab -e

# 每天 15 点 45 执行
45 15 * * * /bin/bash /root/sql/crontab/db/back-up-db.sh

# 启动后执行
@reboot /bin/bash /root/sql/crontab/db/back-up-db.sh

The operation effect is as follows

6. Use backup to restore database contents

6.1. Delete the users table after entering the database

#mysql -uroot -p
#use Test;
#DROP TABLE users
退出数据库
#exit

6.2. Restore the database using backup data

root is the account, 123 is the account password, and Test is the database that needs to be restored.

/root/sql/crontab/db/logs/db_2023_07_19_15_45_01.sql is the backup file to be imported

mysql -uroot -p123 Test < /root/sql/crontab/db/logs/db_2023_07_19_15_45_01.sql

The effect is as follows


The picture is being transferred...(img-Kqpszazg-1692667071700)]

6. Use backup to restore database contents

6.1. Delete the users table after entering the database

#mysql -uroot -p
#use Test;
#DROP TABLE users
退出数据库
#exit

6.2. Restore the database using backup data

root is the account, 123 is the account password, and Test is the database that needs to be restored.

/root/sql/crontab/db/logs/db_2023_07_19_15_45_01.sql is the backup file to be imported

mysql -uroot -p123 Test < /root/sql/crontab/db/logs/db_2023_07_19_15_45_01.sql

The effect is as follows

[External link pictures are being transferred...(img-cOEBFNuS-1692667071700)]

Guess you like

Origin blog.csdn.net/m0_59575008/article/details/132420709