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 ~]#