MYSQL汇总

时间:2023-03-10 05:43:48
MYSQL汇总

一.1.1 MYSQL

一.1.1.1 基础特性

1)性能卓越,服务稳定,很少出现异常宕机;

2)开放源代码且无版权制约,自主性强,使用成本低;

3)历史悠久,社区及用户非常活跃,遇到问题,可快速获得帮助;

4)软件体积小,安装使用简单,易于维护,安装及维护成本低;

5)支持多种操作系统,提供多种API接口,支持多种开发语言,对PHP语言语言无缝支持;

6)品牌口碑效应。

一.1.1.2 基础说明

注:数据库重新初始化要切记先删除data对应目录的数据。

企业环境创建数据库:

a.根据开发的程序确定字符集(建议UTF8);

b.编译时指定字符集,例如:

-DDEFAULT_CHATSET=utf8 \

-DDEFAULT_CHLLATION=utf8_general_ci \

c.当需要的字符集不同于默认字符集时,指定字符集创建数据库即可。

企业环境数据库授权状态:

a.博客、CMS等产品的数据库授权:

对于web连接用户尽量采用最小化原则,较多开源软件都是web界面安装,需要SELECT、INSERT、UPDATE、DELETE和CREATE、DROP(较危险)权限;

> grant select,insert,update,delete,create,drop on blog.* to ‘blog’@’10.0.0.%’ identified by ‘000000’;

b.生成数据库表后,要收回CREATE、DROP权限;

> REVOKE CREATE on blog.* FROM ‘blog’@’10.0.0.%’;

> REVOKE DROP on blog.* FROM ‘blog’@’10.0.0.%’;

c.生产环境针对主库(写为主读为辅)用户的授权;

主库

> GRANT SELECT,INSERT,UPDATE,DELETE ON ‘blog’.* TO ‘blog’@’10.0.0.%’ identified by ‘000000’;

从库

> GRANT SELECT ON ‘blog’.* TO ‘blog’@’10.0.0.%’ identified by ‘000000’;

mysql记录UUID的文件

[root@M-mysql /r2/mysqldata]# cat auto.cnf

[auto]

server-uuid=fda28692-9e31-11e7-bf34-000c2907c998

数据库操作记录文件

/root/.mysql_history

mysql参数说明

-V  --version  查看版本;-e  实现非交换式对话;-U 当发出没有WHERE或LIMIT关键字的UPDATE或DELETE时,mysql程序将拒绝执行;

防止数据库误操作

# echo “alias mysql=’mysql -U’” >>/etc/profile

# source /etc/profile

不重启数据库调整参数

> set global key_buffer_size=10*1024*1024;

# 此操作为全局参数设置,设置完立即生效,重启MySQL后失效,所以若想不重启修改数据库参数并永久生效,可用此操作设置完后再修改对应的配置文件里参数。

登陆数据库后执行系统命令

> system ls -la  /tmp

ALL PRIVILEGES包括如下权限

SELECT, INSERT,UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE

一.1.1.3 配置说明

公司集群环境配置文件

 # Example MySQL config file for very large systems.
#
# This is for a large system with memory of 1G-2G where the system runs mainly
# MySQL.
#
# MySQL programs look for option files in a set of
# locations which depend on the deployment platform.
# You can copy this option file to one of those
# locations. For information about these locations, see:
# http://dev.mysql.com/doc/mysql/en/option-files.html
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option. # The following options will be passed to all MySQL clients
[client]
# password = yourpassword
port =
socket = /usr/local/mysql/data/mysql.sock
# default-character-set=utf8 # Here follows entries for some specific programs # The MySQL server
[mysqld]
# password = yourpassword
server-id = # 主机标示,整数
read-only = # 主机,读写都可以
#binlog-do-db =mysql # 需要备份数据,多个写多行
#replicate-wild-ignor2-table=mysql.%
#binlog-ignore-db =mysql # 不需要备份的数据库,多个写多行
port =
socket = /usr/local/mysql/data/mysql.sock
max_connections=
max_connect_errors=
#init-connect='SET NAMES utf8;insert into accesslog.accesslog values(null,connection_id(),now(),substring(user(),1,locate('@',user())-1),substring(user(),locate('@',user())+1,length(user())));'
init-connect='SET NAMES utf8'
interactive_timeout=
#default-character-set=utf8
datadir=/r2/mysqldata
basedir=/usr/local/mysql
log-error=/r2/mysqldata/mysql-error.log
pid-file=/r2/mysqldata/mysql.pid
#bind-address=127.0.0.1
user=mysql
#skip-locking
key_buffer_size = 384M
max_allowed_packet = 64M
table_open_cache =
sort_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 8M
myisam_sort_buffer_size = 64M
thread_cache_size =
query_cache_size = 32M
# Try number of CPU's*2 for thread_concurrency
#thread_concurrency = log-slave-updates #这个参数一定要加上,否则不会给更新的记录些到二进制文件里
#slave-skip-errors #是跳过错误,继续执行复制操作 expire_logs_days = # Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
#
#skip-networking # Replication Master Server (default)
# binary logging is required for replication
log-bin=mysql-bin # required unique id between and ^ -
# defaults to if master-host is not set
# but will not function as a master if omitted # Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# ) Use the CHANGE MASTER TO command (fully described in our manual) -
# the syntax is:
#
# CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
# MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
# where you replace <host>, <user>, <password> by quoted strings and
# <port> by the master's port number (3306 by default).
#
# Example:
#
# CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=,
# MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# ) Set the variables below. However, in case you choose this method, then
# start replication for the first time (even unsuccessfully, for example
# if you mistyped the password in master-password and the slave fails to
# connect), the slave will create a master.info file, and any later
# change in this file to the variables' values below will be ignored and
# overridden by the content of the master.info file, unless you shutdown
# the slave server, delete master.info and restart the slaver server.
# For that reason, you may want to leave the lines below untouched
# (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between and ^ -
# (and different from the master)
# defaults to if master-host is set
# but will not function as a slave if omitted
#server-id =
#
# The replication master for this slave - required
#master-host = <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user = <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password = <password>
#
# The port the master is listening on.
# optional - defaults to
#master-port = <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin
#
# binary logging format - mixed recommended
binlog_format=mixed # Uncomment the following if you are using InnoDB tables
#innodb_data_home_dir = /var/lib/mysql
#innodb_data_file_path = ibdata1:2000M;ibdata2:10M:autoextend
#innodb_log_group_home_dir = /var/lib/mysql
# You can set .._buffer_pool_size up to - %
# of RAM but beware of setting memory usage too high
innodb_buffer_pool_size = 30720M
sync_binlog=
query_cache_type= ON
query_cache_size= 128M
gtid_mode=ON
enforce_gtid_consistency=ON
slave_parallel_type=LOGICAL_CLOCK
slave_parallel_workers=
master_info_repository=TABLE
relay_log_info_repository=TABLE
relay_log_recovery=ON
#innodb_additional_mem_pool_size = 20M
# Set .._log_file_size to % of buffer pool size
innodb_log_file_size = 256M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit =
#innodb_lock_wait_timeout =
sql_mode=""
[mysqldump]
quick
max_allowed_packet = 16M [mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates [myisamchk]
key_buffer_size = 256M
sort_buffer_size = 256M
read_buffer = 2M
write_buffer = 2M [mysqlhotcopy]
interactive-timeout

my.cnf

DBA整改后的配置文件

 # line V1.
# mail: zhenggc@ipanel.cn & lincm@ipanel.cn
# data: --
# file_name: ipanel-my.cnf
# function: my.cnf ## optimized mysql configure file my.cnf
## 注意:建议参数可需要根据实际情况作调整
## 本配置文件主要适用于MySQL 5.7.18版本 # ********* 以下重要参数必须核对 *********
# .innodb_flush_log_at_trx_commit=
# .sync_binlog =
# .innodb_strict_mode = OFF
# .innodb_flush_method = O_DIRECT
# .lower_case_table_names =
# .character-set-server = utf8
# .sql_mode 配置为空值
# .server-id = 修改成对应数值
# .innodb_buffer_pool_size = 32G 纯mysql server 配置50%和 混合内存配置不低于10G~%
#.key_buffer_cache=1G 如果有myisam表请配置为1G
#.innodb_data_file_path = ibdata1:1G:autoextend 确认innodb_data_file_path配置是否跟原来一样
#.log_bin = /r2/mysqldata/binlog 旧版本或者之前已配置好如:/r2/mysqldata/slave-bin,请维持原样
# ********************************************
[client]
port =
socket = /r2/mysqldata/mysql.sock
#=======================================================================
# # MySQL客户端配置
#=======================================================================
[mysql]
prompt="\u@ipanel \R:\m:\s [\d]> "
no-auto-rehash
#=======================================================================
# MySQL服务器全局配置
#=======================================================================
[mysqld]
user = mysql
port =
server-id =
tmpdir = /r2/mysqldata
datadir = /r2/mysqldata
socket = /r2/mysqldata/mysql.sock
wait_timeout =
#interactive_timeout =
sql_mode =
#sql_mode 配置为空值
skip_name_resolve =
lower_case_table_names =
character-set-server = utf8
#auto_increment_increment =
#auto_increment_offset =
# init_connect =
######################### 性能参数 ####################
open_files_limit =
max_connections =
max_user_connections=
max_connect_errors =
table_open_cache =
max_allowed_packet = 128M
thread_cache_size =
max_heap_table_size = 32M
query_cache_type =
###global cache ###
key_buffer_size = 512M
query_cache_size =
###session cache ###
sort_buffer_size = 8M #排序缓冲
join_buffer_size = 4M #表连接缓冲
read_buffer_size = 8M #顺序读缓冲
read_rnd_buffer_size = 8M #随机读缓冲
tmp_table_size = 32M #内存临时表
binlog_cache_size = 4M #二进制日志缓冲
thread_stack = 256KB #线程的堆栈的大小
######################### binlog设置 #####################
binlog_format = MIXED
log_bin = /r2/mysqldata/binlog
max_binlog_cache_size = 1G
max_binlog_size = 1G
expire_logs_days =
sync_binlog = #重要参数必须修改为0
######################### 复制设置 ########################
log_slave_updates=
#replicate-do-db=User
#binlog-ignore-db = test
#slave-skip-errors=,,
### GTID 配置 ###
gtid_mode=ON
enforce-gtid-consistency=true
######################### innodb ##########################
default_storage_engine = InnoDB
#innodb_data_file_path = ibdata1:1G:autoextend
innodb_buffer_pool_size = 32G #系统内存50%
innodb_open_files =
innodb_flush_log_at_trx_commit = #线上服务器必须配置为2
innodb_file_per_table =
innodb_lock_wait_timeout =
# 根据您的服务器IOPS能力适当调整innodb_io_capacity
# 一般配普通SSD盘的话,可以调整到 -
innodb_io_capacity =
innodb_io_capacity_max =
innodb_flush_method = O_DIRECT
innodb_log_file_size = 2G
innodb_log_files_in_group =
innodb_large_prefix =
innodb_thread_concurrency =
innodb_strict_mode = OFF
innodb_sort_buffer_size =
######################### log 设置 #####################
log_error = /r2/mysqldata/error.log
slow_query_log =
long_query_time =
slow_query_log_file = /r2/mysqldata/slow.log
#=======================================================================
# MySQL mysqldump配置
#=======================================================================
[mysqldump]
quick
max_allowed_packet = 32M
#=======================================================================
# MySQL mysqld_safe配置
#=======================================================================
[mysqld_safe]
log_error = /r2/mysqldata/error.log
pid_file = /r2/mysqldata/mysqldb.pid

my.cnf

自用快速启停配置文件

 [client]
port =
socket = /usr/local/mysql/data/mysql.sock
[mysqld]
server-id = # 主机标示,整数
read-only = # 主机,读写都可以
port =
socket = /usr/local/mysql/data/mysql.sock
max_connections=
max_connect_errors=
init-connect='SET NAMES utf8'
interactive_timeout=
datadir=/r2/mysqldata
basedir=/usr/local/mysql
log-error=/r2/mysqldata/mysql-error.log
pid-file=/r2/mysqldata/mysql.pid
user=mysql
#key_buffer_size = 384M
#max_allowed_packet = 64M
table_open_cache =
sort_buffer_size = 2M
read_buffer_size = 2M
#read_rnd_buffer_size = 8M
#myisam_sort_buffer_size = 64M
thread_cache_size =
#query_cache_size = 32M
log-slave-updates #这个参数一定要加上,否则不会给更新的记录些到二进制文件里
expire_logs_days =
log-bin=mysql-bin
binlog_format=mixed
#innodb_buffer_pool_size = 30720M
sync_binlog=
query_cache_type= ON
#query_cache_size= 128M
gtid_mode=ON
enforce_gtid_consistency=ON
slave_parallel_type=LOGICAL_CLOCK
slave_parallel_workers=
master_info_repository=TABLE
relay_log_info_repository=TABLE
relay_log_recovery=ON
#innodb_log_file_size = 256M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit =
sql_mode=""
[mysqldump]
quick
#max_allowed_packet = 16M
[mysql]
no-auto-rehash
[myisamchk]
#key_buffer_size = 256M
#sort_buffer_size = 256M
#read_buffer = 2M
#write_buffer = 2M
[mysqlhotcopy]
interactive-timeout

my.cnf

一.1.1.4 SQL语言

一.1.1.4.1 SQL基础

介绍

全称为结构化查询语言(Structured Query Language),是一种对关系数据库中数据进行定义和操作的语言方法,用于存取数据以及查询、更新和管理关系数据库系统,同时也是数据库脚本文件的扩展名,是大多数关系数据库管理系统所支持的工业标准。

分类

数据查询语言(DQL)

DQL(Data Query Language),也称为数据检索语言,作用是从表中获取数据,确定数据怎样在应用程序给出,使用动词有SELECT,保留字有WHERE、ORDER BY、GROUP BY、HAVING;

数据操作语言(DML)    #常见

DML(Data Manipulation Language),也称为动作查询语言,使用动词有INSERT、UPDATE、DELETE,分别用于添加、修改、删除表数据等操作;

事物处理语言(TPL)

其语句能确保被DML语句影响的表的所有行及时得以更新,TPL语句包括、BGEIN、TRANSACTION、COMMIT、ROLLBACK.

数据控制语言(DCL)    #常见

DCL(Data Control Language),其语句通过GRANT或REVOKE获得许可;

数据定义语言(DDL)    #常见

DDL(Data Definition Language),其语句包括动词CREATE和DROP,创表、删表,为表加入索引等;

指针控制语言(CCL)

CCL(Cursor Control Language),语句包括DECLARE CUROR、FETCH INTO、UPDATE WHERE CURRENT,用于对一个或多个表单独行的操作。

一.1.1.4.2 SQL命令

注:

a.进行部分命令操作后应刷新授权 > flush privileges;

b.部分命令用小写执行时会报错;

一.1.1.4.2.1 帮助语句

注:一步一步执行以下命令,可根据帮助命令提供的信息得出所需操作对应执行的命令。

> help;

> help show;

> help revoke;

> help show grants;

> help change master to;

一.1.1.4.2.2 查看语句

查看数据库

> show databases;

查看当前会话库状态

> show status;

查看全局状态

> show global status;

查看变量

> show variables;

匹配查看变量

> show variables like ‘key_buffer%’;

查看正在执行的完整SQL语句

> show full processlist;

匹配查看库

> show databases like '%zi%';

查看当前库

> select database();

查看字符编码

> show variables like '%character%';

查看当前版本

> select version();

查看当前用户

> select user();

查看当前时间

> select now();

查看数据库引擎

> show engines;

查看建库语句

> show create database kazihuo\G;

查看建表语句

> show create table kazihuo\G;

查看表

> show tables;

查看表结构

> desc mysql.user;

一.1.1.4.2.3 查询语句

查询用户信息

mysql> select user,host from mysql.user;

查询授权列表

> SELECT DISTINCT CONCAT('User: ''',user,'''@''',host,''';') AS query FROM mysql.user;

> select * from mysql.user where user='root' \G;

查看指定用户授权信息

mysql> SHOW GRANTS FOR 'root'@'localhost';

查询表数据

> select *from student;

指定字段查询

> select id,name from student;

条件查询

> select *from student limit 2;             #只查询2条记录

> select *from student where id=1;         #指定字段数据查询

> select *from student where id>2 and id <4;

> select *from student order by age asc;    #正序

> select *from student order by age desc;   #倒叙

多表查询

> select student.Sno,student.Sname,course.Cname,SC.Grade from student,course,SC where student.Sno=SC.Sno and course.Cno=SC.Cno;

查看sql语句执行计划

> explain select *from test where name=’kazihuo’\G;

一.1.1.4.2.4 使用语句

连接库

> use kazihuo;

一.1.1.4.2.5 创建语句

创建用户

> create user luomr@localhost identified by '000000';

创库

> create database kazihuo;

创建指定字符集数据库(默认为拉丁字符集)

> create database kazihuo_gbk DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci;

> create database kazihuo_utf8 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

创表

mysql> create table student(

-> id int(4) not null,

-> name char(20) not null,

-> age int(3) not null default '0',

-> dept varchar(16) default null

-> );

> create table worker(id int,name varchar(10),sex enum('man','woman'));

一.1.1.4.2.6 插入语句

指定字段插入数据

> insert into student(id,name) values(1,'kazihuo');

不指定字段将按照表格式依次插入数据

> insert into student values(2,'ka',23,'boy');

多条记录插入

mysql> insert into student values(3,'zi',3,'man'),(4,'huo',33,'superman');

一.1.1.4.2.7 修改语句

修改表

>update dns_domain_info set domain_info=replace(domain_info,"192.168.53.71","10.79.6.52");

> update dns_domain_info set domain_info='192.168.11.11' where domain_info='192.168.101.106';

指定字段信息修改表信息

> update student set name='tom' where id=2;

修改表名

> rename table teacher to teacher1;

> alter table teacher1 rename to teacher;

一.1.1.4.2.8 删除语句

删除库

> drop database kazihuo;

删除系统账号

> drop kazihuo ‘root’@’localhost’;

> delete from mysql.user where user=’kazihuo’ and host’localhost’; #drop删除无效时使用

删除指定字符串

#delete from homed_iusm.account_info where nickname like "%test%";

一.1.1.4.2.9 清空语句

清空表中所有内容

> truncate table teacher;

> delete from teacher;

# truncate更快,清空物理文件;delete为逻辑清除,按行删;

一.1.1.4.2.10 字段语句

添加字段

指定位置添加,默认为末尾

> alter table student add qq varchar(20) after id;

> alter table student add qq varchar(20) first;

添加多个字段

> alter table student add qq varchar(20),add grant int;

修改字段

ALTER TABLE 表名

MODIFY  字段名 数据类型 [完整性约束条件…];

ALTER TABLE 表名

CHANGE 旧字段名 新字段名 旧数据类型 [完整性约束条件…];

ALTER TABLE 表名

CHANGE 旧字段名 新字段名 新数据类型 [完整性约束条件…];

一.1.1.4.2.11 权限语句

用户授权

> GRANT ALL PRIVILEGES ON *.* TO 'root'@'luomr' IDENTIFIED BY '123456' WITH GRANT OPTION;

公司授权

> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;

> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '123456' WITH GRANT OPTION;

> GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' IDENTIFIED BY '123456' WITH GRANT OPTION;

#所有IP可通过root账号,passwd密码登陆

[root@slave1 src]# mysql -uroot -ppasswd -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'passwd' WITH GRANT OPTION"

[root@slave1 src]# mysql -uroot -ppasswd -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' IDENTIFIED BY 'passwd' WITH GRANT OPTION"

[root@slave1 src]# mysql -uroot -ppasswd -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@''localhost'' IDENTIFIED BY 'passwd' WITH GRANT OPTION"

局域网内主机授权

# 百分号匹配法

> GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.11.%' IDENTIFIED BY '123456' WITH GRANT OPTION;

# 子网掩码配置法

> GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.11.0/24' IDENTIFIED BY '123456' WITH GRANT OPTION;

一.1.1.4.2.12 密码操作

修改密码

# mysqladmin -uroot -p000000 password '111111'

> update mysql.user set authentication_string=password('newpass') where user='root' and host='localhost';

> set password = password('xxxxxxxx');

> flush privileges;

忘记密码

# /etc/init.d/mysqld stop

# /usr/local/mysql/bin/mysqld_safe --skip-grant-tables --user=mysql &

# 多实例跳过密码启动

#/usr/local/mysql/bin/mysqld_safe --skip-grant-tables --defaults-file=/data/3306/my.cnf &

进入mysql后用update方式设置密码

> flush privileges;

若重新登录mysql时仍不需要密码,则需重启mysql

一.1.1.5 数据迁移

一.1.1.6 数据备份

刷新binlog

# mysqldump -uroot -p000 flush-log

锁表

> flush table with read lock;

解锁

> unlock tables;

一.1.1.6.1 备份命令

生产场景常规备份

# mysqldump -uroot -p000 --set-gtid-purged=OFF --master-data=2 -A -B |gzip> /tmp/bak`date +%F-%T`.sql.gz

# mysqldump -uroot -p000 --all-databases --routines --events >/r2/baksql_`date +"%Y%m%d"`.sql

分引擎备份(专业DBA提供)

myisam

# mysqldump -uroot -p000 -A -E -R -F -x --flush-privileges --master-data=1 --hex-blob --set-gtid-purged=OFF >/tmp/`date +%F-%T`_all.sql

innodb(推荐使用)

# mysqldump -uroot -p000 -A -E -R -F --single-transaction --flush-privileges --master-data=1  --hex-blob --set-gtid-purged=OFF|gzip >/tmp/all_`date +%F-%T`.sql.gz

# mysqldump -uroot -p000 -A -E -R -F --single-transaction --flush-privileges --master-data=1  --hex-blob --set-gtid-purged=OFF >/tmp/all_`date +%Y%m%d`.sql

分库备份

# mysqldump -uroot -p000 --set-gtid-purged=OFF -B $db > "$bakpath"/bak_"$db"_`date +%F-%T`.sql

# 配合for语句实现分库备份

脚本备份

# mysql -uroot -p000 -e "show databases;"|grep -ivE "database|infor|performance|sys|mysql"|sed 's/^/mysqldump -uroot -p000 -B /g'

命令行执行命令实现分库备份并压缩

# mysql -uroot -p000 -e "show databases;"|grep -ivE "database|infor|performance|sys|mysql"|sed -r 's#^([a-zA-Z].*$)#mysqldump -uroot -p000 --set-gtid-purged=OFF -B \1|gzip >/tmp/\1.sql.gz#g'|bash

SQL精简(过滤注释)

# egrep -v "#|\*|--|^$" all.sql

-set-gtid-purged=OFF 说明

当执行mysqldump不加以上参数时发出警告

虽然能备份成功,但是在之后的数据恢复时报错

需注释报错行方可成功导入数据,而当加了以上参数时,将不会出现以上问题,同时数据也可正常导入。

MySQL5.6版本后,官方加入了全局事物ID(GTID)来强化数据库的主备一致性,故障恢复及容错能力;

官方解释:

A global transaction identifier (GTID) is a unique identifier created and associated with each transaction committed on the server of origin (master).

全局事务标识符(GTID)是一个惟一的标识符,它与在源服务器上提交的每个事务相关联(主)。

一.1.1.6.2 mysqldump

部分常用参数说明

-u     --user 
指定连接的用户名;

-p --password       
连接数据库密码

-h --host   
需要导出的主机信息

-P  --port
连接数据库端口号

-A --all-databases 
导出全部数据库;

-B --databases

表示接多个库,且增加use db、create db的信息(即恢复数据时不需指定库、表);

-S   --socket    
指定连接mysql的socket文件位置;

-x --lock-all-tables  
提交请求锁定所有数据库中的所有表,以保证数据的一致性。这是一个 全局读锁,并且自动关闭--single-transaction和--lock-tables选项;
   -Y --all-tablespaces 
导出全部表空间;

-F --flush-logs      
开始导出之前刷新日志;
若一次导出多个数据库(使用选项--databases或者--all-databases), 将会逐个数据库刷新日志。除使用 --lock-all-tables或者--master-data 外。在这种情况下,日志将会被刷新一次,相应的所有表同时被锁定。因此, 如果打算同时导出和刷新日志应该使用--lock-all-tables或者 --master-data和--flush-logs;

-d --no-data 
不导出任何数据,只导出数据库表结构;

-t --no-create-info

只备份数据;

-V --version      
输出mysqldump版本信息并退出;

-X --xml       
导出XML格式;

--default-character-set
设置默认字符集,默认值为utf8;
eg:mysqldump -uroot -p --all-databases --default-character-set=latin1

--compact
导出更少的输出信息(用于调试),去掉注释和头尾等结构;

--master-data

将binlog位置和文件名追加输入文件,如果为1,将会输出CHANGE MASTER命令;如果为2,输出的 CHANGE MASTER命令前添加注释信息;

--hex-blob

使用十六进制格式导出二进制字符串字段。如果有二进制数据就必须使 用该选项,影响到的字段类型有BINARY、VARBINARY、BLOB;

--flush-privileges

在导出mysql数据库之后,发出一条FLUSH PRIVILEGES语句。为了正确 恢复,用于导出mysql数据库和依赖mysql数据库数据的任何时候;

--triggers

导出触发器(默认启用,用--skip-triggers禁用);

-R --routines

导出存储过程以及自定义函数;

-E --events
导出事件;
  -y --no-tablespaces   
不导出任何表空间信息;

一.1.1.7 数据恢复

一.1.1.7.1 恢复操作

恢复方式

方法一:

mysql>use $db;

mysql>set names utf8;

mysql>source /tmp/bak.sql;

方法二:

#mysql -uroot -p000 $db < bak.sql

一.1.1.7.2 bin-log

基础说明

MySQL的binlog存在于数据库的数据目录下;

其作用是:

用来记录mysql内部增删改查等对mysql数据库有更新的内容的记录。

参数说明

-d

截取指定库的binlog;

解析binlog日志

[root@Q5 /r2/mysqldata]# mysqlbinlog mysql-bin.000003 > bin.sql

导出指定库的对应sql操作

# mysqlbinlog -d kazihuo mysql-bin.000010 >kazihuo.sql

一.1.1.7.3 增量恢复
一.1.1.7.3.1 基于位置点

指定开始位置和结束位置

# mysqlbinlog msql-bin.000020 --start-position=510 --stop-position=1312 -r pos.sql

# 输出初始位置510,结束位置1312的所有binlog日志到pos.sql;

注:结尾日志点将不被包含(即输出1312pos之前的binlog),位置信息点要实际存在。

-r 选项相当于重定向;

指定开始位置到文件结束

# mysqlbinlog msql-bin.000020 --start-position=510 -r pos510-end.sql

同时也可指定库名输出binlog

# mysqlbinlog msql-bin.000020 --start-position=510 -r pos510-end.sql -d kazihuo

从文件开头到指定结束位置

一.1.1.7.3.2 基于时间点

一.1.1.8 多实例化

注:多实例执行mysql命令时要指定sock文件。

一.1.1.8.1 配置方案

通过配置多个配置文件及多个启动程序实现多实例方案;

配置:

[root@Q1 /]# tree /data/

 /data/

 ├── 

 │   ├── data       #数据文件

 │   ├── my.cnf     #配置文件

 │   └── mysql      #启动文件

 └── 

     ├── data

     ├── my.cnf

     └── mysql

data

配置文件对比

一.1.1.8.2 安装部署

# groupadd mysql

# useradd -r -s /sbin/nologin g mysql mysql

# tar axvf mysql-5.7.18

# mv mysql-5.7.18 /usr/local/mysql

# chown -R mysql.mysql /data

# find /data/ -type f -name “mysql”|xargs ls -l

# find /data/ -type f -name “mysql”|xargs chmod +x

# cd /usr/local/mysql/bin

#./mysqld --initialize-insecure --user=mysql --basedir=/usr/local/mysql --datadir=/data/3306/data

#./mysqld --initialize-insecure --user=mysql --basedir=/usr/local/mysql --datadir=/data/3307/data

常用初始化命令

# ./mysqld --initialize-insecure --user=mysql --datadir=/r2/mysqldata --basedir=/usr/local/mysql

环境变量

方式一

# echo ‘export PATH=/usr/local/mysql/bin:$PATH ’ >> /etc/profile

# echo后必须为单引号

# source /etc/profile

方式二

把/usr/local/mysql/bin下面命令cp到全局系统命令路径/usr/local/sbin也可,或者做link

*************************************************************

a.初始化数据库原因:

初始化的目的是创建基础的数据库文件(生成mysql库表等);

初始化后对应实例数据目录下生成文件;

一.1.1.8.3 服务启停

:尽量不要野蛮的方式杀死数据库,生产高并发环境可能会引起数据丢失。

多实例启动文件的启动mysql:

# mysql_safe --defaults-file=/data/3306/my.cnf 2>&1 >/dev/null &

# mysql_safe --defaults-file=/data/3307/my.cnf 2>&1 >/dev/null &

多实例启动文件的停止mysql(平滑停止)

# mysqladmin -uroot -p000000 -S /data/3306/mysql.sock shutdown

# mysqladmin -uroot -p000000 -S /data/3307/mysql.sock shutdown

一.1.1.8.4 服务登陆

#mysql -uroot -p00000 -S/data/3306/mysql.sock

#mysql -uroot -p00000 -S/data/3307/mysql.sock

一.1.1.9 问题说明

一.1.1.9.1 登陆报错

问题描述

数据库正常启动,登陆时显示

[root@M-mysql ~]# mysql -uroot -p000000

-bash:mysql:未找到命令

解决方案

配置了mysql的环境变量未生效,执行# source /etc/profile

一.1.1.9.2 表操作报错

问题描述

登陆数据库打开表时报错:can’t create/write to file ‘tmp#sql_23e6_0MYI’

解决方案

# mkdir /var/lib/mysql/tmp

# chown mysql.mysql /var/lib/mysql/tmp

# vim /etc/my.cnf

tmp=/var/lib/mysql/tmp

# /etc/init.d/mysql restart

#查看指定目录大小:

# df -h /tmp

以上问题实操解决

一.1.1.9.3 关机卡死

问题描述

虚拟机部署了mysql5.7之后关机卡在如下页面:

解决方案

# swapon -s

# free -h

# df -h /dev/shm

# grep -i huge /proc/meminfo

查看swap使用超过50%

出现此问题可能是服务器内存不足导致,可增大内存或者修改my.cnf将参数要求值降低,可解决此问题。

一.1.1.9.4 删除binlog无法启动

问题描述

当磁盘空间不足,删除mysqldata下的binlog后导致数据库无法正常启动。

解决方案

清空binlog索引文件即可

[root@M-mysql /r2/mysqldata]# > mysql-bin.index

一.1.1.10 主从同步

一.1.1.10.1 主从复制原理

a.slave数据库上执行start slave,开启主从复制开关;

b.slave的I/O线程通过在master上的授权的复制用户权限请求连接master服务器,并请求从指定binlog日志文件的指定位置(日志文件名和位置就是在配置主从复制时执行change master命令时指定的)之后发送binlog日志内容;

c.master收到请求后,负责复制的I/O线程根据请求提供相应binlog给slave;

d.slave收到信息后,将binlog写入到自身中继日志(Relay Log)文件(MySQL-relay-bin.xxx)的最末端,并将新的binlog文件名和位置记录到master-info文件(便于下次读取master的binlog日志时能告诉master服务器需要从新binlog日志的哪个文件哪个位置开始请求新的binlog日志内容)。

e.slave通过SQL线程将log文件内容解析成SQL语句并执行,应用完毕后清理用过的日志;

说明

从服务器上生成的master.info是给I/O线程使用,relay-log.INFO给SQL线程使用。

一.1.1.10.2 实现主从同步

主库操作

建立从库复制的账号rep

> grant replication slave on *.* to 'rep'@'192.168.11.%' identified by 'master';

> show master status;

+------------------+----------+--------------+------------------+---------------------------------------------+

| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                           |

+------------------+----------+--------------+------------------+---------------------------------------------+

| mysql-bin.000021  |   791|     | fda28692-9e31-11e7-bf34-000c2907c998:1-1132 |

+------------------+----------+--------------+------------------+---------------------------------------------+

# mysqldump -uroot -pmaster -A -E -R -F --single-transaction --flush-privileges --master-data=1  --hex-blob --set-gtid-purged=OFF >/tmp/all_`date +%Y%m%d`.sql

将备份的sql同步到从库

说明:当主库备份时加了--master-data=1时,在生成的sql里面包含了对应的binlog信息及指定的position,所有在从库上执行CHANGE MASTER TO时可省略MASTER_LOG_FILE='mysql-bin.000021',MASTER_LOG_POS=791;

从库操作

CHANGE MASTER TO

MASTER_HOST='192.168.11.17',

MASTER_USER='rep',

MASTER_PASSWORD='master',

MASTER_PORT=3306,

MASTER_LOG_FILE='mysql-bin.000021',

MASTER_LOG_POS=791;

> start slave;

检验是否成功

> show slave status;

Slave_IO_Running: Yes

Slave_SQL_Running: Yes

Seconds_Behind_Master: 0

当显示以上信息,同时在master上对数据进行操作时,对应的slave数据库有着对应操作的结果体现。