一、mysql简介及安装配置

1、mysql简介


2、mysql linux版安装

二级制源码安装、rpm包本地安装、yum安装
本次采用rpm安装

2.1 下载地址

https://dev.mysql.com/downloads/
beta版
release版
ga版(稳定发布版)generally available release

wget https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-community-server-5.7.27-1.el6.x86_64.rpm
wget https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-community-client-5.7.27-1.el6.x86_64.rpm

mysql-community-common-5.7.27-1.el6.x86_64.rpm
mysql-community-libs-5.7.27-1.el6.x86_64.rpm
mysql-community-client-5.7.27-1.el6.x86_64.rpm
mysql-community-server-5.7.27-1.el6.x86_64.rpm

2.2 检查当前系统是否安装过mysql

# 查询当前系统是否安装过mariadb或mysql
rpm -qa | grep -i 'mariadb\|mysql'
# 删除卸载安装过的package
rpm -e xxxx
rpm -e --nodeps yyyy

2.3 安装mysql服务端

# rpm包有依赖顺序
rpm -ivh mysql-community-common-5.7.27-1.el6.x86_64.rpm 
rpm -ivh mysql-community-libs-5.7.27-1.el6.x86_64.rpm 
rpm -ivh mysql-community-client-5.7.27-1.el6.x86_64.rpm 
rpm -ivh mysql-community-server-5.7.27-1.el6.x86_64.rpm 

2.4 查看mysql安装时创建的mysql用户和mysql组

cat /etc/passwd | grep mysql
cat /etc/group | grep mysql

2.5 mysql服务的启动+停止

#启动mysql
service mysqld start
#关闭mysql
service mysqld stop
[root@michael ~]# ps -ef | grep mysql | grep -v grep
root       3065      1  0 23:05 pts/0    00:00:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --socket=/var/lib/mysql/mysql.sock --pid-file=/var/run/mysqld/mysqld.pid --basedir=/usr --user=mysql
mysql      3259   3065  0 23:05 pts/0    00:00:00 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --user=mysql --log-error=/var/log/mysqld.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/lib/mysql/mysql.sock

针对上面的参数简单记录

/bin/sh /usr/bin/mysqld_safe 			使用bash运行的具体脚本
--datadir=/var/lib/mysql 				数据库文件保存目录
--socket=/var/lib/mysql/mysql.sock 		sock文件位置,3306
--pid-file=/var/run/mysqld/mysqld.pid 	进程标识文件位置
--basedir=/usr 							mysql管理软件安装位置
--user=mysql							运行用户				
/usr/sbin/mysqld 								mysqld数据库管理系统运行程序
--basedir=/usr 									mysql管理软件安装位置
--datadir=/var/lib/mysql 						数据库文件保存目录
--plugin-dir=/usr/lib64/mysql/plugin 			插件
--user=mysql 									mysqld服务的启动用户
--log-error=/var/log/mysqld.log 				错误日志位置
--pid-file=/var/run/mysqld/mysqld.pid 			进程标识文件位置
--socket=/var/lib/mysql/mysql.sock				sock文件位置,3306

2.6 mysql服务启动后,连接

2.6.1 连接报错
[root@michael ~]# mysql
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
2.6.2 查看默认密码
[root@michael ~]# cat /var/log/mysqld.log | grep 'temporary password'
2020-03-16T22:19:40.820924Z 1 [Note] A temporary password is generated for root@localhost: m:Lsfpi6SpRe
2.6.3 使用默认密码登录
[root@michael ~]# mysql -uroot -pm:Lsfpi6SpRe
2.6.4 修改密码
-- dsfgs 
alter user 'root'@'localhost' identified by 'root';

flush privileges;

2.6.5 设置root可远程登录
-- 切换数据库
use mysql;
-- 查看user表中的用户
select host,user from user;
-- 授权远程登录
GRANT ALL PRIVILEGES 
ON *.* 
TO 'root'@'%' 
IDENTIFIED BY 'root' 
WITH GRANT OPTION;
-- 刷新权限
flush privileges;  

2.7 自启动mysql服务

[root@michael ~]# chkconfig mysqld off
[root@michael ~]# chkconfig --list | grep mysql
mysqld         	0:off	1:off	2:off	3:off	4:off	5:off	6:off

[root@michael ~]# chkconfig mysqld on
[root@michael ~]# chkconfig --list | grep mysql
mysqld         	0:off	1:off	2:on	3:on	4:on	5:on	6:off

2.8 修改配置文件位置

mysql默认使用的配置文件位置

[root@michael ~]# mysql --help | grep 'Default options' -A 1
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf
path desc note
/var/lib/mysql/ mysql数据库文件的存放路径 /var/lib/mysql/michael.pid
/usr/share/mysql/ 配置文件目录 mysql.server命令及配置文件
/usr/bin/ 相关命令目录 mysqladmin mysqldump等命令
/etc/init.d/mysqld 启动停止脚本

2.9 修改字符集和数据存储路径

-- 创建数据库
create database mydb001;
-- 切换数据库
use mydb001;
-- 查看库中的表
show tables;
-- 创建一张测试用表
create table my_table01(id int not null,name varchar(100));
-- 插入数据
insert into my_table01 values(101,'LiBai');
-- 查看表中的的数据
mysql> select * from my_table01;
+-----+-------+
| id  | name  |
+-----+-------+
| 101 | LiBai |
+-----+-------+
1 row in set (0.00 sec)

-- 插入包含中文的数据
mysql> insert into my_table01 values(101,'白居易');
ERROR 1366 (HY000): Incorrect string value: '\xE7\x99\xBD\xE5\xB1\x85...' for column 'name' at row 1

mysql> show variables like 'character%';
mysql> show variables like '%char%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | latin1                     |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | latin1                     |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

默认的character_set_database和character_set_server都用了latin1,所以会插入数据报错。
[root@michael ~]# vim /etc/my.cnf

# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html
[client]

[mysqld]
character_set_server=utf8
character_set_client=utf8
collation-server=utf8_general_ci
# Linux下mysql安装完成后默认:表名区分大小写;列名不区分大小写
# 0:区分大小写; 1:不区分大小写
lower_case_table_names=1
# 设置最大连接数,默认为151,Mysql服务器允许的最大连接数16384
max_connections=100

datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

[mysql]
default-character-set=utf8

3、mysql配置文件

3.1 二进制日志log-bin

用于主从复制

# Relication Master Server (default)
# binary logging is required for repalication
log-bin=mysql-bin

3.2 错误日志log-error

默认关闭,记录严重的警告和错误信息,每次启动和关闭的详细信息等。

3.3 查询日志log

默认关闭,记录查询的sql语句。
如果开启会降低mysql的整体性能,因为记录日志也是需要消耗系统资源。

3.4 数据文件

ls -1F | grep ^d
默认路径:/usr/lib/mysql

3.4.1 frm文件

存放表结构

3.4.1 myd文件

存放表数据

3.4.1 myi文件

存放表索引

3.5 如何配置

windows:my.ini文件

log-bin=D:/xx/yyy-log-bin
log-err=D:/xx/yyy-log-err

linux:/etc/my.cnf文件


4、mysql逻辑架构介绍

MySQL采用插件式的存储引擎架构将查询处理和其他的系统任务以及数据的存储提取相分离。这种架构可以根据业务的需要和实际需要选择合适的存储引擎。
在这里插入图片描述

4.1 连接层

最上层是一些客户端和连接服务,包含本地sock通信和大多数基于客户端/服务端工具实现的类似于TCP/IP的通信。主要完成一些类似于连接处理、授权认证、及相关的安全方案。在该层上引入了线程池的概念,为通过认证安全接入的客户端提供线程。同样在该层上可以实现基于SSL的安全链接。服务器也会为安全接入的每个客户端验证它所具有的操作权限。

4.2 服务层

第二层架构主要完成大多数的核心功能,如SQL接口,并完成缓存的查询,SQL的分析和优化及部分内置函数的执行。所有跨存储引擎的功能也在这一层实现,如过程、函数等。在该层,服务器会解析查询并创建相应的内部解析树,并对其完成相应的优化如确定查询表的顺序,是否利用索引等,最后生成相应的执行操作。如果是select语句,服务器还会查询内部的缓存。如果缓存空间足够大,这样在解决大量读操作的环境中能够很好的提升系统的性能。

4.3 引擎层

存储引擎真正的负责了MySQL中数据的存储和提取,服务器通过API与存储引擎进行通信。不同的存储引擎具有的功能不同,我们可根据实际需要进行选取。

4.4 存储层

数据存储层,主要是将数据存储在运行于裸设备的文件系统之上,并完成与存储引擎的交互。


5、mysql存储引擎

-- 查看当前mysql提供了哪些存储引擎
mysql> show engines;

在这里插入图片描述

-- 查看当前mysql默认使用的存储引擎
mysql> show variables like '%storage_engine%';

在这里插入图片描述

对比项 MyISAM InnoDB
主外键 不支持 支持
事务 不支持 支持
行表锁 表锁,即使操作一条记录也会锁住整个表,
不适合高并发的操作
行锁,操作时只锁某一行,不对其他行影响,
适合高并发操作
缓存 只缓存索引,不缓存真是数据 不仅缓存索引还要缓存真实数据,对内存要求较高,
而且内存大小对性能有决定性的影响
表空间
关注点 性能 事务
默认安装 YES YES

percona为mysql数据库服务器进行了改进,在功能和性能上较mysql有着很显著的提升。
perconna新建了一款存储引擎xtradb完全可以替代innodb,并且在性能和并发上做的更好。



注:忘记密码时修改密码.

/usr/sbin/mysqld --skip-grant-tables --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --user=mysql --log-error=/var/log/mysqld.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/lib/mysql/mysql.sock
mysql> update mysql.user set authentication_string=password('123456') where user='root' and Host = 'localhost'; 
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

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


注:
法一:

alter 
user 'root'@'localhost' 
identified by '123456';

法二:

set password for 'root'@'localhost'=password('123456');

法三:

update mysql.user 
set authentication_string=password('123456') 
where user='root' and Host = 'localhost';

最后刷新权限

mysql> flush privileges;


server-id=1
log-bin=自己本地的路径/mysqlbin

server-id=2

grant replication slave on . to ‘xxx’@’%’ identified by ‘123456’;

change master to
master_host=‘192.168.21.193’,
master_user=‘zhangsan’,
master_password=‘123456’,
master_log_file=‘mysqlbin.具体数字’,
master_log_pos=‘具体值’;

=========================================
备份
mysqldump -uroot --all-databases --lock-all-tables > ~/my_master_db.sql
mysqldump -uroot -proot 数据库名 > /opt/my_master_db.sql
恢复
连接数据库,创建数据库
退出连接,执行如下命令
mysql -uroot -proot < ~/my_master_db.sql
mysql -uroot -proot 新数据库名 < ~/my_master_db.sql

=====================================================
set global validate_password_policy=0;
set global validate_password_length=1;

1,master 设置server-id
2,开启二进制日志
server-id=1
log_bin=/var/log/mysql/mysql-bin.log

grant replication slave
on .
to ‘xxxx’@’%’
identified by ‘yyyy’;

flush privileges;

show master status;

1,slave设置server-id
2,去哪里什么位置复制
server-id=2

change master to
master_host=‘192.168.168.168’,
master_user=‘xxxx’,
master_password=‘yyyy’,
master_log_file=‘mysqlbin.000001’,
master_log_pos=589;

start slave;

show slave status \G;

slave_IO_running:yes
slave_sql_running:yes

CREATE TABLE Persons11
(
Id_P int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)


mysql8.0 修改密码:

mysql> SHOW VARIABLES LIKE 'validate_password%';
+--------------------------------------+--------+
| Variable_name                        | Value  |
+--------------------------------------+--------+
| validate_password.check_user_name    | ON     |
| validate_password.dictionary_file    |        |
| validate_password.length             | 8      |
| validate_password.mixed_case_count   | 1      |
| validate_password.number_count       | 1      |
| validate_password.policy             | MEDIUM |
| validate_password.special_char_count | 1      |
+--------------------------------------+--------+
7 rows in set (0.11 sec)

设置“123456”等简单密码需修改密码规则:

mysql> set global validate_password.policy=0;
mysql> set global validate_password.length=1;

设置密码为:

mysql> alter user'root'@'localhost' identified by '123456';
Query OK, 0 rows affected (0.01 sec)

注:

validate_password_policy取值有0、1、2。
默认是1,即MEDIUM,所以设置的密码必须符合长度,且必须含有数字,小写或大写字母,特殊字符
取值0:只限制密码长度,大于validate_password.length参数即可。


mysql5.7 修改密码:

mysql> use mysql;
mysql> update mysql.user set authentication_string=password('Mysql123$') where user='root' and host='localhost';    # and host='localhost'部分可以不加
mysql> flush privileges;    # 刷新权限

mysql5.6 修改密码:

mysql> use mysql; 
mysql> update user set password=password('Mysql123@') where user='root' and host='localhost'; 
mysql> flush privileges;    # 刷新权限

– sdfdsf
SHOW VARIABLES LIKE ‘validate_password%’;
set global validate_password_policy=0;
set global validate_password_length=1;
select @@validate_password_policy;
select @@validate_password_length;
select @@validate_password_mixed_case_count;

– 或者
set password=password(“root”);

select user,host,password from user;

update user
set password=password(‘root’)
where user=‘root’ and host=‘localhost’;

[root@michael ~]# mysql --help
mysql  Ver 14.14 Distrib 5.7.27, for Linux (x86_64) using  EditLine wrapper
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

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

Usage: mysql [OPTIONS] [database]
  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup
                      and reconnecting may take a longer time. Disable with
                      --disable-auto-rehash.
                      (Defaults to on; use --skip-auto-rehash to disable.)
  -A, --no-auto-rehash 
                      No automatic rehashing. One has to use 'rehash' to get
                      table and field completion. This gives a quicker start of
                      mysql and disables rehashing on reconnect.
  --auto-vertical-output 
                      Automatically switch to vertical output mode if the
                      result is wider than the terminal width.
  -B, --batch         Don't use history file. Disable interactive behavior.
                      (Enables --silent.)
  --bind-address=name IP address to bind to.
  --binary-as-hex     Print binary data as hex
  --character-sets-dir=name 
                      Directory for character set files.
  --column-type-info  Display column type information.
  -c, --comments      Preserve comments. Send comments to the server. The
                      default is --skip-comments (discard comments), enable
                      with --comments.
  -C, --compress      Use compression in server/client protocol.
  -#, --debug[=#]     This is a non-debug version. Catch this and exit.
  --debug-check       This is a non-debug version. Catch this and exit.
  -T, --debug-info    This is a non-debug version. Catch this and exit.
  -D, --database=name Database to use.
  --default-character-set=name 
                      Set the default character set.
  --delimiter=name    Delimiter to be used.
  --enable-cleartext-plugin 
                      Enable/disable the clear text authentication plugin.
  -e, --execute=name  Execute command and quit. (Disables --force and history
                      file.)
  -E, --vertical      Print the output of a query (rows) vertically.
  -f, --force         Continue even if we get an SQL error.
  --histignore=name   A colon-separated list of patterns to keep statements
                      from getting logged into syslog and mysql history.
  -G, --named-commands 
                      Enable named commands. Named commands mean this program's
                      internal commands; see mysql> help . When enabled, the
                      named commands can be used from any line of the query,
                      otherwise only from the first line, before an enter.
                      Disable with --disable-named-commands. This option is
                      disabled by default.
  -i, --ignore-spaces Ignore space after function names.
  --init-command=name SQL Command to execute when connecting to MySQL server.
                      Will automatically be re-executed when reconnecting.
  --local-infile      Enable/disable LOAD DATA LOCAL INFILE.
  -b, --no-beep       Turn off beep on error.
  -h, --host=name     Connect to host.
  -H, --html          Produce HTML output.
  -X, --xml           Produce XML output.
  --line-numbers      Write line numbers for errors.
                      (Defaults to on; use --skip-line-numbers to disable.)
  -L, --skip-line-numbers 
                      Don't write line number for errors.
  -n, --unbuffered    Flush buffer after each query.
  --column-names      Write column names in results.
                      (Defaults to on; use --skip-column-names to disable.)
  -N, --skip-column-names 
                      Don't write column names in results.
  --sigint-ignore     Ignore SIGINT (CTRL-C).
  -o, --one-database  Ignore statements except those that occur while the
                      default database is the one named at the command line.
  --pager[=name]      Pager to use to display results. If you don't supply an
                      option, the default pager is taken from your ENV variable
                      PAGER. Valid pagers are less, more, cat [> filename],
                      etc. See interactive help (\h) also. This option does not
                      work in batch mode. Disable with --disable-pager. This
                      option is disabled by default.
  -p, --password[=name] 
                      Password to use when connecting to server. If password is
                      not given it's asked from the tty.
  -P, --port=#        Port number to use for connection or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --prompt=name       Set the mysql prompt to this value.
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).
  -q, --quick         Don't cache result, print it row by row. This may slow
                      down the server if the output is suspended. Doesn't use
                      history file.
  -r, --raw           Write fields without conversion. Used with --batch.
  --reconnect         Reconnect if the connection is lost. Disable with
                      --disable-reconnect. This option is enabled by default.
                      (Defaults to on; use --skip-reconnect to disable.)
  -s, --silent        Be more silent. Print results with a tab as separator,
                      each row on new line.
  -S, --socket=name   The socket file to use for connection.
  --ssl-mode=name     SSL connection mode.
  --ssl               Deprecated. Use --ssl-mode instead.
                      (Defaults to on; use --skip-ssl to disable.)
  --ssl-verify-server-cert 
                      Deprecated. Use --ssl-mode=VERIFY_IDENTITY instead.
  --ssl-ca=name       CA file in PEM format.
  --ssl-capath=name   CA directory.
  --ssl-cert=name     X509 cert in PEM format.
  --ssl-cipher=name   SSL cipher to use.
  --ssl-key=name      X509 key in PEM format.
  --ssl-crl=name      Certificate revocation list.
  --ssl-crlpath=name  Certificate revocation list path.
  --tls-version=name  TLS version to use, permitted values are: TLSv1, TLSv1.1
  -t, --table         Output in table format.
  --tee=name          Append everything into outfile. See interactive help (\h)
                      also. Does not work in batch mode. Disable with
                      --disable-tee. This option is disabled by default.
  -u, --user=name     User for login if not current user.
  -U, --safe-updates  Only allow UPDATE and DELETE that uses keys.
  -U, --i-am-a-dummy  Synonym for option --safe-updates, -U.
  -v, --verbose       Write more. (-v -v -v gives the table output format).
  -V, --version       Output version information and exit.
  -w, --wait          Wait and retry if connection is down.
  --connect-timeout=# Number of seconds before connection timeout.
  --max-allowed-packet=# 
                      The maximum packet length to send to or receive from
                      server.
  --net-buffer-length=# 
                      The buffer size for TCP/IP and socket communication.
  --select-limit=#    Automatic limit for SELECT when using --safe-updates.
  --max-join-size=#   Automatic limit for rows in a join when using
                      --safe-updates.
  --secure-auth       Refuse client connecting to server if it uses old
                      (pre-4.1.1) protocol. Deprecated. Always TRUE
  --server-arg=name   Send embedded server this as a parameter.
  --show-warnings     Show warnings after every statement.
  -j, --syslog        Log filtered interactive commands to syslog. Filtering of
                      commands depends on the patterns supplied via histignore
                      option besides the default patterns.
  --plugin-dir=name   Directory for client-side plugins.
  --default-auth=name Default authentication client-side plugin to use.
  --binary-mode       By default, ASCII '\0' is disallowed and '\r\n' is
                      translated to '\n'. This switch turns off both features,
                      and also turns off parsing of all clientcommands except
                      \C and DELIMITER, in non-interactive mode (for input
                      piped to mysql or loaded using the 'source' command).
                      This is necessary when processing output from mysqlbinlog
                      that may contain blobs.
  --connect-expired-password 
                      Notify the server that this client is prepared to handle
                      expired password sandbox mode.

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf 
The following groups are read: mysql client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file,
                        except for login file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#
                        Also read groups with concat(group, suffix)
--login-path=#          Read this path from the login file.

Variables (--variable-name=value)
and boolean options {FALSE|TRUE}  Value (after reading options)
--------------------------------- ----------------------------------------
auto-rehash                       TRUE
auto-vertical-output              FALSE
bind-address                      (No default value)
binary-as-hex                     FALSE
character-sets-dir                (No default value)
column-type-info                  FALSE
comments                          FALSE
compress                          FALSE
database                          (No default value)
default-character-set             auto
delimiter                         ;
enable-cleartext-plugin           FALSE
vertical                          FALSE
force                             FALSE
histignore                        (No default value)
named-commands                    FALSE
ignore-spaces                     FALSE
init-command                      (No default value)
local-infile                      FALSE
no-beep                           FALSE
host                              (No default value)
html                              FALSE
xml                               FALSE
line-numbers                      TRUE
unbuffered                        FALSE
column-names                      TRUE
sigint-ignore                     FALSE
port                              0
prompt                            mysql> 
quick                             FALSE
raw                               FALSE
reconnect                         TRUE
socket                            (No default value)
ssl                               TRUE
ssl-verify-server-cert            FALSE
ssl-ca                            (No default value)
ssl-capath                        (No default value)
ssl-cert                          (No default value)
ssl-cipher                        (No default value)
ssl-key                           (No default value)
ssl-crl                           (No default value)
ssl-crlpath                       (No default value)
tls-version                       (No default value)
table                             FALSE
user                              (No default value)
safe-updates                      FALSE
i-am-a-dummy                      FALSE
connect-timeout                   0
max-allowed-packet                16777216
net-buffer-length                 16384
select-limit                      1000
max-join-size                     1000000
secure-auth                       TRUE
show-warnings                     FALSE
plugin-dir                        (No default value)
default-auth                      (No default value)
binary-mode                       FALSE
connect-expired-password          FALSE
[root@michael ~]# 

猜你喜欢

转载自blog.csdn.net/Michael_lcf/article/details/105003501