MariaDB database under Centos 7

1. Centos 7 binary installation and configuration of MariaDB database

I haven't installed a database server for a long time. I remember that when MySQL was installed and configured last time, the system was still Cenots 6.5. Now the Centos system version is updated too fast, and it can't keep up with the pace. Just recently, the company needs a few Mariadb Servers just to practice.

Since each company's database server version is different, I still recommend everyone to use the Mariadb database. At least the community and products are very stable at present. As for any new features, it is recommended to go to its official website to learn more about its features.

View system version command

$ cat /etc/redhat-release
CentOS Linux release 7.4.1708 (Core) x64

Install MariaDB (MySQL)

Download the MariaDB binary installation package:

https://downloads.mariadb.org
解压并安装 Mariadb-devel 静态库:

$ yum install mariadb-devel numactl -y
$ mkdir /renwole
$ cd /renwole
$ tar zxvf mariadb-10.2.8-linux-glibc_214-x86_64.tar.gz
移动目录并创建软连接:

$ mv mariadb-10.2.8-linux-glibc_214-x86_64 /usr/local
$ cd /usr/local
$ ln -s mariadb-10.2.8-linux-glibc_214-x86_64 mysql
创建 MariaDB(MySQL)用户和组

$ groupadd mysql
$ useradd -g mysql mysql
赋予 MariaDB(MySQL)目录权限:

$ cd /usr/local/mysql
$ chown -R root .
$ chown -R mysql data

Configure MariaDB (MySQL)

Delete the included my.cnf configuration file and create a new configuration file:

$ rm -rf /etc/my.cnf
$ cp /usr/local/mysql/support-files/my-large.cnf /etc/my.cnf

Note: There are 5 configuration files under /usr/local/mysql/support-files, please select the configuration file according to the memory size of the server (you can also customize and optimize the my.cnf configuration file, if you have it before, as long as it is the same version It can be used normally, so there is no need to create it again. When MariaDB (MySQL) starts, it will automatically go to /etc to find the my.cnf file).

The files are:

my-small.ini (内存 < = 64M)
my-medium.ini (内存 128M )
my-large.ini (内存 512M)
my-huge.ini (内存 1G-2G)
my-innodb-heavy-4G.ini (内存 4GB)

Add the database path to the mysqld field of the my.cnf file:

$ vim /etc/my.cnf
datadir = /usr/local/mysql/data

Note: This path is used to initialize the database. In the future, your database will all exist in this directory. This storage path can be changed to other paths to avoid unnecessary losses caused by system downtime in the future, so please replace it according to your own needs. The path, don't forget to give permissions on the line.

Initialize the database

$ cd /usr/local/mysql/scripts
$ ./mysql_install_db --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data

$ cd /usr/local/mysql/support-files
$ cp mysql.server /etc/init.d/mysql
$ chmod +x /etc/init.d/mysql
$ systemctl enable mysql

Add system variables, for example, directly input: mysql -uroot -p will prompt that there is no such command:

$ vim /etc/profile

Add the following at the end of the file:

PATH=$PATH:/usr/local/mysql/bin
export PATH

Make the variable take effect immediately and start the Mysql database:

$ source /etc/profile
$ systemctl restart mysql
$ ss -antp

Initialize MariaDB (MySQL) Security Account

$ /usr/local/mysql/bin/mysql_secure_installation

Note: Press Enter to prompt you to enter the MariaDB (MySQL) password. The newly installed mysql password is empty by default, so just press Enter, then enter Y to set the MySQL password, enter twice Enter, then press Y for all (roughly) It means to delete the test database, anonymous account, and finally the Y configuration takes effect.

 

2. Mariadb database and table management

database management

Buddha said: "First there is the library, then there is the table, and then there is the data..."

create database

CREATE DATABASE [IF NOT EXISTS] db_name
    [create_specification] ...
create_specification:
    [DEFAULT] CHARACTER SET [=] charset_name
  | [DEFAULT] COLLATE [=] collation_name

For example: create a database and specify the default character set as UTF-8

SHOW CHARACTER SET;//查看支持的字符集
CREATE DATABASE mydb CHARACTER SET='utf8'; //创建数据库mydb,并指定字符集为utf-8

View database creation information

MariaDB [(none)]> SHOW CREATE DATABASE mydb;
+----------+---------------------------------------------------------------+
| Database | Create Database                                               |
+----------+---------------------------------------------------------------+
| mydb     | CREATE DATABASE `mydb` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+----------+---------------------------------------------------------------+
1 row in set (0.00 sec)

`

Modify the database

ALTER {DATABASE | SCHEMA} [db_name]
alter_specification ...
ALTER {DATABASE | SCHEMA} db_name
UPGRADE DATA DIRECTORY NAME //这条命令在升级数据库时,使用此命令重新编码数据库文件
alter_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_nam
修改数据库mydb的字符集为utf-16:
MariaDB [(none)]> ALTER DATABASE mydb CHARACTER SET = utf16;
Query OK, 1 row affected (0.00 sec)

delete database

DROP {DATABASE | SCHEMA} [IF EXISTS] db_name 删除数据库非常的。。。快!所以呢,想好再回车。
MariaDB [(none)]> DROP DATABASE IF EXISTS mydb;
Query OK, 0 rows affected (0.00 sec)
设定数据库默认字符集
只需要在my.cnf中加入此指令即可,在[mysqld]下:
character_set_server = utf8

table management

create table

CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    (create_definition,...) [table_options    ]... [partition_options]

The most basic is the table definition option, as follows:

column_definition:
    data_type
      [NOT NULL | NULL] [DEFAULT default_value | (expression)]
      [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
      [INVISIBLE] [{WITH|WITHOUT} SYSTEM VERSIONING]
      [COMMENT 'string']
      [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]
      [reference_definition]

For example: Create a User table with 4 fields: ID, username, password, login time

MariaDB [mydb]> CREATE TABLE IF NOT EXISTS user(
    -> id INT AUTO_INCREMENT PRIMARY KEY,
    -> username VARCHAR(10) NOT NULL,
    -> password VARCHAR(32) NOT NULL,
    -> logintime TIMESTAMP NOT NULL);

View table

In Mysql, you can use DESCRIBE table_name; to view the definition of the table, DESCRIBE can be abbreviated as DESC, as follows:

MariaDB [mydb]> DESC user;
+-----------+-------------+------+-----+-------------------+-----------------------------+
| Field     | Type        | Null | Key | Default           | Extra                       |
+-----------+-------------+------+-----+-------------------+-----------------------------+
| id        | int(11)     | NO   | PRI | NULL              | auto_increment              |
| username  | varchar(10) | NO   |     | NULL              |                             |
| password  | varchar(32) | NO   |     | NULL              |                             |
| logintime | timestamp   | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-----------+-------------+------+-----+-------------------+-----------------------------+
4 rows in set (0.03 sec)

Of course, we can also use SHOW CREATE TABLE table_name; to view the command used to define the table

MariaDB [mydb]> SHOW CREATE TABLE user;
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                                                                           |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| user  | CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(10) NOT NULL,
  `password` varchar(32) NOT NULL,
  `logintime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf16 |  //这里可以看到这张表使用的存储引擎和字符集
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Modify table

1. Add a new field registertime to the user table to record the user's registration time

MariaDB [mydb]> ALTER TABLE user ADD COLUMN registtime TIMESTAMP NOT NULL AFTER logintime;

Therefore, the format of the added field can be as follows:

ALTER TABLE table_name ADD [COLUMN] col_name column_definition
        [FIRST | AFTER col_name ]

Among them, FIRST and AFTER specify where the newly added field is, FIRST represents the first column, and AFTER indicates after a certain column

2. Modify a field for the user table, and change the data type of the newly added registertime field to datatime type

MariaDB [mydb]> ALTER TABLE user MODIFY COLUMN registtime DATETIME;
命令格式如下:
ALTER TABLE table_name MODIFY [COLUMN] col_name column_definition
        [FIRST | AFTER col_name]

`
3. Modify the field registertime to createtime

MariaDB [mydb]> ALTER TABLE user CHANGE registtime createtime DATETIME NOT NULL;
命令格式如下,需要重新定义下新的字段:
ALTER TABLE table_name CHANGE [COLUMN] old_col_name new_col_name column_definition
        [FIRST|AFTER col_name]

4. Delete the createtime field, the data of this field in all rows will also be deleted

MariaDB [mydb]> ALTER TABLE user DROP COLUMN createtime;

5. Modify the table name user to users

MariaDB [mydb]> ALTER TABLE user RENAME TO users;

6. Modify the character set of the data table

MariaDB [mydb]> ALTER TABLE users DEFAULT CHARACTER SET=utf8;

7. Modify the storage engine of the data table. I don't know much about the storage engine for the time being, so this command... Well, you know.

MariaDB [mydb]> ALTER TABLE users ENGINE=MyISAM;

Will lead to data reconstruction... So, modify with caution

8. Modify the sort field of the data table

MariaDB [mydb]> ALTER TABLE users ORDER BY logintime;

Deleting a table
is the same as deleting a database, be careful when pressing the enter key

MariaDB [mydb]> DROP TABLE IF EXISTS users;

 

3. Mariadb: data type

type of data

Data type -> is an abstraction of a class of data classifications with the same properties and properties.

For example:
a string, which is a string of characters composed of one by one, is called a string... In the computer, substrings can be divided, and new characters can be added at the end of the string, and such operations can only operate on string data, not Manipulate integers.
Digital type, the Arabic numerals we most often come into contact with, can perform arithmetic operations, logical operations, etc.

Data Types in Mysql

MySQL supports a variety of types, which can be roughly divided into three categories: numeric, date/time, and string (character) types.

Numeric type

1. For the integer type, its length can be limited, the format is as follows:

整数类型[(M)] [SIGNED | UNSIGNED | ZEROFILL]

M is the number of digits, such as TINYINT(3), which can only store three digits, and the number of digits should not exceed the range that it can represent.
SIGNED: The default is a signed number
UNSIGNED: specified as an unsigned number
ZEROFILL: When When the M bits are not satisfied, the front is filled with 0, and it becomes an unsigned number.

2. For floating-point numbers, the overall number of digits and the number of digits after the decimal point can be limited

(FLOAT|DOUBLE)[(M,D)] [SIGNED | UNSIGNED | ZEROFILL]

M is the total number of digits, D is the number of digits after the decimal point
ZEROFILL For floating point type, the effect is equivalent to UNSIGNED

MariaDB [mydb]> DESC t1;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| c1    | float(5,2)   | YES  |     | NULL    |       |
| c2    | double(10,3) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
MariaDB [mydb]> INSERT INTO t1 VALUES(23.5,12.34566777);
Query OK, 1 row affected (0.01 sec)
MariaDB [mydb]> SELECT * FROM t1;   //这里可以看到,在其后补了0
+-------+--------+
| c1    | c2     |
+-------+--------+
| 23.50 | 12.346 |
+-------+--------+
1 row in set (0.00 sec)

date and time type

Format abbreviation: Date time format, which supports loose format in addition to standard format.

Create a test table with the following structure:

MariaDB [mydb]> desc datetable;
+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type      | Null | Key | Default           | Extra                       |
+-------+-----------+------+-----+-------------------+-----------------------------+
| c1    | date      | YES  |     | NULL              |                             |
| c2    | time      | YES  |     | NULL              |                             |
| c3    | datetime  | YES  |     | NULL              |                             |
| c4    | timestamp | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+

For DATE type: YY-MM-DD, YYMMDD, YYYY/MM/DD

MariaDB [mydb]> INSERT INTO datetable(c1) VALUES('2018-01-01'),('18-01-01'),
    -> ('180101'),('2018/01/01'),(180101);
Query OK, 5 rows affected (0.01 sec)
Records: 5  Duplicates: 0  Warnings: 0
MariaDB [mydb]> SELECT c1 FROM datetable;
+------------+
| c1         |
+------------+
| 2018-01-01 |
| 2018-01-01 |
| 2018-01-01 |
| 2018-01-01 |
| 2018-01-01 |
+------------+
5 rows in set (0.00 sec)

For TIME type: 'D HH:MM:SS', 'HH:MM:SS', 'HH:MM', 'D HH:MM', 'D HH', 'SS', 'HHMMSS'
D stands for day, That is TIME+D*24

MariaDB [mydb]> INSERT INTO datetable(c2) VALUES
    -> ('12:20:20'),('1 12:20:20'),
    -> ('12:20'),('1 12'),('20'),('122020'), 
    -> (122020);
Query OK, 7 rows affected (0.03 sec)
Records: 7  Duplicates: 0  Warnings: 0
MariaDB [mydb]> SELECT c2 FROM datetable;
+----------+
| c2       |
+----------+
| 12:20:20 |
| 36:20:20 |
| 12:20:00 |
| 36:00:00 |
| 00:00:20 |
| 12:20:20 |
| 12:20:20 |
+----------+
7 rows in set (0.00 sec)

For the two formats DATETIME and TIMESTAMP, it is the abbreviation of the above time abbreviation format, for example:

20180101122020 -> '2018-01-01 12:20:20'

For the format of TIMESTAMP, it is more commonly used. It should be said that it stores the number of milliseconds from '1970-01-01 00:00:00' to the storage time. The default value can be CURRENT_TIMESTAMP or its synonym:

CURRENT_TIMESTAMP(), NOW(), LOCALTIME, LOCALTIME(), LOCALTIMESTAMP,LOCALTIMESTAMP()

String type

 

The CHAR and VARCHAR types are similar, but they are stored and retrieved differently. They also differ in terms of their maximum length and whether trailing spaces are preserved. No case conversion is done during storage or retrieval.

The BINARY and VARBINARY classes are similar to CHAR and VARCHAR, except that they contain binary strings instead of non-binary strings. That is, they contain byte strings instead of character strings. This means they have no character set, and sorting and comparison is based on the numeric values ​​of the column value bytes.

A BLOB is a binary large object that can hold a variable amount of data:
there are 4 BLOB types: TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. They just differ in the maximum length of the value they can hold.
There are 4 TEXT types: TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT. These correspond to the 4 BLOB types, with the same maximum length and storage requirements.

other types

Enumeration type: ENUM('value1','value2',...)
Storage bytes: Because it stores the element number, it only occupies one byte for 0-255 elements, and 255-65535 occupies two element

 

Fourth, Mariadb: data insertion, deletion and modification

INSERT insert data

INSERT statement format:

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
 [INTO] tbl_name [PARTITION (partition_list)] [(col,...)]
 {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
 [ ON DUPLICATE KEY UPDATE
   col=expr
     [, col=expr] ... ]

The table structure is as follows:

MariaDB [mydb]> DESC user;
+----------+-------------+------+-----+---------------------+----------------+
| Field    | Type        | Null | Key | Default             | Extra          |
+----------+-------------+------+-----+---------------------+----------------+
| id       | int(11)     | NO   | PRI | NULL                | auto_increment |
| username | varchar(10) | NO   |     | NULL                |                |
| password | varchar(10) | NO   |     | NULL                |                |
| regtime  | timestamp   | NO   |     | CURRENT_TIMESTAMP   |                |
| logtime  | timestamp   | NO   |     | 0000-00-00 00:00:00 |                |
| logip    | varchar(20) | YES  |     | NULL                |                |
+----------+-------------+------+-----+---------------------+----------------+
6 rows in set (0.01 sec)

Insert a single piece of data

MariaDB [mydb]> INSERT INTO user VALUES(1,'test','test',NOW(),NOW(),'127.0.0.1');

Because in many cases some values ​​are default, we can specify which columns to insert data for, and other columns use default values, as follows:

MariaDB [mydb]> INSERT INTO user(username,password) VALUES('test2','test2');

Similarly, inserting data in a specific column can also be written like this:

MariaDB [mydb]> INSERT INTO user SET username='test3',password='test3';

This only inserts the username and password, and uses the default for other values.

MariaDB [mydb]> SELECT * FROM user;
+----+----------+----------+---------------------+---------------------+-----------+
| id | username | password | regtime             | logtime             | logip     |
+----+----------+----------+---------------------+---------------------+-----------+
|  1 | test     | test     | 2018-02-24 15:43:41 | 2018-02-24 15:43:41 | 127.0.0.1 |
|  2 | test2    | test2    | 2018-02-24 15:45:16 | 0000-00-00 00:00:00 | NULL      |
|  3 | test3    | test3    | 2018-02-24 15:46:56 | 0000-00-00 00:00:00 | NULL      |
+----+----------+----------+---------------------+---------------------+-----------+
3 rows in set (0.00 sec)

Insert multiple rows of data

Many times we have the need to use one INSERT statement to insert multiple records into the data table, which can be written like this:

MariaDB [mydb]> INSERT INTO user(username,password) VALUES('test4','test4'),('test5',
    -> 'test5');

Inexplicable priorities?


When the storage engine used (MyISAM, MEMORY, MERGE) uses table-level locks, you can use

LOW_PRIORITY| HIGH_PRIORITY这两个关键字:
    当使用LOW_PRIORITY关键字时,当没有客户端再读取该表时才写入数据。
    当使用HIGH_PRIORITY时,INSERT语句具有同SELECT语句一样的优先级。(默认策略)

Therefore, when a SELECT statement is executed before the INSERT statement is executed, the INSERT blocks and waits for the SELECT to be read, but at this time, if a SELECT enters the scheduling again, the SELECT is blocked (the read lock can be read directly), but at this time because the INSERT The statement has the same priority as the SELECT statement, so the SELECT cannot be executed until the INSERT ends, so the INSERT can add LOW_PRIORITY to optimize the reading speed.

Let's take a look here, I don't know much about locks.

change the data

The syntax of the UPDATE statement is as follows:

UPDATE [LOW_PRIORITY] [IGNORE] table_reference 
  [PARTITION (partition_list)]
  SET col1={expr1|DEFAULT} [,col2={expr2|DEFAULT}] ...
  [WHERE where_condition]
  [ORDER BY ...]
  [LIMIT row_count]

update all

When the WHERE clause is not used to constrain the selection conditions, all data is updated. For example, the login time of all records in the user table is modified to now:

MariaDB [mydb]> UPDATE user SET logtime=NOW();
Query OK, 5 rows affected (0.01 sec)
Rows matched: 5  Changed: 5  Warnings: 0

Update the login IP of the three earliest registered people to 127.0.0.1

MariaDB [mydb]> UPDATE user SET logip='127.0.0.1' ORDER BY regtime LIMIT 3;

The ORDER BY statement can be used for SELECT UPDATE DELETE, etc., to indicate which field of the table to follow when outputting, deleting, and updating the table.

For example, in the above, ORDER BY regtime is to arrange and update in positive order according to the registration time, and only the first three rows are updated with the LIMIT statement.

Then use DESC to specify the flashback arrangement, for example: ORDER BY regtime DESC

LIMIT statement: used to limit the number of query results.
usage:

LIMIT[position offset,] number of lines
The first line starts at 0, so the following:

SELECT * FROM user LIMIT 2,2;  //从第3行开始,取两行,即取第3、4条记录。
使用WHERE语句选中特定行更新
MariaDB [mydb]> UPDATE user SET logip='192.168.1.2' WHERE username='test2';

Because the WHERE clause also has a lot of things, I won't post too much here.

LOW_PRIORITY:这个跟INSERT的LOW_PRIORITY是一样的。

REPLACE statement

MariaDB [mydb]> REPLACE INTO user VALUES(1,'test111','test111',NOW(),NOW(),'192.168.1.1');

The above statement is MariaDB's extended SQL, which is equivalent to deleting duplicate records (primary key or unique index) and adding new records.

Seems a bit tasteless? ….

delete data

DELETE语语法:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] 
    FROM tbl_name [PARTITION (partition_list)]
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]
    [RETURNING select_expr 
      [, select_expr ...]]

delete all data

When the WHERE statement is not used to constrain the conditions, all data is deleted, as follows:

MariaDB [mydb]> DELETE FROM user;

Use WHERE statement to constrain selected rows

MariaDB [mydb]> DELETE FROM user WHERE username='test1';

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325877279&siteId=291194637