MySQL 日常维护

其中第一至第六, 每天都需要执行, 第七到第九定期执行(1周或者2周一次?)

一  检查数据库运行状态

1 通过putty.exe登录远程数据库服务器,在shell命令行里面执行:

service mysql status

SUCCESS! MySQL running (1302)

则表示数据库正在运行之中

2 检查错误日志

进入/var/lib/mysql,查看错误日志,例如mysql.err。看近期mysql在运行中是否有错误异常发生。

tail -f /var/lib/mysql/mysql.err

比如发现类似错误:

090418 19:59:11 [ERROR] Got error 127 when reading table ‘./csf/ms_company’

对于127以及126的类似错误,可以采取如下解决措施:

(1)   进入mysql窗口执行: Mysql> repair csf.ms_company;

(2)   进入shell命令窗口: Shell> myisamchk /usr/local/mysql/var/csf/ms_company.MYI

【】在线修复的时候,要保证没有程序在访问要修复的表。

3 检查备份日志

检查前一天的备份的日志,看备份是否成功完成,或者备份过程中出

现什么错误提示。

4 检查数据库调度任务events事件

二  检查数据库服务器磁盘空间, 记录最近一天磁盘使用量

通过如下shell命令检查:

df -hvT

Filesystem          Type      Size  Used Avail Use% Mounted on
devtmpfs            devtmpfs  852M     0  852M   0% /dev
tmpfs               tmpfs     872M     0  872M   0% /dev/shm
tmpfs               tmpfs     872M  8.6M  863M   1% /run
tmpfs               tmpfs     872M     0  872M   0% /sys/fs/cgroup
/dev/mapper/ol-root xfs        14G  3.6G  9.9G  27% /
/dev/sda1           xfs      1014M  174M  841M  18% /boot
tmpfs               tmpfs     175M     0  175M   0% /run/user/0

得出目前已剩余磁盘空间,跟昨天的记录一对比,得出每天磁盘使用量为3G,如果磁盘可用空间小,就需要清理旧的binlog.

三  检查表

打开MySQL Administration工具,登录数据库服务器,检查每个库的表情况,

遇到有坏表的,直接Repair Table修复掉。

四  检查master服务器的master服务以及slave机的slave服务状态

查看master服务器状态:行正常的状态如下所示:

mysql -u root -p
 
show master status;

+------------------+----------+--------------+------------------+----------------------------------------------------------------------------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                                                                      |
+------------------+----------+--------------+------------------+----------------------------------------------------------------------------------------+
| mysql-bin.000023 |      231 |              |                  | 08a5acd3-6673-11e8-b993-000c29ee89cd:1-4,
1fdb51e5-6242-11e8-9e40-000c293b8095:1-29808 |
+------------------+----------+--------------+------------------+----------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

查看mysql用户线程状态:运行正常的状态如下所示:

show processlist;

+----+------+--------------------+------+------------------+------+-----------------------------------------------------------------------+------------------+
| Id | User | Host               | db   | Command          | Time | State                                                                 | Info             |
+----+------+--------------------+------+------------------+------+-----------------------------------------------------------------------+------------------+
|  1 | repl | mysqlstandby:21442 | NULL | Binlog Dump GTID | 6091 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL             |
|  2 | repl | mysql3:5330        | NULL | Binlog Dump GTID | 5981 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL             |
|  5 | root | monitor:30729      | NULL | Binlog Dump      | 3810 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL             |
|  8 | root | monitor:38586      | NULL | Sleep            |    0 |                                                                       | NULL             |
|  9 | root | localhost          | NULL | Query            |    0 | init                                                                  | show processlist |
+----+------+--------------------+------+------------------+------+-----------------------------------------------------------------------+------------------+
5 rows in set (0.00 sec)

查看slave服务器状态:运行正常的状态如下所示:

show slave status \G

*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.1.11
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000023
          Read_Master_Log_Pos: 231
               Relay_Log_File: mysqlstandby-relay-bin.000008
                Relay_Log_Pos: 361
        Relay_Master_Log_File: mysql-bin.000023
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 231
              Relay_Log_Space: 541
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
                  Master_UUID: 1fdb51e5-6242-11e8-9e40-000c293b8095
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set: 08a5acd3-6673-11e8-b993-000c29ee89cd:1-4,
1fdb51e5-6242-11e8-9e40-000c293b8095:1-29808
                Auto_Position: 1
1 row in set (0.00 sec)

五  检查Excel错误

详细见文档“excel_error_check.sql”。

六, MySQL用户账户管理

对用户严格管理,单用户只能赋予执行单个业务的权限,防止对数据的误操作。示范命令如下:

创建用户:

grant select,insert,update,delete on sbtest.* to 'test'@'192.168.1.10' identified by 'jdy62ZHA';

查看用户:

select * from mysql.user;

select * from mysql.db;

select * from mysql.tables_priv;

select * from mysql.columns_priv;

select * from mysql.procs_priv;

赋予权限

grant update on sbtest.* to 'test'@'192.168.1.10';

grant update(id) on sbtest.sbtest to 'test'@'192.168.1.10';

收回权限

revoke drop on *.* from 'test'@'192.168.1.10';

删除过期用户

drop user 'test'@'192.168.1.10';

七, 定期索引检查、索引优化

重点检查大表比如rpt_style1_0到rpt_style1_f等的索引。

八, 定期检查表结构以及数据

通过 Administration工具检查,将主机与从机的库结构以及数据进行

全方位的对比对比。比如说,表以及数据量的总记录,索引的记录数,触发器的记录数,存储函数存储过程的记录数等.

1 检查和修复MyISAM表的一个方式是使用CHECK TABLE和REPAIR TABLE语句。

2 优化MyISAM表,对于没有问题的表执行optimize table进行做碎片整理,回收空闲空间,例如:

optimize table sbtest.sbtest;

+---------------+----------+----------+-------------------------------------------------------------------+
| Table         | Op       | Msg_type | Msg_text                                                          |
+---------------+----------+----------+-------------------------------------------------------------------+
| sbtest.sbtest | optimize | note     | Table does not support optimize, doing recreate + analyze instead |
| sbtest.sbtest | optimize | status   | OK                                                                |
+---------------+----------+----------+-------------------------------------------------------------------+
2 rows in set (1 min 25.34 sec)

或者是,如果可以停一会mysqld服务器,进入数据库目录,当mysqld停止时候使用该命令:

service mysql stop

cd /var/lib/mysql

myisamchk -r -s -sort-index -o --myisam_sort_buffer_size=16M */*.MYI

myisamchk: error: 140 when opening MyISAM-table 'mysql/columns_priv.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/db.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/event.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/func.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/help_category.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/help_keyword.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/help_relation.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/help_topic.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/ndb_binlog_index.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/plugin.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/proc.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/procs_priv.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/proxies_priv.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/servers.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/tables_priv.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/time_zone_leap_second.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/time_zone.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/time_zone_name.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/time_zone_transition.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/time_zone_transition_type.MYI'
myisamchk: error: 140 when opening MyISAM-table 'mysql/user.MYI'

3 修复innodb表

mysql目前没有修复innodb 表的工具,只能用innodb_force_recovery=1,避免在导出数据时再crash。在my.cnf中设置好后重启库,再用 mysqldump或者select *把出问题的表导出来。然后重新导入(删除原表)。

九, 检查备份文件,将从机的备份数据恢复到测试库,检验备份数据是否正确。

具体操作参见文档“MySQL备份恢复初稿.docx”

MySQL运维之--日常维护操作

一、Linux内核和发行版本

uname -a

Linux mysql 4.1.12-94.3.9.el7uek.x86_64 #2 SMP Fri Jul 14 20:09:40 PDT 2017 x86_64 x86_64 x86_64 GNU/Linux

cat /etc/issue

\S
Kernel \r on an \m

二、glibc的版本
/lib/libc.so.6 ---没有man函数据的动态链接库

三、MySQL的版本
MySQL二进制分发版的文件名格式为:mysql-VERSION-OS.tar.gz
例如:Linux-Generic(glibc 2.5) (x86,64bit),Compressed TAR Archive(mysql-5.6.16-linux-glibc2.5-x86_64.tar.gz)

1、下载
https://dev.mysql.com/downloads/mysql/

2、查rpm包装在什么目录下

rpm -qpl MySQL-server-5.6.40-1.el7.x86_64.rpm |more

warning: MySQL-server-5.6.40-1.el7.x86_64.rpm: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
/etc/init.d/mysql
/etc/logrotate.d/mysql
/etc/my.cnf
/etc/my.cnf.d
/usr/bin/innochecksum
/usr/bin/my_print_defaults
/usr/bin/myisam_ftdump
/usr/bin/myisamchk
/usr/bin/myisamlog
/usr/bin/myisampack
/usr/bin/mysql_convert_table_format
/usr/bin/mysql_fix_extensions
/usr/bin/mysql_install_db
/usr/bin/mysql_plugin
/usr/bin/mysql_secure_installation
/usr/bin/mysql_setpermission
/usr/bin/mysql_tzinfo_to_sql
/usr/bin/mysql_upgrade
/usr/bin/mysql_zap
/usr/bin/mysqlbug
/usr/bin/mysqld_multi
/usr/bin/mysqld_safe
/usr/bin/mysqldumpslow
/usr/bin/mysqlhotcopy
/usr/bin/mysqltest
/usr/bin/perror
/usr/bin/replace
/usr/bin/resolve_stack_dump
/usr/bin/resolveip
/usr/lib64/mysql/plugin/adt_null.so
/usr/lib64/mysql/plugin/auth.so
/usr/lib64/mysql/plugin/auth_socket.so
/usr/lib64/mysql/plugin/auth_test_plugin.so
/usr/lib64/mysql/plugin/connection_control.so
/usr/lib64/mysql/plugin/daemon_example.ini
/usr/lib64/mysql/plugin/debug/adt_null.so
/usr/lib64/mysql/plugin/debug/auth.so
/usr/lib64/mysql/plugin/debug/auth_socket.so
/usr/lib64/mysql/plugin/debug/auth_test_plugin.so
/usr/lib64/mysql/plugin/debug/connection_control.so
/usr/lib64/mysql/plugin/debug/innodb_engine.so

rpm -qpl MySQL-client-5.6.40-1.el7.x86_64.rpm |more

warning: MySQL-client-5.6.40-1.el7.x86_64.rpm: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
/usr/bin/msql2mysql
/usr/bin/mysql
/usr/bin/mysql_config_editor
/usr/bin/mysql_find_rows
/usr/bin/mysql_waitpid
/usr/bin/mysqlaccess
/usr/bin/mysqlaccess.conf
/usr/bin/mysqladmin
/usr/bin/mysqlbinlog
/usr/bin/mysqlcheck
/usr/bin/mysqldump
/usr/bin/mysqlimport
/usr/bin/mysqlshow
/usr/bin/mysqlslap
/usr/share/doc/MySQL-client-5.6.40
/usr/share/doc/MySQL-client-5.6.40/COPYING
/usr/share/doc/MySQL-client-5.6.40/README
/usr/share/man/man1/msql2mysql.1.gz
/usr/share/man/man1/mysql.1.gz
/usr/share/man/man1/mysql_config_editor.1.gz
/usr/share/man/man1/mysql_find_rows.1.gz
/usr/share/man/man1/mysql_waitpid.1.gz
/usr/share/man/man1/mysqlaccess.1.gz
/usr/share/man/man1/mysqladmin.1.gz
/usr/share/man/man1/mysqlbinlog.1.gz
/usr/share/man/man1/mysqlcheck.1.gz
/usr/share/man/man1/mysqldump.1.gz
/usr/share/man/man1/mysqlimport.1.gz
/usr/share/man/man1/mysqlshow.1.gz
/usr/share/man/man1/mysqlslap.1.gz

3、更改rpm安装路径

rpm --help

rpm --prefix --relocate

rpmbuild spec binary rpm

yum install

四、rpm安装

rpm -ivh xxx.rpm

rpm -pql xxx.rpm

MySQL 实例安装和启动

1. 安装

mysql_install_db --defaults-file=/root/data/mysql3306/my.cnf --basedir=/usr/ --datadir=/root/data/mysql3306/data

2. 启动

mysqld_safe --defaults-file=/root/data/mysql3306/my.cnf &

3. 登录

mysql -h 127.0.0.1 -u root -P 3306 -p

五、安装演示:

1.关闭mysql

ps -ef|grep mysqld

kill 3397 3801

2.安装

cat init3306.sh

sh init3306.sh

3.启动

cat start3306.sh

sh start3306.sh

注意:mysql_install_db(通过安装rpm包产生mysql_install_db),有如下命令查看:

rpm -pql MySQL-server-5.6.40-1.el7.x86_64.rpm |grep install

warning: MySQL-server-5.6.40-1.el7.x86_64.rpm: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
/usr/bin/mysql_install_db
/usr/bin/mysql_secure_installation
/usr/share/man/man1/mysql_install_db.1.gz
/usr/share/man/man1/mysql_secure_installation.1.gz

which mysql_install_db

/usr/bin/mysql_install_db

4.看日志

tail -100f /var/lib/mysql/mysql.err

发生数据字典不存在,就会自动创建。。。。

5.查看进程

ps -ef|grep mysqld

root      1948     1  0 19:17 pts/0    00:00:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/lib/mysql/mysql.pid
mysql     2129  1948  0 19:17 pts/0    00:00:01 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --user=mysql --log-error=mysql.err --pid-file=/var/lib/mysql/mysql.pid
root      2328  1539  0 22:12 pts/0    00:00:00 grep --color=auto mysqld

mysqld_safe是mysqld的父进程

6.登录

sh my3306.sh --mysql -h 127.0.0.1 -u root -P 3306

六、脚本:

1.---安装mysql:

vi init3306.sh

rm -rf /root/data/mysql3306/data/*
 rm -rf /root/log/mysql3306/iblog/*
 rm -rf /root/log/mysql3306/binlog/*
 chmod -R 777 /root/data/mysql3306/data/
 chmod -R 777 /root/log/mysql3306/iblog/
 chmod -R 777 /root/log/mysql3306/binlog/

chmod 755 /root/data/mysql3306/my.cnf

mysql_install_db --defaults-file=/root/data/mysql3306/my.cnf --basedir=/usr/ --datadir=/root/data/mysql3306/data

chmod -R 777 /root/data/mysql/3306/data/
 chmod -R 777 /root/log/mysql3306/iblog/
 chmod -R 777 /root/log/mysql3306/binlog/

2.--启动mysql:

vi start336.sh

mysqld_safe --defaults-file=/root/data/mysql3306/my.cnf &

3.--登录mysql:

vi my3306.sh

mysql -h127.0.0.1 -uroot -P3306 -p

------研究下

cd /root/data/mysql3306/data/mysql

cd /root/data/mysql3306/data/performance_schema --性能相关的

cd /root/data/mysql3306/data/test ---测试库

cd /root/log/mysql3306/iblog/ ---innodb自己的数据和日志

------了解my.cnf(多实例用端口来取分)

vi /root/data/mysql3306/my.cnf

[client]
 port=3306
 socket=/root/data/mysql3306/run/mysql.sock

[mysql]
 port=3306
 promprt=\\u@\\d \\r:\\m:\\s>

[mysqld]
 default-storage-engine=INNODB
 character-set-server=iatin1
 explicit_defaults_for_timestamp=true

#dir
 innodb_log_group_home_dir=/root/log/mysql3306/iblog
 innodb_data_home_dir=/root/log/mysql3306/iblog
 basedir=/usr
 datadir=/root/data/mysql3306/data
 tmpdir=/root/data/mysql3306/tmp
 slave_load_tmpdir=/root/data/mysql3306/tmp
 log-error=/root/data/mysql3306/log/alert.log
 slow_query_log_file=/root/data/mysql3306/log/slow.log
 relay_log_info_file=/root/log/mysql3306/binlog/relay-log.info
 master-info-file=/root/log/mysql3306/binlog/master.info
 socket=/root/data/mysql3306/run/mysql.sock
 log-bin=/root/log/mysql3306/binlog/binlog
 relay-log=/root/log/mysql3306/binlog/relaylog

innodb_force_recovery=0

七、操作mysql

1、登录mysql:

本地:
mysql -u root -p

远程:
mysql -u root -p -h 192.168.1.12

多实例:
mysql -u root -p -P 3306

2、用户操用

(1)创建用户

create user 'test2'@'192.168.1.10' identified by 'test2';

(2)用户授权

单纯的授权

grant all privileges on *.* to 'test2'@'localhost';

grant insert,update,delete,select on *.* to 'test2'@'localhost';

授权并创建用户

--创建用户并刷缓存

grant all privileges on *.* to 'test2'@'localhost' identified by 'test2';

--对象权限

grant all privileges on *.* to 'test2'@'localhost';

--系统权限 (super相当于oracle中的dba权限)

grant super on *.* to 'test2'@'localhost';

3、实操

--查看所有的数据库
show databases;

--切到mysql数据库
use mysql;

----查mysql的所有用户,这个是由mysql_install_db创建的
select user,host,password from mysql.user;

--all代表(select update,delete,alter admin,super_acl),第一个*代表所有数据库,第二个*代表所有对象,%代表所有的客户端都可以访问。
grant all privileges on *.* to 'test2'@'%';

----用grant创建的用户登录mysql
mysql -h 127.0.0.1 -u test2 -p

---当前是什么用户
select user();

---创建数据库(mysql中的数据库类似于oracle中的schema
create database test2;

---创建表
create table test2(id int) engine=innodb;

---sbtest.test2表的查询授权给test2用户
grant select on sbtest.test2 to 'test2'@'%';

---把mysql.user表的用户权限重新刷到内存中
flush privileges;

show master status \G

---查看当前用户的连接,线程形式(类似oracle中的v$session)
show processlist;

4、drop table处理

(可以快速切回来rename table test3 to test2;)
rename table test2 to test3;

备份mysqldump:
mysqldump -h 127.0.0.1 -u root -p sbtest test > /home/sbtest.test.sql

drop table sbtest;

5、自增主键(最好是自己定义主键,系统默认的是全局的增量)
create table test (id int primary key auto_increment,name varchar(100)) engine=innodb;

show create table test \G

create index test_name_idx on test(name);

show create table test \G

insert into test(name) values('test');

select * from test;

6、alter table处理 --会动原来的数据,需要拷贝数据

alter table test add coll int;

7、执行计划

select * from test where id=1 \G

explain select * from test where id=1;

+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | test  | const | PRIMARY       | PRIMARY | 4       | const |    1 | NULL  |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
1 row in set (0.00 sec)

create index test_id_coll_idx on test(id,coll);

explain select * from test where id=1;

+----+-------------+-------+-------+--------------------------+---------+---------+-------+------+-------+
| id | select_type | table | type  | possible_keys            | key     | key_len | ref   | rows | Extra |
+----+-------------+-------+-------+--------------------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | test  | const | PRIMARY,test_id_coll_idx | PRIMARY | 4       | const |    1 | NULL  |
+----+-------------+-------+-------+--------------------------+---------+---------+-------+------+-------+
1 row in set (0.00 sec)

create index test_col_name on test(coll,name);

explain select * from test where coll>10 and name='xx';

+----+-------------+-------+------+-----------------------------+---------------+---------+-------+------+------------------------------------+
| id | select_type | table | type | possible_keys               | key           | key_len | ref   | rows | Extra                              |
+----+-------------+-------+------+-----------------------------+---------------+---------+-------+------+------------------------------------+
|  1 | SIMPLE      | test  | ref  | test_name_idx,test_col_name | test_name_idx | 303     | const |    1 | Using index condition; Using where |
+----+-------------+-------+------+-----------------------------+---------------+---------+-------+------+------------------------------------+
1 row in set (0.00 sec)

show create table test \G

alter table test drop index test_name_idx;

explain select * from test where coll>10 and name>'xx';

8、数据导出

(1)用dump导出数据

mysqldump -h 127.0.0.1 -u root -p sbtest test > /home/sbtest.test.sql

mysql -u root -p

drop table sbtest.test;

use sbtest;

--导入数据
source /home/sbtest.test.sql

(2)用select导出数据

select * from test into outfile '/home/select_export_sbtest.test.sql';
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

9、数据迁移

(1)停机方式

mysqldump/loadata

(2)不停机方式

物理上:搭备库(可以级联5.5-->5.6,向下兼容的)
 把主库read only,备库就能把主库转过来的binlog消化完,再把备库切为主

show global variables like '%read_only%';

+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| innodb_read_only | OFF   |
| read_only        | OFF   |
| tx_read_only     | OFF   |
+------------------+-------+
3 rows in set (0.00 sec)

set global read_only=on;

--插不进的,不能用root用户
insert into test(name) values('xx');

(3)不同平台小表:oracle--->mysql

脚本:synfull.pl

(4)不同平台的一个大表迁多:增量迁移

a.把数据的全量迁过去

b.把迁的过程中产生的日志传过去

c.apply增量

d.锁表切切换

(5)增量

a.Oracle:物化视图

b.MySQL:trigger

10、binlog

reset master; --会把当前的binlog清掉

show binlog events;

类似于:
mysqlbinlog -vvv /var/lib/mysql/mysql-bin.000024 > /home/mysql-bin.000024.txt

less /home/mysql-bin.000024.txt

WAL: write ahead log,日志优先写

11、归档

flush logs;

show master status;

write ahead log. recover backup, duriably. undo acid mvcc

12、参数和统计信息

----参数
show variables;

show variables like '%bin%';

----统计信息
show status;

show global status like '%insert%';

show variables like '%default%';

---不影响当前会话的操作,影响新建立的连接
set global default_storage_engine=myisam;

---影响当前会话的操作
set session default_storage_engine=myisam;

---连接池

show global variables like '%max_connect%';
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| max_connect_errors | 100   |
| max_connections    | 151   |
+--------------------+-------+
2 rows in set (0.00 sec)

show global variables like '%timeout%';
+------------------------------+----------+
| Variable_name                | Value    |
+------------------------------+----------+
| connect_timeout              | 10       |
| delayed_insert_timeout       | 300      |
| innodb_flush_log_at_timeout  | 1        |
| innodb_lock_wait_timeout     | 50       |
| innodb_rollback_on_timeout   | OFF      |
| interactive_timeout          | 28800    |
| lock_wait_timeout            | 31536000 |
| net_read_timeout             | 30       |
| net_write_timeout            | 60       |
| rpl_semi_sync_master_timeout | 10000    |
| rpl_stop_slave_timeout       | 31536000 |
| slave_net_timeout            | 3600     |
| wait_timeout                 | 28800    |
+------------------------------+----------+
13 rows in set (0.00 sec)

show global variables like '%disconnect%';
+--------------------------------+-------+
| Variable_name                  | Value |
+--------------------------------+-------+
| disconnect_on_expired_password | ON    |
+--------------------------------+-------+
1 row in set (0.00 sec)

MySQL数据库的日常使用及维护

一:使用MySQL数据库:

1、查看数据库结构:

查看当前服务器中有哪些库:

SHOW DATABASES 语句:用于列出当前MySQL服务器中包含的库;经过初始化后的MySQL服务器,默认建立了三个库:information_schema、mysql和performance_schema(其中mysql库中包含了用户认证相关的表)

show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+

查看当前使用的库中有哪些表:

SHOW TABLES 语句:用于列出当前所在的库中包含的表。操作之前,需要先使用USE语句切换到所使用的库:

use mysql;

show tables;

Mysql数据库的数据文件默认存放在/var/lib/mysql目录下,每个数据库对应一个子目录,用于存储数据表文件;

每一个数据表对应为三个文件,后缀名分别为”.frm”” .MYD ”” .MYI ”。

a.查看表的结构:

DESCRIBE 语句:用于显示表的结构,即组成表的各字段(列)的信息;

需要指定“库名.表名”作为参数;

若只指定表名参数,则需先通过“USE”语句切换到目标库。

创建及删除库和表:

b、创建新的库:

CREATE DATABASE 语句:用于创建一个新的库,需指定数据库名称作为参数。

Eg:创建一个名为welcome的库:

CREATE DATABASE welcome;

新建的空数据库在/var/lib/mysql目录下会自动生成一个与新建的库名相同的空文件夹。

c、创建新的表:

CREATE TABLE 语句:用于在当前库中创建新的表,需指定数据表名称作为参数,并定义该表格所使用的各字段。

格式: CREATE TABLE 表名(字段1名称类型,字段2名称类型,… ,PRIMARY kEY (主键名))

在welcome库中创建users表。其中,字段定义部分的DEFAULT用于设置默认的密码字串,PRIMARY用于设置主键字段名。

mysql> USE welcome;

mysql> CREATE TABLE users (user_name CHAR(16) NOT NULL, user_passwd CHAR(48) DEFAULT '', PRIMARY KEY (user_name));

删除一个数据表:

DROP TABLE 语句:用于删除库中的表,需要指定“库名.表名”作为参数;若只指定表名参数,则需先通过“USE”语句切换到目标库。

Eg:删除welcome库中的users表:

mysql> DROP TABLE welcome.users;

删除一个数据库:

DROP DATABASE 语句:用于删除指定的库,需要指定库名作为参数。

Eg:删除名为welcome的库:

mysql> DROP DATABASE welcome;

3、管理表中的数据记录:

插入数据记录:

INSERT INTO 语句:用于向表中插入新的数据记录。

格式: INSERT INTO 表名(字段1,字段2,…) VALUES(字段1的值,字段2的值,…)

向welcome库中的users表中插入一条记录:用户www,对应的密码为“123456”:

mysql> use welcome;

mysql> INSERT INTO users(user_name,user_passwd) VALUES('www',PASSWORD('123456'));

Eg:向welcome库中的users表中插入一条新的记录,用户qqq,对应密码“654321”。

mysql> use welcome;

mysql> INSERT INTO users VALUES('qqq',PASSWORD(654321));

查询数据记录:

SELECT 语句:用于从指定的表中查找符合条件的数据记录。

格式: SELECT 字段名1,字段名2,… FROM 表名 WHERE 条件表达式

表示所有字段可以使用通配符“*”,若要列出所有的数据记录则可以省略WHERE条件子句。

Eg:查看welcome库中的users表内的所有数据记录:

mysql> select * from welcome.users;

根据特定的条件查找记录,WHERE条件子句是必不可少的。

Eg:查找users表中用户名为qqq的记录,输出其用户名、密码字段的信息:

mysql> SELECT user_name,user_passwd from welcome.users where user_name='qqq';

修改数据记录:

UPDATE 语句:用于修改、更新表中的数据记录。

UPDATE 表名 SET 字段名1=字段值1[,字段名2=字段值2] WHERE 条件表达式

Eg:修改users表中用户名为www的记录,将密码字串设为空值,并验证:

mysql> UPDATE welcome.users SET user_passwd=PASSWORD('') WHERE user_name='www';

mysql> select * from welcome.users;

mysql数据库服务器中,用于访问数据库的各种用户信息都保存在mysql库的user表中。

删除数据记录:

DELETE 语句:用于删除表中指定的数据记录。

格式: DELETE FROM 表名 WHERE 条件表达式

Eg:删除users表名为www的数据记录,并验证:

mysql> DELETE FROM welcome.users WHERE user_name='www';

mysql> SELECT * FROM welcome.users;

在mysql数据库服务器中,默认添加了从本机访问数据库的空用户(user、password均为空)。基于数据库安全性考虑,应该删除这些空用户。

mysql> SELECT user,host,password FROM mysql.user WHERE user='';

mysql> DELETE FROM mysql.user WHERE user='';

推荐阅读:

Percona_Toolkit 简介及安装 -- MySQL管理员必备的工具包 http://www.linuxidc.com/Linux/2013-06/86631.htm

二:维护MySQL数据库:

1、数据库的用户授权:

Mysql数据库的root用户账号拥有对其所有库、表的全部权限,频繁使用root账号会给数据库服务器带来安全风险。所以实际工作中需要建立一些低权限的用户:

授予权限:

GRANT 语句:专门用来设置数据库用户的访问权限。当指定的用户名不存在时,GRANT语句将会创建新的用户,否则用于修改已有用户信息。

GRANT 权限列表 ON 库名.表名 TO 用户名@来源地址 [ IDENTIFIED BY ‘密码‘]

使用GRANT语句的注意事项:

权限列表:用于列出授权使用的各种数据库操作,以逗号分隔。All表示所有权限;

库名.表名:用于指定授权操作的库和表的名称,其中可以使用“*”。Eg:使用“welcome.*”表示授权操作的对象为welcome库中的所有表。

用户名@来源地址:用于指定用户名称和允许访问的客户机地址,即谁能连接、能从哪里连接。来源的地址可以是域名、IP地址,还可以使用“%”通配符,表示某个区域或网段内的所有地址。Eg:“%.benet.com”、“192.168.10.%”等

IDENTIFIED BY:设置用户连接数据库时所使用的密码字符串。在新建用户时,若省略则用户的密码将为空。

使用GRANT语句授权的用户记录,会保存到mysql库的user、db、host、tables_priv等。

Eg:添加一个名为zqq的数据库用户,并允许其从本机访问,对welcome库中的所有表具有查询权限,验证密码为“123456”。

mysql> GRANT select ON welcome.* TO 'zqq'@'localhost' IDENTIFIED BY '123456';

Eg:以用户zqq的身份连接到数据库,当执行授权的数据库操作时将被允许,而执行非授权的数据库操作时将被拒绝:

在企业服务器的应用中,数据库与网站服务器有时候是相互独立的。因此在mysql服务器中,应根据实际情况创建新的用户授权,允许授权用户从网站服务器访问数据库;

通常的做法是:创建一个或几个网站专用的库,并授权所有权限,限制访问的来源IP地址。

Eg:新建bash库,并授权从IP地址为192.168.10.1的主机连接,用户名为zqq,密码123456,允许在bash库中执行所有操作。

mysql> CREATE DATABASE bash;

mysql> GRANT all ON bash.* TO 'zqq'@'192.168.10.1' IDENTIFIED BY '123456';

查看权限:

SHOW GRANTS 语句:专门用来查看数据库用户的授权信息,通过FOR语句可指定查看的用户对象(必须与授权时使用的格式: SHOW GRANTS FOR 用户名@来源地址

Eg:查看用户zqq从主机192.168.10.1访问数据库时得授权信息。

mysql> SHOW GRANTS FOR 'zqq'@'192.168.10.1';

撤销权限:

REVOKE 语句:用于撤销指定用户的数据库权限,撤销权限后的用户仍然可以连接到mysql服务器,但将禁止执行对应的数据库操作:

格式:REVOKE 权限列表 ON 数据库名.表名 FROM 用户名@来源地址

Eg:撤销用户zqq从本机访问数据库bash的所有权限:

mysql> REVOKE all ON bash.* FROM 'zqq'@'localhost';

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

二、数据库的备份与恢复:

及时备份数据库是信息安全管理的重要内容之一,mysql数据库的备份采用直接打包数据库文件夹/var/lib/mysql或者使用专用的导出工具。

备份数据库:

通过mysqldump命令可以将指定的库、表或全部的库导出为SQL脚本,便于该命令在不同版本的MySQL服务器上使用。

A执行导出操作:

格式1:导出指定库中的部分表

Mysqldump [选项] 库名 [表名1][表名2] . .>/备份路径/备份文件名

格式2:导出一个或多个完整的库(包括其中所有的表)

Mysqldump [选项] --databases 库名1[库名2]… >/备份路径/备份文件名

格式3:备份mysql服务器中的所有的库

Mysqldump [选项] --all-databases >/备份路径/备份文件名

其中“ -u ”用来指定数据库的用户名;“ -p ”用来指定数据库的密码

Eg:将mysql库中的user表中导出为/home/mysql.user.sql文件,将整个mysql库导出为/home/mysql.sql文件,所有操作都以root用户的身份验证:

mysqldump -u root -p --set-gtid-purged=OFF mysql user > /home/mysql.user.sql

mysqldump -u root -p --set-gtid-purged=OFF --databases mysql > /home/mysql.sql

若要备份整个mysql服务器的所有库,应使用格式3,当导出的数据量较大时,可以添加‘--opt‘选项以优化执行速度。

Eg:创建备份文件/home/all-databases.sql,其中包括mysql服务器中的所有库:

mysqldump -u root -p --set-gtid-purged=OFF --opt --all-databases > /home/all-databases.sql

B查看备份文件内容:

Eg:过滤出/home/all-databases.sql脚本中的数据库操作语句:

grep -v "^--" /home/all-databases.sql |grep -v "^/" |grep -v "^$" |more

恢复数据库:

格式: mysql [选项] [库名] [表名] < /备份路径/备份文件名

当备份文件中只包含表的备份,而不包括创建库的语句时,则执行导入操作时必须指定库名,且目标库必须存在。

Eg:从备份文件中/home/mysql.user.sql中将表导入到mysql库:

mysql -u root -p mysql < /home/mysql.user.sql

若备份文件中已经包括完整的库信息,则执行导入操作时无需指定库名。

Eg:从备份文件/home/all-databases.sql恢复其中的所有库:

mysql -u root -p < /home/all-databases.sql

日常维护MySQL常用sql

1.慢sql情况查询:

可以使用以下三种方式查询,第一种是了解MySQL进程大概情况;第二种是按照影响时间倒序的,可以查询到目前最慢的一条sql;第三种是防止sql 的info消息过长而无法显示完整。

了解MySQL进程大概情况

show processlist;

+----+------+--------------------+------+------------------+--------+-----------------------------------------------------------------------+------------------+
| Id | User | Host               | db   | Command          | Time   | State                                                                 | Info             |
+----+------+--------------------+------+------------------+--------+-----------------------------------------------------------------------+------------------+
|  1 | repl | mysqlstandby:21541 | NULL | Binlog Dump GTID | 179745 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL             |
|  2 | repl | mysql3:5429        | NULL | Binlog Dump GTID | 179745 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL             |
| 31 | root | localhost          | NULL | Query            |      0 | init                                                                  | show processlist |
+----+------+--------------------+------+------------------+--------+-----------------------------------------------------------------------+------------------+
3 rows in set (0.00 sec)

按照影响时间倒序的,可以查询到目前最慢的一条sql

select * from information_schema.`PROCESSLIST` where info is not null order by time desc;

+----+------+-----------+------+---------+------+-----------+------------------------------------------------------------------------------------------+
| ID | USER | HOST      | DB   | COMMAND | TIME | STATE     | INFO                                                                                     |
+----+------+-----------+------+---------+------+-----------+------------------------------------------------------------------------------------------+
| 31 | root | localhost | NULL | Query   |    0 | executing | select * from information_schema.`PROCESSLIST` where info is not null order by time desc |
+----+------+-----------+------+---------+------+-----------+------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)

防止sql 的info消息过长而无法显示完整

show full processlist;

+----+------+--------------------+------+------------------+--------+-----------------------------------------------------------------------+-----------------------+
| Id | User | Host               | db   | Command          | Time   | State                                                                 | Info                  |
+----+------+--------------------+------+------------------+--------+-----------------------------------------------------------------------+-----------------------+
|  1 | repl | mysqlstandby:21541 | NULL | Binlog Dump GTID | 180737 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL                  |
|  2 | repl | mysql3:5429        | NULL | Binlog Dump GTID | 180737 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL                  |
| 31 | root | localhost          | NULL | Query            |      0 | init                                                                  | show full processlist |
+----+------+--------------------+------+------------------+--------+-----------------------------------------------------------------------+-----------------------+
3 rows in set (0.01 sec)

补充一下,若出现大量慢sql,在不影响业务的前提下,可以将一些select先kill掉,然后来缓冲一下MySQL的性能问题

select concat('kill ',id,' ;') from information_schema.`PROCESSLIST` where info like 'select%' and time>3 order by time desc;

2.连接数的查询:

可以使用以下sql查询到当前实例下所有库的连接数(由于该sql是根据同一个host来判断的,所以可能存在一个ip,不同端口有多个连接)

select db,count(1) from information_schema.`PROCESSLIST` group by db order by 2 desc;

+------+----------+
| db   | count(1) |
+------+----------+
| NULL |        3 |
+------+----------+
1 row in set (0.00 sec)

若想查询到完整的host

select db,host from information_schema.`PROCESSLIST`
    -> -- where db = dbname
    -> ;

+------+--------------------+
| db   | host               |
+------+--------------------+
| NULL | localhost          |
| NULL | mysqlstandby:21541 |
| NULL | mysql3:5429        |
+------+--------------------+
3 rows in set (0.00 sec)

查询有哪些host连接到当前实例,而不考虑host端口

select substring_index(host,':',1) ip,count(1) from information_schema.`PROCESSLIST` where db is null group by ip order by 2 desc;

+--------------+----------+
| ip           | count(1) |
+--------------+----------+
| localhost    |        1 |
| mysql3       |        1 |
| mysqlstandby |        1 |
+--------------+----------+
3 rows in set (0.00 sec)

3.磁盘空间的预估:

主要是根据数据量和索引量来对一个实例进行预估磁盘容量,以下sql统计出来的结果都是以MB为单位

查某个数据库的总容量(查数据库mysql的总容量)

select round(sum(data_length+index_length)/1024/1024,2) as total_db_mb from information_schema.tables where table_schema like 'mysql%';

+-------------+
| total_db_mb |
+-------------+
|        0.88 |
+-------------+
1 row in set (0.00 sec)

查磁盘告警的rds的表容量

select table_schema,table_name,table_rows,round((data_length+index_length)/1024/1024,2) as total_mb from information_schema.tables
    -> where -- table_schema in ('dbname') and
    -> table_schema not in ('mysql','information_schema','performance_schema','sys_info')
    -> -- and table_name in ('tbname1','tbname2')
    -> order by total_mb desc;

+--------------+------------+------------+----------+
| table_schema | table_name | table_rows | total_mb |
+--------------+------------+------------+----------+
| sbtest       | test       |          0 |     0.05 |
| xiaoboluo    | test       |          4 |     0.02 |
| sbtest       | test_log   |          0 |     0.02 |
+--------------+------------+------------+----------+
3 rows in set (0.00 sec)

mysql日常维护

1.mysql权限管理

1.1 mysql账户权限信息被存储在mysql数据库的user 、db、host、tables_priv、column_priv和procs_priv表中,mysql启动时服务器将这些数据库表内容读入内存。推荐grant和revoke语句

例如:

grant select,update on mysql.user to 'test'@'192.168.1.10' identified by 'jdy62ZHA';

flush privileges;

创建成功后查看mysql数据库表的变化

select * from mysql.user where user='test' \G

*************************** 1. row ***************************
                  Host: %
                  User: test
              Password:
           Select_priv: N
           Insert_priv: N
           Update_priv: N
           Delete_priv: N
           Create_priv: N
             Drop_priv: N
           Reload_priv: N
         Shutdown_priv: N
          Process_priv: N
             File_priv: N
            Grant_priv: N
       References_priv: N
            Index_priv: N
            Alter_priv: N
          Show_db_priv: N
            Super_priv: N
 Create_tmp_table_priv: N
      Lock_tables_priv: N
          Execute_priv: N
       Repl_slave_priv: N
      Repl_client_priv: N
      Create_view_priv: N
        Show_view_priv: N
   Create_routine_priv: N
    Alter_routine_priv: N
      Create_user_priv: N
            Event_priv: N
          Trigger_priv: N
Create_tablespace_priv: N
              ssl_type:
            ssl_cipher:
           x509_issuer:
          x509_subject:
         max_questions: 0
           max_updates: 0
       max_connections: 0
  max_user_connections: 0
                plugin: mysql_native_password
 authentication_string:
      password_expired: N
*************************** 2. row ***************************
                  Host: 192.168.1.10
                  User: test
              Password: *2FF960917BC9231714223F746ECBC728FCC24E59
           Select_priv: Y
           Insert_priv: Y
           Update_priv: Y
           Delete_priv: Y
           Create_priv: Y
             Drop_priv: Y
           Reload_priv: N
         Shutdown_priv: N
          Process_priv: N
             File_priv: N
            Grant_priv: N
       References_priv: N
            Index_priv: N
            Alter_priv: N
          Show_db_priv: N
            Super_priv: N
 Create_tmp_table_priv: N
      Lock_tables_priv: N
          Execute_priv: N
       Repl_slave_priv: N
      Repl_client_priv: N
      Create_view_priv: N
        Show_view_priv: N
   Create_routine_priv: N
    Alter_routine_priv: N
      Create_user_priv: N
            Event_priv: N
          Trigger_priv: N
Create_tablespace_priv: N
              ssl_type:
            ssl_cipher:
           x509_issuer:
          x509_subject:
         max_questions: 0
           max_updates: 0
       max_connections: 0
  max_user_connections: 0
                plugin: mysql_native_password
 authentication_string:
      password_expired: N

select * from mysql.db where user='test' \G

Empty set (0.01 sec)

select * from mysql.tables_priv where user='test' \G

*************************** 1. row ***************************
       Host: 192.168.1.10
         Db: mysql
       User: test
 Table_name: user
    Grantor: root@localhost
  Timestamp: 0000-00-00 00:00:00
 Table_priv: Select,Update
Column_priv:
1 row in set (0.00 sec)

mysql权限按照user 、db、tables_priv、column_priv检查顺序,如果对应表权限为Y,则不会检查后面的表

1.2.查看或修改账户权限

例如:

show grants for 'test'@'192.168.1.10' \G

*************************** 1. row ***************************
Grants for test@192.168.1.10: GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP ON *.* TO 'test'@'192.168.1.10' IDENTIFIED BY PASSWORD '*2FF960917BC9231714223F746ECBC728FCC24E59'
*************************** 2. row ***************************
Grants for test@192.168.1.10: GRANT SELECT, UPDATE ON `mysql`.`user` TO 'test'@'192.168.1.10'
2 rows in set (0.00 sec)

1.3 回收账户权限

revoke usage on *.* from 'test2'@'192.168.1.10';

drop user 'test2'@'192.168.1.10';

2.mysql日志管理

mysql服务支持的日志有二进制日志、错误日志、访问日志和满查询日志。

2.1 二进制日志(binlog)

记录所有DDL和DML操作,但不包括数据查询语句,通过mysqlbinlog查看 例如:

mysqlbinlog mysql-bin.000001 |cat -n |more

2.1.1 删除binlog,用purge binary logs 例如:

删除指定序号之前的二进制日志

mysql -u root -p

purge binary logs to 'mysql-bin.000005';

删除指定时间之前的二进制日志

mysql -u root -p

purge binary logs before '2018-07-04 18:57:00';

2.1.2 指定参数设置二进制文件保留天数“expire_logs_days=#”

自动清理14天之前的二进制日志文件

set global expire_logs_days=14;

vi /usr/my.cnf

expire_logs_days=14

2.2 操作错误日志

通过设置“--log_error=[file-name]” 指定错误日志存放位置,如没有设置,则错误日志默认位于mysql服务的datadir目录下

vi /usr/my.cnf

log_error='/var/lib/mysql/mysql.err'

2.3 访问日志

记录了所有关于客户端发起的链接,查询和更新语句,由于记录了所有的操作,在相对繁忙的系统中建议关闭

在配置文件“--log=[file-name]” 指定访问日志的位置,另外一种方法可以在登陆mysql实例后通过变量启用此日志,如

show global variables like '%general_log%';

+------------------+--------------------------+
| Variable_name    | Value                    |
+------------------+--------------------------+
| general_log      | OFF                      |
| general_log_file | /var/lib/mysql/mysql.log |
+------------------+--------------------------+
2 rows in set (0.00 sec)

set global general_log=on;

show global variables like '%general_log%';
+------------------+--------------------------+
| Variable_name    | Value                    |
+------------------+--------------------------+
| general_log      | ON                       |
| general_log_file | /var/lib/mysql/mysql.log |
+------------------+--------------------------+
2 rows in set (0.00 sec)

2.4 慢查询日志

记录了时间超过参数long_query_time(单位是秒)所设定值的SQL语句日志,对于审核和开发者发现性能问题及时优化有重要意义。

如需启用该日志可以在配置文件中设置 “slow_query_log" ,没有指定文件名,则默认hostname-slow.log作为文件名,并存放在数据目录中

show global variables like '%long_query_time%';

+-----------------+-----------+
| Variable_name   | Value     |
+-----------------+-----------+
| long_query_time | 10.000000 |
+-----------------+-----------+
1 row in set (0.00 sec)

show global variables like '%slow_query_log%';

+---------------------+-------------------------------+
| Variable_name       | Value                         |
+---------------------+-------------------------------+
| slow_query_log      | OFF                           |
| slow_query_log_file | /var/lib/mysql/mysql-slow.log |
+---------------------+-------------------------------+
2 rows in set (0.00 sec)

开启慢查询日志功能

set global slow_query_log=on;

show global variables like '%slow_query_log%';

+---------------------+-------------------------------+
| Variable_name       | Value                         |
+---------------------+-------------------------------+
| slow_query_log      | ON                            |
| slow_query_log_file | /var/lib/mysql/mysql-slow.log |
+---------------------+-------------------------------+
2 rows in set (0.01 sec)

vi /usr/my.cnf

slow_query_log=on

慢查询日志分析工具 mysqldumpslow

-s 排序类型

怎样排序这个输出。排序类型的这个值应该从以下清单中选择:

t, at: 按查询时间来排序 或者 按平均查询时间来排序

l, al: 按锁定时间来排序 或者 按平均锁定时间来排序

r, ar: 按返回记录数来排序 或者 按平均返回记录数来排序

c: Sort by count

默认情况下, mysqldumpslow按照平均查询时间来排序(等于-s at)。

[-s] 排序类型,可选al:平均锁定时间 ar:平均返回记录数 at:平均查询时间;

[-t] 只显示指定的行数;

mysqldumpslow -s at /var/lib/mysql/mysql-slow.log

3. mysql备份与恢复

3.1 备份方式可以通过直接备份数据文件或使用mysqldump命令将数据库数据导出到文本文件,直接备份数据库文件适用于MyISAM和InnoDB存储引擎,由于备份时数据库表正在读写,备份出的文件可能损坏无法使用,不推荐直接使用此方法。

导出数据库sbtest

mysqldump -u root -p --set-gtid-purged=OFF sbtest > /home/sbtest.sql

导出一个表mysql.user

mysqldump -u root -p --set-gtid-purged=OFF mysql user > /home/mysql.user.sql

只导出数据库表结构 -d没有数据 --add-drop-table 在每个create语句前增加一个drop table

mysqldump -u root -p --set-gtid-purged=OFF -d --add-drop-table sbtest > /home/sbtest.sql

恢复数据方法1

mysql -u root -p sbtest < /home/sbtest.sql

恢复数据方法2

mysql -u root -p

use sbtest;

source /home/sbtest.sql

3.2 另外一种可以实时备份的开源工具为xtrabackup

http://www.percona.com/downloads/提供下载

Xtrabackup是由 Percona 开发的一个开源软件,可实现对 InnoDB 的数据备份,支持在线热备份(备份时不影响数据读写)。备份时,Xtrabackup 会将 Master 的 binlog 信息记录在 xtrabackup_slave_info 文件中,通过此信息可以方便的搭建主从复制。

XtraBackup 有两个工具:xtrabackup 和 innobackupex:
xtrabackup 本身只能备份 InnoDB 和 XtraDB ,不能备份 MyISAM;
innobackupex 本身是 Hot Backup 脚本修改而来,同时可以备份 MyISAM 和 InnoDB,但是备份 MyISAM 需要加读锁。

官网:http://www.percona.com/software/percona-xtrabackup
文档:http://www.percona.com/doc/percona-xtrabackup/2.2/index.html

安装 XtraBackup(主从库都要操作)

vi /etc/resolv.conf

nameserver 192.168.1.1
nameserver 8.8.8.8

1、添加源

yum install https://www.percona.com/downloads/percona-release/redhat/0.1-4/percona-release-0.1-4.noarch.rpm

2、安装 xtrabackup

从这个位置E:\zachary\mysql\上传以下两个软件到服务器的/software目录

libev-4.15-3.el7.x86_64.rpm
Percona-XtraBackup-2.4.11-rb4e0db5-el7-x86_64-bundle.tar

cd /software

rpm -ivh libev-4.15-3.el7.x86_64.rpm

tar -xvf Percona-XtraBackup-2.4.11-rb4e0db5-el7-x86_64-bundle.tar

yum install rsync perl-DBD-MySQL perl-Digest-MD5

rpm -ivh percona-xtrabackup-24-2.4.11-1.el7.x86_64.rpm

创建备份

innobackupex --user=root --password=jge64NSU /home

如果执行正确,其输出信息通常类似:
180602 07:05:25 Executing UNLOCK TABLES
180602 07:05:25 All tables unlocked
180602 07:05:25 Backup created in directory '/home/2018-06-02_07-05-20/'
MySQL binlog position: filename 'master-bin.000009', position '120'
180602 07:05:25 [00] Writing /home/2018-06-02_07-05-20/backup-my.cnf
180602 07:05:25 [00]        ...done
180602 07:05:25 [00] Writing /home/2018-06-02_07-05-20/xtrabackup_info
180602 07:05:25 [00]        ...done
xtrabackup: Transaction log of lsn (1684441) to (1684441) was copied.
180602 07:05:25 completed OK!

备份时,innobackupex 会调用 xtrabackup 备份 InnoDB 表的数据,并且会复制 MyISAM, MERGE,CSV 和 ARCHIVE 表的表定义文件(.frm 文件)、数据文件。同时还会备份触发器和数据库配置信息相关的文件。这些文件将会保存在指定备份目录中一个以时间戳命名的目录下。

准备备份

一般情况下,在备份完成后,数据尚且不能用于恢复操作,因为备份的数据中可能会包含尚未提交的事务或已经提交但尚未同步至数据文件中的事务。因此,此时数据文件仍处理不一致状态。“准备”的主要作用正是通过回滚未提交的事务及同步已经提交的事务至数据文件也使得数据文件处于一致性状态。

innobackupex --apply-log /home/2018-06-02_07-05-20

如果执行正确,其最后输出的几行信息通常如下:
xtrabackup: starting shutdown with innodb_fast_shutdown = 1
InnoDB: page_cleaner: 1000ms intended loop took 8226ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
InnoDB: FTS optimize thread exiting.
InnoDB: Starting shutdown...
InnoDB: Shutdown completed; log sequence number 1685544
180602 07:15:20 completed OK!

在实现“准备”的过程中,innobackupex 通常还可以使用 --use-memory 选项来指定其可以使用的内存的大小,默认通常为 100M。如果有足够的内存可用,可以多划分一些内存给 prepare 的过程,以提高其完成速度。

恢复备份

将数据复制到从服务器上:
scp -r /home/2018-06-02_07-05-20 root@192.168.1.12:/home

在从服务器中恢复备份数据:(从库上操作)

service mysql stop

mv -f /var/lib/mysql /var/lib/`date +%Y_%m%d`_mysql_BACKUP

mkdir /var/lib/mysql

chown mysql:mysql /var/lib/mysql

innobackupex --datadir=/var/lib/mysql --copy-back /home/2018-06-02_07-05-20

如果服务器剩余空间不足,你可以使用 --move-back 替换掉 --copy-back。

如果执行正确,其输出信息的最后几行通常如下:
180602 08:22:12 [01] Copying ./performance_schema/session_account_connect_attrs.frm to /var/lib/mysql/performance_schema/session_account_connect_attrs.frm
180602 08:22:12 [01]        ...done
180602 08:22:12 [01] Copying ./xtrabackup_info to /var/lib/mysql/xtrabackup_info
180602 08:22:12 [01]        ...done
180602 08:22:12 [01] Copying ./xtrabackup_binlog_pos_innodb to /var/lib/mysql/xtrabackup_binlog_pos_innodb
180602 08:22:12 [01]        ...done
180602 08:22:12 [01] Copying ./xtrabackup_master_key_id to /var/lib/mysql/xtrabackup_master_key_id
180602 08:22:12 [01]        ...done
180602 08:22:12 [01] Copying ./ibtmp1 to /var/lib/mysql/ibtmp1
180602 08:22:12 [01]        ...done
180602 08:22:12 completed OK!

chown -R mysql:mysql /var/lib/mysql

chmod -R g+w /var/lib/mysql

chmod -R o+x /var/lib/mysql/mysql

chcon -R -t mysqld_db_t /var/lib/mysql

service mysql start

4.mysql复制

复制功能可以经济高效地提高应用程序的性能、扩展力和高可用性。既支持简单的主从拓扑,也可以 实现复杂、极具可伸缩性的链式集群。

使用mysql复制时,所有对复制表的更新必须在主服务器上进行,否则可能引起主服务器上的表进行的更新与对从服务器上的表所进行的更新产生冲突。

好处:(1)主从数据同步,主服务器故障时,从服务器可作为主服务器接管服务。

(2)负载均衡。实现读写分离,主服务器记录更新、删除、插入等操作;从服务器只查询请求;

(3)数据备份。从服务器可设置在异地,增加容灾的健壮性,为避免传输过慢,可设置参数slave_compressed_protocol 启用binlog压缩传输

show global variables like '%slave_compressed_protocol%';

+---------------------------+-------+
| Variable_name             | Value |
+---------------------------+-------+
| slave_compressed_protocol | OFF   |
+---------------------------+-------+
1 row in set (0.00 sec)

set global slave_compressed_protocol=on;

show global variables like '%slave_compressed_protocol%';

+---------------------------+-------+
| Variable_name             | Value |
+---------------------------+-------+
| slave_compressed_protocol | ON    |
+---------------------------+-------+
1 row in set (0.00 sec)

mysql使用3个线程来执行复制功能,1个在主服务器上,2个在从服务器上。当执行START SLAVE时,主服务器创建一线程负责发送二进制日志。从服务器创建一个I/O线程,负责读取主服务器上的二进制日志,然后将该数据保存到从服务器数据目录中的中继日志文件中。从服务器的SQL线程负责读取中继日志并重做日志中包含的更新,从而达到主从数据库数据的一致性。#在主从服务器上输入命令查询状态:mysql>show processlist \G 其中time列的值可以显示从服务器比主服务器滞后多长时间。

master操作:

show processlist;
+----+------+--------------------+------+------------------+--------+-----------------------------------------------------------------------+------------------+
| Id | User | Host               | db   | Command          | Time   | State                                                                 | Info             |
+----+------+--------------------+------+------------------+--------+-----------------------------------------------------------------------+------------------+
|  1 | repl | mysqlstandby:21541 | NULL | Binlog Dump GTID | 274390 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL             |
|  2 | repl | mysql3:5429        | NULL | Binlog Dump GTID | 274390 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL             |
| 33 | root | monitor:30742      | NULL | Binlog Dump      |  34083 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL             |
| 36 | root | monitor:38599      | NULL | Sleep            |      1 |                                                                       | NULL             |
| 51 | root | localhost          | NULL | Query            |      0 | init                                                                  | show processlist |
+----+------+--------------------+------+------------------+--------+-----------------------------------------------------------------------+------------------+
5 rows in set (0.00 sec)

slave操作:

show processlist;
+----+-------------+-----------+------+---------+--------+-----------------------------------------------------------------------------+------------------+
| Id | User        | Host      | db   | Command | Time   | State                                                                       | Info             |
+----+-------------+-----------+------+---------+--------+-----------------------------------------------------------------------------+------------------+
|  1 | system user |           | NULL | Connect | 290159 | Waiting for master to send event                                            | NULL             |
|  2 | system user |           | NULL | Connect |   3687 | Slave has read all relay log; waiting for the slave I/O thread to update it | NULL             |
| 12 | root        | localhost | NULL | Query   |      0 | init                                                                        | show processlist |
+----+-------------+-----------+------+---------+--------+-----------------------------------------------------------------------------+------------------+
3 rows in set (0.00 sec)

启动:

nohup mysqld_safe --defaults-file=/usr/my.cnf 2>&1 > /dev/null &

关闭:

mysqladmin -u root -p -S /var/lib/mysql/mysql.sock shutdown

查看mysql端口:

netstat -tulpn |grep -i mysql

tcp6       0      0 :::3306                 :::*                    LISTEN      8681/mysqld

ss -tulpn |grep -i mysql

tcp    LISTEN     0      80       :::3306                 :::*                   users:(("mysqld",pid=8681,fd=15))

登录mysql:

mysql -u root -p -S /var/lib/mysql/mysql.sock

远程登录,指定IP、端口

mysql -u root -p -h 192.168.1.14 -P 3306

清屏:

mysql> system clear;

临时修改mysql提示符:

prompt \u@\h \d \r:\m:\s>

PROMPT set to '\u@\h \d \r:\m:\s>'
root@localhost (none) 04:39:01>

永久修改mysql提示符:(无需重启)

参考:http://www.2cto.com/database/201304/201745.html

或在shell中添加环境变量

vi /etc/profile

MYSQL_PS1="\u@\h \d \r:\m:\s>";export MYSQL_PS1

su -

刷新权限

flush privileges;

删除用户

drop user 'test2'@'%';

创建用户并授权

grant all privileges on sbtest.* to 'test2'@'localhost' identified by 'test2';

create user 'test3'@'%' identified by 'test3';

grant all privileges on sbtest.* to 'test3'@'%';

查看权限

show grants for 'test2'@'localhost';

+--------------------------------------------------------------------------------------------------------------+
| Grants for test2@localhost                                                                                   |
+--------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'test2'@'localhost' IDENTIFIED BY PASSWORD '*7CEB3FDE5F7A9C4CE5FBE610D7D8EDA62EBE5F4E' |
| GRANT ALL PRIVILEGES ON `sbtest`.* TO 'test2'@'localhost'                                                    |
+--------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

show grants for 'test3'@'%';

+------------------------------------------------------------------------------------------------------+
| Grants for test3@%                                                                                   |
+------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'test3'@'%' IDENTIFIED BY PASSWORD '*F357E78CABAD76FD3F1018EF85D78499B6ACC431' |
| GRANT ALL PRIVILEGES ON `sbtest`.* TO 'test3'@'%'                                                    |
+------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql日常维护

MySQL重要目录

数据库目录   /var/lib/mysql
配置文件     /usr/share/mysql
命令目录     /usr/bin(mysqladmin mysqldump等命令)
启动脚本     /etc/rc.d/init.d/mysql

重新启动mysql服务

service mysql restart

Shutting down MySQL.... SUCCESS!
Starting MySQL. SUCCESS!

检查mysql3306状态

netstat -nat

Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN    
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN    
tcp        0     52 192.168.1.11:22         192.168.1.10:49576      ESTABLISHED
tcp6       0      0 :::3306                 :::*                    LISTEN    
tcp6       0      0 :::22                   :::*                    LISTEN    
tcp6       0      0 ::1:25                  :::*                    LISTEN    
tcp6       0      0 192.168.1.11:3306       192.168.1.14:5464       ESTABLISHED
tcp6       0      0 192.168.1.11:3306       192.168.1.12:21576      ESTABLISHED

检查mysql活动状态

mysqladmin -u root -p ping

Enter password:
mysqld is alive

返回服务器状态

mysqladmin -u root -p status

Enter password:
Uptime: 632  Threads: 3  Questions: 30  Slow queries: 0  Opens: 70  Flush tables: 1  Open tables: 63  Queries per second avg: 0.047

关闭MySQL服务

mysqladmin -u root -p shutdown

service mysql start

显示服务器版本

mysqladmin -u root -p version

Enter password:
mysqladmin  Ver 8.42 Distrib 5.6.40, for Linux on x86_64
Copyright (c) 2000, 2018, 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.

Server version          5.6.40-log
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 4 min 53 sec

Threads: 3  Questions: 30  Slow queries: 0  Opens: 70  Flush tables: 1  Open tables: 63  Queries per second avg: 0.102

修改mysql管理员密码

mysqladmin -u root -p password 'jge64NSU'       ###单引号里面的为新密码

Enter password: 输入旧密码
Warning: Using a password on the command line interface can be insecure.

mysql添加新用户

格式:grant 权限 on 数据库.* to 用户名@登录主机 identified by "密码"
 
grant select,insert,update,delete on *.* to 'test2'@'%' identified by 'test2';

grant all on sbtest.* to 'test3'@'localhost' identified by 'test3';

'test2'@'%'=所有网络
'test3'@'localhost'=只能本地服务器登录
'test3'@'192.168.0.10'=指定IP登录
'test3'@'192.168.0.%'=192.168.0/254网络登录

mysql撤销用户权限

格式: revoke 权限 on 数据库.表 from 用户名@登录客户端;

revoke insert,delete on *.* from 'test2'@'localhost';

revoke all on sbtest.* from 'test3'@'localhost';

mysql删除用户

drop user 'test2'@'localhost';

drop user 'test3'@'localhost';

查看mysql用户

select host,user,password from mysql.user;

+--------------+------+-------------------------------------------+
| host         | user | password                                  |
+--------------+------+-------------------------------------------+
| localhost    | root | *919C4FEEA34F61D80C2784EA3B9E5AEA260BA29D |
| 127.0.0.1    | root |                                           |
| ::1          | root |                                           |
| 192.168.1.12 | repl | *A65B51DC9961BDCD4A93BE9063689226163D7343 |
| %            | repl |                                           |
| %            | test |                                           |
| 192.168.1.10 | test | *2FF960917BC9231714223F746ECBC728FCC24E59 |
| 192.168.1.13 | test | *2FF960917BC9231714223F746ECBC728FCC24E59 |
| 192.168.1.11 | test | *2FF960917BC9231714223F746ECBC728FCC24E59 |
| 192.168.1.12 | test | *2FF960917BC9231714223F746ECBC728FCC24E59 |
| 192.168.1.11 | repl | *A65B51DC9961BDCD4A93BE9063689226163D7343 |
| 192.168.1.14 | repl | *A65B51DC9961BDCD4A93BE9063689226163D7343 |
| 192.168.1.11 | root | *919C4FEEA34F61D80C2784EA3B9E5AEA260BA29D |
| 192.168.1.12 | root | *919C4FEEA34F61D80C2784EA3B9E5AEA260BA29D |
| 192.168.1.14 | root | *919C4FEEA34F61D80C2784EA3B9E5AEA260BA29D |
| 192.168.1.15 | root | *919C4FEEA34F61D80C2784EA3B9E5AEA260BA29D |
| 192.168.1.26 | root | *919C4FEEA34F61D80C2784EA3B9E5AEA260BA29D |
| 192.168.1.%  | test | *2FF960917BC9231714223F746ECBC728FCC24E59 |
+--------------+------+-------------------------------------------+
18 rows in set (0.00 sec)

查看连接服务器用户线程

show processlist;

+----+------+--------------------+------+------------------+------+-----------------------------------------------------------------------+------------------+
| Id | User | Host               | db   | Command          | Time | State                                                                 | Info             |
+----+------+--------------------+------+------------------+------+-----------------------------------------------------------------------+------------------+
|  1 | repl | mysqlstandby:21583 | NULL | Binlog Dump GTID | 6239 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL             |
|  2 | repl | mysql3:5471        | NULL | Binlog Dump GTID | 6239 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL             |
| 11 | root | localhost          | NULL | Query            |    0 | init                                                                  | show processlist |
+----+------+--------------------+------+------------------+------+-----------------------------------------------------------------------+------------------+
3 rows in set (0.00 sec)

杀掉用户线程

mysql> kill 11;

ERROR 1317 (70100): Query execution was interrupted

mysql数据库备份恢复

显示数据库sbtest内容

mysqldump -u root -p --set-gtid-purged=OFF sbtest |more

备份多个表,备份数据库sbtest的表test和表test_log

mysqldump -u root -p --set-gtid-purged=OFF sbtest test test_log > /home/sbtest.test_test_log.sql

备份单一数据库sbtest

mysqldump -u root -p --set-gtid-purged=OFF sbtest > /home/sbtest.sql

备份多个数据库,备份数据库sbtest和数据库mysql

mysqldump -u root -p --set-gtid-purged=OFF -B sbtest mysql > /home/sbtest_mysql.sql

备份所有数据库

mysqldump -u root -p --set-gtid-purged=OFF --all-databases > /home/all-databases.sql

恢复数据库

mysql -u root -p

use sbtest;

source /home/sbtest.sql;

一.Mysql状态检查

1.关注连接数

如果连接数达到了最大连接数,那不管有多少资源,用户都会阻塞在外面。

修改MySQL最大连接数,修改max_connections=100(默认为100)。

请根据硬件情况调整到合适的大小,一般经验值可设为3000。Windows服务器大概支持量为1500-1800个连接,linux服务器可以支持到8000个左右。

mysql -u root -p

show global variables like '%max_connections%';

+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 151   |
+-----------------+-------+
1 row in set (0.00 sec)

set global max_connections=300;

show global variables like '%max_connections%';

+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 300   |
+-----------------+-------+
1 row in set (0.00 sec)

vi /usr/my.cnf

max_connections=300

请将max_user_connections设0(默认值已经是0了)——–这个0代表不限制单用户的最大连接数,其最大连接值可以等于max_connections值。

show global variables like '%max_user_connections%';

+----------------------+-------+
| Variable_name        | Value |
+----------------------+-------+
| max_user_connections | 0     |
+----------------------+-------+
1 row in set (0.00 sec)

检查下最大的过往使用连接数,这个值在max_connections的85%左右是比较合适的,如果过高则是max_connections过少或者系统负荷过高了。

show global status like 'Max_used_connections';

+----------------------+-------+
| Variable_name        | Value |
+----------------------+-------+
| Max_used_connections | 3     |
+----------------------+-------+
1 row in set (0.00 sec)

mysql日常运维

1. mysql查看数据库mysql大小,单位为GB。

select (sum(data_length)+sum(index_length))/1024/1024/1024 as 'DB_SIZE_GB' from information_schema.tables where table_schema='mysql';

+----------------+
| DB_SIZE_GB     |
+----------------+
| 0.000865336508 |
+----------------+
1 row in set (0.00 sec)

2. mysql表占用的空间,查询mysql.user表的大小,单位为GB。

select table_name,(data_length+index_length)/1024/1024/1024 as 'TABLE_SIZE_GB',table_rows from information_schema.tables where table_schema='mysql' and table_name='user';

+------------+----------------+------------+
| table_name | TABLE_SIZE_GB  | table_rows |
+------------+----------------+------------+
| user       | 0.000004224479 |         18 |
+------------+----------------+------------+
1 row in set (0.00 sec)

3. 查看表的最后mysql修改时间,查看数据库mysql里面的全部表的最后修改时间。

select table_name,update_time from information_schema.tables where table_schema='mysql';

+---------------------------+---------------------+
| table_name                | update_time         |
+---------------------------+---------------------+
| columns_priv              | 2018-07-17 17:44:07 |
| db                        | 2018-07-19 23:36:43 |
| event                     | 2018-07-17 17:44:07 |
| func                      | 2018-07-17 17:44:07 |
| general_log               | NULL                |
| help_category             | 2018-07-17 17:44:07 |
| help_keyword              | 2018-07-17 17:44:07 |
| help_relation             | 2018-07-17 17:44:07 |
| help_topic                | 2018-07-17 17:44:07 |
| innodb_index_stats        | NULL                |
| innodb_table_stats        | NULL                |
| ndb_binlog_index          | 2018-07-17 17:44:08 |
| plugin                    | 2018-07-17 17:44:08 |
| proc                      | 2018-07-17 17:44:08 |
| procs_priv                | 2018-07-17 17:44:08 |
| proxies_priv              | 2018-07-17 17:44:08 |
| servers                   | 2018-07-17 17:44:09 |
| slave_master_info         | NULL                |
| slave_relay_log_info      | NULL                |
| slave_worker_info         | NULL                |
| slow_log                  | NULL                |
| tables_priv               | 2018-07-19 17:23:33 |
| test                      | NULL                |
| time_zone                 | 2018-07-17 17:44:11 |
| time_zone_leap_second     | 2018-07-17 17:44:11 |
| time_zone_name            | 2018-07-17 17:44:11 |
| time_zone_transition      | 2018-07-17 17:44:11 |
| time_zone_transition_type | 2018-07-17 17:44:11 |
| user                      | 2018-07-19 23:37:06 |
+---------------------------+---------------------+
29 rows in set (0.00 sec)

4.查看当前的连接数

show global status like 'Threads%';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| Threads_cached    | 0     |
| Threads_connected | 3     |当前连接数
| Threads_created   | 3     |
| Threads_running   | 3     |当前的并发数
+-------------------+-------+
4 rows in set (0.00 sec)

5.查看最大连接数

show global variables like '%max_connections%';

+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 300   |
+-----------------+-------+
1 row in set (0.00 sec)

6.查看QPS

QPS (Query per second) (每秒查询量)

show global status like 'Questions';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Questions     | 87    |
+---------------+-------+
1 row in set (0.00 sec)

show global status like 'Uptime';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Uptime        | 6060  |
+---------------+-------+
1 row in set (0.00 sec)

select 87/6060 as QPS from dual;

+--------+
| QPS    |
+--------+
| 0.0144 |
+--------+
1 row in set (0.00 sec)

7.查看tps

TPS(Transaction per second) (每秒事务量,如果是InnoDB会显示,没有InnoDB就不会显示)

show global status like 'Com_commit';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Com_commit    | 0     |
+---------------+-------+
1 row in set (0.00 sec)

show global status like 'Com_rollback';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Com_rollback  | 0     |
+---------------+-------+
1 row in set (0.00 sec)

show global status like 'Uptime';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Uptime        | 6832  |
+---------------+-------+
1 row in set (0.00 sec)

select (0+0)/6832 as TPS from dual;
+--------+
| TPS    |
+--------+
| 0.0000 |
+--------+
1 row in set (0.00 sec)

8. 登录(-D 数据库名 表示登录成功后切换到该数据库),以下则表示以ROOT用户远程登录到服务器192.168.1.14的3306端口的MYSQL服务,在登录成功后,切换到数据库sbtest

mysql -h $IP -P $PORT -u $USER -p -D 数据库名

mysql -h 192.168.1.14 -P 3306 -u root -p -D sbtest

查看当前使用的是哪个数据库

select database();

+------------+
| database() |
+------------+
| sbtest     |
+------------+
1 row in set (0.01 sec)

MYSQL日常维护

查看连接数; (Threads 连接数)

show global status like '%Threads_%';

+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| Threads_cached    | 1     |
| Threads_connected | 1     |
| Threads_created   | 2     |
| Threads_running   | 1     |
+-------------------+-------+
4 rows in set (0.00 sec)

查看最大连接数

show global variables like 'max_connections';

+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 151   |
+-----------------+-------+
1 row in set (0.00 sec)

设置最大连接数

set global max_connections=300;

查看状态:

show global status;

+-----------------------------------------------+-------------+
| Variable_name                                 | Value       |
+-----------------------------------------------+-------------+
| Aborted_clients                               | 0           |
| Aborted_connects                              | 0           |
| Binlog_cache_disk_use                         | 0           |
| Binlog_cache_use                              | 0           |
| Binlog_stmt_cache_disk_use                    | 0           |
| Binlog_stmt_cache_use                         | 0           |
| Bytes_received                                | 1902        |
| Bytes_sent                                    | 3377        |
| Com_admin_commands                            | 2           |
| Com_assign_to_keycache                        | 0           |
| Com_alter_db                                  | 0           |
| Com_alter_db_upgrade                          | 0           |
| Com_alter_event                               | 0           |
| Com_alter_function                            | 0           |
| Com_alter_procedure                           | 0           |
| Com_alter_server                              | 0           |
| Com_alter_table                               | 0           |
| Com_alter_tablespace                          | 0           |
| Com_alter_user                                | 0           |
| Com_analyze                                   | 0           |
| Com_begin                                     | 0           |
| Com_binlog                                    | 0           |
| Com_call_procedure                            | 0           |
| Com_change_db                                 | 0           |
| Com_change_master                             | 0           |
| Com_check                                     | 0           |
| Com_checksum                                  | 0           |
| Com_commit                                    | 0           |
| Com_create_db                                 | 0           |
| Com_create_event                              | 0           |
| Com_create_function                           | 0           |
| Com_create_index                              | 0           |
| Com_create_procedure                          | 0           |
| Com_create_server                             | 0           |
| Com_create_table                              | 0           |
| Com_create_trigger                            | 0           |
| Com_create_udf                                | 0           |
| Com_create_user                               | 0           |
| Com_create_view                               | 0           |
| Com_dealloc_sql                               | 0           |
| Com_delete                                    | 0           |
| Com_delete_multi                              | 0           |
| Com_do                                        | 0           |
| Com_drop_db                                   | 0           |
| Com_drop_event                                | 0           |
| Com_drop_function                             | 0           |
| Com_drop_index                                | 0           |
| Com_drop_procedure                            | 0           |
| Com_drop_server                               | 0           |
| Com_drop_table                                | 0           |
| Com_drop_trigger                              | 0           |
| Com_drop_user                                 | 0           |
| Com_drop_view                                 | 0           |
| Com_empty_query                               | 0           |
| Com_execute_sql                               | 0           |
| Com_flush                                     | 0           |
| Com_get_diagnostics                           | 0           |
| Com_grant                                     | 0           |
| Com_ha_close                                  | 0           |
| Com_ha_open                                   | 0           |
| Com_ha_read                                   | 0           |
| Com_help                                      | 0           |
| Com_insert                                    | 0           |
| Com_insert_select                             | 0           |
| Com_install_plugin                            | 0           |
| Com_kill                                      | 0           |
| Com_load                                      | 0           |
| Com_lock_tables                               | 0           |
| Com_optimize                                  | 0           |
| Com_preload_keys                              | 0           |
| Com_prepare_sql                               | 0           |
| Com_purge                                     | 0           |
| Com_purge_before_date                         | 0           |
| Com_release_savepoint                         | 0           |
| Com_rename_table                              | 0           |
| Com_rename_user                               | 0           |
| Com_repair                                    | 0           |
| Com_replace                                   | 0           |
| Com_replace_select                            | 0           |
| Com_reset                                     | 0           |
| Com_resignal                                  | 0           |
| Com_revoke                                    | 0           |
| Com_revoke_all                                | 0           |
| Com_rollback                                  | 0           |
| Com_rollback_to_savepoint                     | 0           |
| Com_savepoint                                 | 0           |
| Com_select                                    | 7           |
| Com_set_option                                | 11          |
| Com_signal                                    | 0           |
| Com_show_binlog_events                        | 0           |
| Com_show_binlogs                              | 0           |
| Com_show_charsets                             | 0           |
| Com_show_collations                           | 0           |
| Com_show_create_db                            | 0           |
| Com_show_create_event                         | 0           |
| Com_show_create_func                          | 0           |
| Com_show_create_proc                          | 0           |
| Com_show_create_table                         | 0           |
| Com_show_create_trigger                       | 0           |
| Com_show_databases                            | 0           |
| Com_show_engine_logs                          | 0           |
| Com_show_engine_mutex                         | 0           |
| Com_show_engine_status                        | 0           |
| Com_show_events                               | 0           |
| Com_show_errors                               | 0           |
| Com_show_fields                               | 0           |
| Com_show_function_code                        | 0           |
| Com_show_function_status                      | 0           |
| Com_show_grants                               | 0           |
| Com_show_keys                                 | 0           |
| Com_show_master_status                        | 0           |
| Com_show_open_tables                          | 0           |
| Com_show_plugins                              | 0           |
| Com_show_privileges                           | 0           |
| Com_show_procedure_code                       | 0           |
| Com_show_procedure_status                     | 0           |
| Com_show_processlist                          | 0           |
| Com_show_profile                              | 0           |
| Com_show_profiles                             | 0           |
| Com_show_relaylog_events                      | 0           |
| Com_show_slave_hosts                          | 0           |
| Com_show_slave_status                         | 0           |
| Com_show_status                               | 1           |
| Com_show_storage_engines                      | 0           |
| Com_show_table_status                         | 0           |
| Com_show_tables                               | 0           |
| Com_show_triggers                             | 0           |
| Com_show_variables                            | 8           |
| Com_show_warnings                             | 0           |
| Com_slave_start                               | 0           |
| Com_slave_stop                                | 0           |
| Com_stmt_close                                | 0           |
| Com_stmt_execute                              | 0           |
| Com_stmt_fetch                                | 0           |
| Com_stmt_prepare                              | 0           |
| Com_stmt_reprepare                            | 0           |
| Com_stmt_reset                                | 0           |
| Com_stmt_send_long_data                       | 0           |
| Com_truncate                                  | 0           |
| Com_uninstall_plugin                          | 0           |
| Com_unlock_tables                             | 0           |
| Com_update                                    | 0           |
| Com_update_multi                              | 0           |
| Com_xa_commit                                 | 0           |
| Com_xa_end                                    | 0           |
| Com_xa_prepare                                | 0           |
| Com_xa_recover                                | 0           |
| Com_xa_rollback                               | 0           |
| Com_xa_start                                  | 0           |
| Compression                                   | OFF         |
| Connection_errors_accept                      | 0           |
| Connection_errors_internal                    | 0           |
| Connection_errors_max_connections             | 0           |
| Connection_errors_peer_address                | 0           |
| Connection_errors_select                      | 0           |
| Connection_errors_tcpwrap                     | 0           |
| Connections                                   | 4           |
| Created_tmp_disk_tables                       | 0           |
| Created_tmp_files                             | 6           |
| Created_tmp_tables                            | 9           |
| Delayed_errors                                | 0           |
| Delayed_insert_threads                        | 0           |
| Delayed_writes                                | 0           |
| Flush_commands                                | 1           |
| Handler_commit                                | 3           |
| Handler_delete                                | 0           |
| Handler_discover                              | 0           |
| Handler_external_lock                         | 146         |
| Handler_mrr_init                              | 0           |
| Handler_prepare                               | 0           |
| Handler_read_first                            | 6           |
| Handler_read_key                              | 3           |
| Handler_read_last                             | 0           |
| Handler_read_next                             | 1           |
| Handler_read_prev                             | 0           |
| Handler_read_rnd                              | 0           |
| Handler_read_rnd_next                         | 51          |
| Handler_rollback                              | 0           |
| Handler_savepoint                             | 0           |
| Handler_savepoint_rollback                    | 0           |
| Handler_update                                | 0           |
| Handler_write                                 | 8           |
| Innodb_buffer_pool_dump_status                | not started |
| Innodb_buffer_pool_load_status                | not started |
| Innodb_buffer_pool_pages_data                 | 337         |
| Innodb_buffer_pool_bytes_data                 | 5521408     |
| Innodb_buffer_pool_pages_dirty                | 0           |
| Innodb_buffer_pool_bytes_dirty                | 0           |
| Innodb_buffer_pool_pages_flushed              | 1           |
| Innodb_buffer_pool_pages_free                 | 7854        |
| Innodb_buffer_pool_pages_misc                 | 0           |
| Innodb_buffer_pool_pages_total                | 8191        |
| Innodb_buffer_pool_read_ahead_rnd             | 0           |
| Innodb_buffer_pool_read_ahead                 | 0           |
| Innodb_buffer_pool_read_ahead_evicted         | 0           |
| Innodb_buffer_pool_read_requests              | 14998       |
| Innodb_buffer_pool_reads                      | 338         |
| Innodb_buffer_pool_wait_free                  | 0           |
| Innodb_buffer_pool_write_requests             | 1           |
| Innodb_data_fsyncs                            | 5           |
| Innodb_data_pending_fsyncs                    | 0           |
| Innodb_data_pending_reads                     | 0           |
| Innodb_data_pending_writes                    | 0           |
| Innodb_data_read                              | 5607424     |
| Innodb_data_reads                             | 353         |
| Innodb_data_writes                            | 5           |
| Innodb_data_written                           | 34304       |
| Innodb_dblwr_pages_written                    | 1           |
| Innodb_dblwr_writes                           | 1           |
| Innodb_have_atomic_builtins                   | ON          |
| Innodb_log_waits                              | 0           |
| Innodb_log_write_requests                     | 0           |
| Innodb_log_writes                             | 1           |
| Innodb_os_log_fsyncs                          | 3           |
| Innodb_os_log_pending_fsyncs                  | 0           |
| Innodb_os_log_pending_writes                  | 0           |
| Innodb_os_log_written                         | 512         |
| Innodb_page_size                              | 16384       |
| Innodb_pages_created                          | 0           |
| Innodb_pages_read                             | 337         |
| Innodb_pages_written                          | 1           |
| Innodb_row_lock_current_waits                 | 0           |
| Innodb_row_lock_time                          | 0           |
| Innodb_row_lock_time_avg                      | 0           |
| Innodb_row_lock_time_max                      | 0           |
| Innodb_row_lock_waits                         | 0           |
| Innodb_rows_deleted                           | 0           |
| Innodb_rows_inserted                          | 0           |
| Innodb_rows_read                              | 0           |
| Innodb_rows_updated                           | 0           |
| Innodb_num_open_files                         | 8           |
| Innodb_truncated_status_writes                | 0           |
| Innodb_available_undo_logs                    | 128         |
| Key_blocks_not_flushed                        | 0           |
| Key_blocks_unused                             | 6695        |
| Key_blocks_used                               | 3           |
| Key_read_requests                             | 6           |
| Key_reads                                     | 3           |
| Key_write_requests                            | 0           |
| Key_writes                                    | 0           |
| Last_query_cost                               | 0.000000    |
| Last_query_partial_plans                      | 0           |
| Max_used_connections                          | 3           |
| Not_flushed_delayed_rows                      | 0           |
| Open_files                                    | 21          |
| Open_streams                                  | 0           |
| Open_table_definitions                        | 70          |
| Open_tables                                   | 63          |
| Opened_files                                  | 130         |
| Opened_table_definitions                      | 70          |
| Opened_tables                                 | 70          |
| Performance_schema_accounts_lost              | 0           |
| Performance_schema_cond_classes_lost          | 0           |
| Performance_schema_cond_instances_lost        | 0           |
| Performance_schema_digest_lost                | 0           |
| Performance_schema_file_classes_lost          | 0           |
| Performance_schema_file_handles_lost          | 0           |
| Performance_schema_file_instances_lost        | 0           |
| Performance_schema_hosts_lost                 | 0           |
| Performance_schema_locker_lost                | 0           |
| Performance_schema_mutex_classes_lost         | 0           |
| Performance_schema_mutex_instances_lost       | 0           |
| Performance_schema_rwlock_classes_lost        | 0           |
| Performance_schema_rwlock_instances_lost      | 0           |
| Performance_schema_session_connect_attrs_lost | 0           |
| Performance_schema_socket_classes_lost        | 0           |
| Performance_schema_socket_instances_lost      | 0           |
| Performance_schema_stage_classes_lost         | 0           |
| Performance_schema_statement_classes_lost     | 0           |
| Performance_schema_table_handles_lost         | 0           |
| Performance_schema_table_instances_lost       | 0           |
| Performance_schema_thread_classes_lost        | 0           |
| Performance_schema_thread_instances_lost      | 0           |
| Performance_schema_users_lost                 | 0           |
| Prepared_stmt_count                           | 0           |
| Qcache_free_blocks                            | 1           |
| Qcache_free_memory                            | 1031352     |
| Qcache_hits                                   | 0           |
| Qcache_inserts                                | 0           |
| Qcache_lowmem_prunes                          | 0           |
| Qcache_not_cached                             | 7           |
| Qcache_queries_in_cache                       | 0           |
| Qcache_total_blocks                           | 1           |
| Queries                                       | 32          |
| Questions                                     | 31          |
| Rpl_semi_sync_master_clients                  | 2           |
| Rpl_semi_sync_master_net_avg_wait_time        | 0           |
| Rpl_semi_sync_master_net_wait_time            | 0           |
| Rpl_semi_sync_master_net_waits                | 0           |
| Rpl_semi_sync_master_no_times                 | 0           |
| Rpl_semi_sync_master_no_tx                    | 0           |
| Rpl_semi_sync_master_status                   | ON          |
| Rpl_semi_sync_master_timefunc_failures        | 0           |
| Rpl_semi_sync_master_tx_avg_wait_time         | 0           |
| Rpl_semi_sync_master_tx_wait_time             | 0           |
| Rpl_semi_sync_master_tx_waits                 | 0           |
| Rpl_semi_sync_master_wait_pos_backtraverse    | 0           |
| Rpl_semi_sync_master_wait_sessions            | 0           |
| Rpl_semi_sync_master_yes_tx                   | 0           |
| Rpl_semi_sync_slave_status                    | OFF         |
| Select_full_join                              | 0           |
| Select_full_range_join                        | 0           |
| Select_range                                  | 0           |
| Select_range_check                            | 0           |
| Select_scan                                   | 9           |
| Slave_heartbeat_period                        | 0.000       |
| Slave_last_heartbeat                          |             |
| Slave_open_temp_tables                        | 0           |
| Slave_received_heartbeats                     | 0           |
| Slave_retried_transactions                    | 0           |
| Slave_running                                 | OFF         |
| Slow_launch_threads                           | 0           |
| Slow_queries                                  | 0           |
| Sort_merge_passes                             | 0           |
| Sort_range                                    | 0           |
| Sort_rows                                     | 0           |
| Sort_scan                                     | 0           |
| Ssl_accept_renegotiates                       | 0           |
| Ssl_accepts                                   | 0           |
| Ssl_callback_cache_hits                       | 0           |
| Ssl_cipher                                    |             |
| Ssl_cipher_list                               |             |
| Ssl_client_connects                           | 0           |
| Ssl_connect_renegotiates                      | 0           |
| Ssl_ctx_verify_depth                          | 0           |
| Ssl_ctx_verify_mode                           | 0           |
| Ssl_default_timeout                           | 0           |
| Ssl_finished_accepts                          | 0           |
| Ssl_finished_connects                         | 0           |
| Ssl_server_not_after                          |             |
| Ssl_server_not_before                         |             |
| Ssl_session_cache_hits                        | 0           |
| Ssl_session_cache_misses                      | 0           |
| Ssl_session_cache_mode                        | NONE        |
| Ssl_session_cache_overflows                   | 0           |
| Ssl_session_cache_size                        | 0           |
| Ssl_session_cache_timeouts                    | 0           |
| Ssl_sessions_reused                           | 0           |
| Ssl_used_session_cache_entries                | 0           |
| Ssl_verify_depth                              | 0           |
| Ssl_verify_mode                               | 0           |
| Ssl_version                                   |             |
| Table_locks_immediate                         | 73          |
| Table_locks_waited                            | 0           |
| Table_open_cache_hits                         | 3           |
| Table_open_cache_misses                       | 70          |
| Table_open_cache_overflows                    | 0           |
| Tc_log_max_pages_used                         | 0           |
| Tc_log_page_size                              | 0           |
| Tc_log_page_waits                             | 0           |
| Threads_cached                                | 0           |
| Threads_connected                             | 3           |
| Threads_created                               | 3           |
| Threads_running                               | 3           |
| Uptime                                        | 179         |
| Uptime_since_flush_status                     | 179         |
+-----------------------------------------------+-------------+
356 rows in set (0.00 sec)

查看连接详细资料:

show full processlist;

+----+------+--------------------+------+------------------+------+-----------------------------------------------------------------------+-----------------------+
| Id | User | Host               | db   | Command          | Time | State                                                                 | Info                  |
+----+------+--------------------+------+------------------+------+-----------------------------------------------------------------------+-----------------------+
|  1 | root | localhost          | NULL | Query            |    0 | init                                                                  | show full processlist |
|  2 | repl | mysqlstandby:21588 | NULL | Binlog Dump GTID |  787 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL                  |
|  3 | repl | mysql3:5476        | NULL | Binlog Dump GTID |  787 | Master has sent all binlog to slave; waiting for binlog to be updated | NULL                  |
+----+------+--------------------+------+------------------+------+-----------------------------------------------------------------------+-----------------------+
3 rows in set (0.00 sec)

查看MYSQL配置信息

show global variables;

5.5.2 MySQL常用统计语句

查询指定SQL的trace信息

mysql -u root -p -h 192.168.1.11 -e "\
use xiaoboluo; \
set session optimizer_trace='enabled=on'; \
set optimizer_trace_max_mem_size = 1638400; \
explain select * from test; \
select * from information_schema.optimizer_trace\G;" > /home/sql_trace.log

查看表的大小的使用情况,不要WHERE条件就是查找整个MYSQL数据库中的全部表。

select table_name,(data_length+index_length)/1024/1024/1024 as TOTAL_GB,table_rows from information_schema.tables
where table_schema='mysql'
order by TOTAL_GB desc;

+---------------------------+----------------+------------+
| table_name                | TOTAL_GB       | table_rows |
+---------------------------+----------------+------------+
| help_topic                | 0.000559028238 |        585 |
| help_keyword              | 0.000134549104 |        619 |
| help_relation             | 0.000029743649 |       1273 |
| slave_worker_info         | 0.000015258789 |          0 |
| slave_relay_log_info      | 0.000015258789 |          0 |
| slave_master_info         | 0.000015258789 |          0 |
| innodb_table_stats        | 0.000015258789 |          4 |
| innodb_index_stats        | 0.000015258789 |         21 |
| test                      | 0.000015258789 |          0 |
| tables_priv               | 0.000009214506 |          1 |
| proxies_priv              | 0.000006059185 |          2 |
| db                        | 0.000005997717 |          0 |
| user                      | 0.000004224479 |         18 |
| help_category             | 0.000003904104 |         40 |
| procs_priv                | 0.000003814697 |          0 |
| columns_priv              | 0.000003814697 |          0 |
| plugin                    | 0.000001989305 |          2 |
| proc                      | 0.000001907349 |          0 |
| event                     | 0.000001907349 |          0 |
| func                      | 0.000000953674 |          0 |
| time_zone_transition_type | 0.000000953674 |          0 |
| servers                   | 0.000000953674 |          0 |
| time_zone_transition      | 0.000000953674 |          0 |
| ndb_binlog_index          | 0.000000953674 |          0 |
| time_zone_name            | 0.000000953674 |          0 |
| time_zone_leap_second     | 0.000000953674 |          0 |
| time_zone                 | 0.000000953674 |          0 |
| slow_log                  | 0.000000000000 |          2 |
| general_log               | 0.000000000000 |          2 |
+---------------------------+----------------+------------+
29 rows in set (0.00 sec)

MySQL查询阻塞语句

select r.trx_id waiting_trx_id, r.trx_mysql_thread_Id waiting_thread,
       r.trx_query waiting_query, b.trx_id blocking_trx_id,
       b.trx_mysql_thread_id blocking_thread, b.trx_query blocking_query
  from information_schema.innodb_lock_waits w inner join information_schema.innodb_trx b on b.trx_id = w.blocking_trx_id
  inner join information_schema.innodb_trx r on r.trx_id = w.requesting_trx_id;

查询表的数据量大小

select table_name,(data_length+index_length)/1024/1024/1024 as TABLE_GB,table_rows from information_schema.tables where table_schema='mysql' order by TABLE_GB desc;

+---------------------------+----------------+------------+
| table_name                | TABLE_GB       | table_rows |
+---------------------------+----------------+------------+
| help_topic                | 0.000559028238 |        585 |
| help_keyword              | 0.000134549104 |        619 |
| help_relation             | 0.000029743649 |       1273 |
| slave_worker_info         | 0.000015258789 |          0 |
| slave_relay_log_info      | 0.000015258789 |          0 |
| slave_master_info         | 0.000015258789 |          0 |
| innodb_table_stats        | 0.000015258789 |          4 |
| innodb_index_stats        | 0.000015258789 |         21 |
| test                      | 0.000015258789 |          0 |
| tables_priv               | 0.000009214506 |          1 |
| proxies_priv              | 0.000006059185 |          2 |
| db                        | 0.000005997717 |          0 |
| user                      | 0.000004224479 |         18 |
| help_category             | 0.000003904104 |         40 |
| procs_priv                | 0.000003814697 |          0 |
| columns_priv              | 0.000003814697 |          0 |
| plugin                    | 0.000001989305 |          2 |
| proc                      | 0.000001907349 |          0 |
| event                     | 0.000001907349 |          0 |
| func                      | 0.000000953674 |          0 |
| time_zone_transition_type | 0.000000953674 |          0 |
| servers                   | 0.000000953674 |          0 |
| time_zone_transition      | 0.000000953674 |          0 |
| ndb_binlog_index          | 0.000000953674 |          0 |
| time_zone_name            | 0.000000953674 |          0 |
| time_zone_leap_second     | 0.000000953674 |          0 |
| time_zone                 | 0.000000953674 |          0 |
| slow_log                  | 0.000000000000 |          2 |
| general_log               | 0.000000000000 |          2 |
+---------------------------+----------------+------------+
29 rows in set (0.00 sec)

统计数据库中访问量前10的IP

select substring_index(host,':',1) as IP,count(*) from information_schema.processlist group by IP order by count(*) desc limit 10;

+--------------+----------+
| IP           | count(*) |
+--------------+----------+
| localhost    |        1 |
| mysql3       |        1 |
| mysqlstandby |        1 |
+--------------+----------+
3 rows in set (0.00 sec)

MySql常用维护命令1

内容摘要:

本篇主要是对项目运行过程中会产生的一些数据维护,更新,参数设置等常用操作的记录和总结,方面在运用是有个参考。主要内容会涉及可参考目录简介。本编包含前1章节。按照目录连续7篇发布。

目录简介:

1.    数据库启停及状态检查

2.    CREATE操作项目

3.    ALTER操作项目

4.    数据库参数查看和设置

5.    客户端权限管理

6.    事件调度/临时触发器/定制任务

7.    触发器、存储过程

标签:

MySql,Create,Alter,ShowParameter,Event,Trigger,Procedure,Privilige

1.  数据库启停及状态检查

这里分linux和windows两个系统分别介绍

Linux:

启动数据库有三种方法,在root账户登录后的命令提示符下输入:

方法1:service mysqld start (5.0版本是mysqld)

service mysql start  (5.5.7版本是mysql)

方法2:/etc/init.d/mysql start

方法3:nohup mysqld_safe --defaults-file=/usr/my.cnf 2>&1 > /dev/null &

停止数据库有三种方法,在root账户登录后的命令提示符下输入:

方法1:service mysqld stop (5.0版本是mysqld)

service mysql stop  (5.5.7版本是mysql)

方法2:/etc/init.d/mysql stop

方法3:mysqladmin -u root -p shutdown

重启数据库推荐两种方法,在root账户登录后的命令提示符下输入:

方法1:service mysqld restart (5.0版本是mysqld)

service mysql restart  (5.5.7版本是mysql)

方法2:/etc/init.d/mysql restart

备注:数据库是否启动,可以用以下命令来查看。如下提示表示进程正常运行。

service mysql status

SUCCESS! MySQL running (15093)

Windows:

启动/停止/重启数据库有两种方法,

方法1: 通过Mysql Notifier,如下图

启动/停止/重启按照需要进行选择。这里也能够看出来实例实际运行状态。

方法2:通过服务来进行

Mysql安装成功后会在window系统服务中注册,服务名就是实例名,如下图所示为“MySQL56”

通过在命令行中输入services.msc打开服务控制台。红色方框内容可以进行启停操作,蓝色框内可以查看当前状态,蓝色框中的启动类型是指是否跟随操作系统的启动而自动启动

方法3:通过命令行服务来进行,如下命令不包含提示符(高逼格方式)

net start mysql56

net stop mysql56

红色部分是服务名称,不区分大小写。

MySQL数据库维护手册

一、每天做的

(一)确保mysql启动并运行。

查看mysql进程是否运行正常,具体命令是

ps -ef|grep -i mysql

root     14865     1  0 15:21 pts/0    00:00:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/lib/mysql/mysql.pid
mysql    15093 14865  0 15:21 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/lib/mysql/mysql.err --pid-file=/var/lib/mysql/mysql.pid
root     15173  9704  0 16:05 pts/0    00:00:00 grep --color=auto -i mysql

top检查mysql的运行。以下是一个例子:

top

top - 16:07:24 up 6 days,  1:12,  1 user,  load average: 0.00, 0.01, 0.05
Tasks: 157 total,   2 running, 155 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  1783992 total,   680836 free,   584036 used,   519120 buff/cache
KiB Swap:  1679356 total,  1679088 free,      268 used.  1037932 avail Mem

PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND                                                                                                                       
    1 root      20   0  125184   5040   3808 S  0.0  0.3   0:02.91 systemd                                                                                                                       
    2 root      20   0       0      0      0 S  0.0  0.0   0:00.03 kthreadd                                                                                                                      
    3 root      20   0       0      0      0 S  0.0  0.0   0:00.11 ksoftirqd/0                                                                                                                   
    7 root      20   0       0      0      0 S  0.0  0.0   0:03.76 rcu_sched                                                                                                                     
    8 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcu_bh                                                                                                                        
    9 root      20   0       0      0      0 R  0.0  0.0   0:03.50 rcuos/0                                                                                                                       
   10 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcuob/0                                                                                                                       
   11 root      rt   0       0      0      0 S  0.0  0.0   0:00.00 migration/0                                                                                                                   
   12 root      rt   0       0      0      0 S  0.0  0.0   0:01.17 watchdog/0

(二)检查管理员错误日志和慢查询日志。

管理员错误日志为DBA准备,它记录了mysqld当启动和停止,以及服务器在运行过程中发生的任务号严重错误是的相关信息。用log_error指定路径。命令:

tail -f /var/lib/mysql/mysql.err

2018-07-21 15:21:37 15093 [Note] Semi-sync replication enabled on the master.
2018-07-21 15:21:37 15093 [Note] Server hostname (bind-address): '*'; port: 3306
2018-07-21 15:21:37 15093 [Note] IPv6 is available.
2018-07-21 15:21:37 15093 [Note]   - '::' resolves to '::';
2018-07-21 15:21:37 15093 [Note] Server socket created on IP: '::'.
2018-07-21 15:21:37 15093 [Note] Event Scheduler: Loaded 0 events
2018-07-21 15:21:37 15093 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.6.40-log'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Community Server (GPL)
2018-07-21 15:22:33 15093 [Note] Start semi-sync binlog_dump to slave (server_id: 3), pos(, 4)
2018-07-21 15:22:33 15093 [Note] Start semi-sync binlog_dump to slave (server_id: 2), pos(, 4)

慢日志文件为开发人员而准备,记录了所有执行时间超过参数long_query_time 的sql语句。

查看:

show global variables like 'long_query_time';

+-----------------+-----------+
| Variable_name   | Value     |
+-----------------+-----------+
| long_query_time | 10.000000 |
+-----------------+-----------+
1 row in set (0.00 sec)

修改:

set global long_query_time=5;

命令1:汇总查看

mysqldumpslow /var/lib/mysql/mysql-slow.log

Reading mysql slow query log from /var/lib/mysql/mysql-slow.log
Count: 1  Time=0.00s (0s)  Lock=0.00s (0s)  Rows=0.0 (0), 0users@0hosts

命令2:直接文本文件查看

tail -100 /var/lib/mysql/mysql-slow.log |more

/usr/sbin/mysqld, Version: 5.6.40-log (MySQL Community Server (GPL)). started with:
Tcp port: 3306  Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command    Argument
/usr/sbin/mysqld, Version: 5.6.40-log (MySQL Community Server (GPL)). started with:
Tcp port: 0  Unix socket: (null)
Time                 Id Command    Argument
/usr/sbin/mysqld, Version: 5.6.40-log (MySQL Community Server (GPL)). started with:
Tcp port: 0  Unix socket: (null)
Time                 Id Command    Argument
/usr/sbin/mysqld, Version: 5.6.40-log (MySQL Community Server (GPL)). started with:
Tcp port: 0  Unix socket: (null)
Time                 Id Command    Argument

(三)检查昨天晚上的备份是否成功。

晚上备份如果有错或没有存放在安全的地方,那么对日后的恢复来说简直就是灾难。确认备份成功的命令是:

1、查看备份日志记录:tail –f /var/bak/mysql_bak_log.log

2、备份的文件:cat /var/bak/2012-03-07/IDM_bak.sql|more

3、可以每天把备份的结果和内容email发送给相关人员

4、异地备份文件

(四)查看数据库日志文件是否归档成功。

此处说的日志是mysql数据库的二进制日志,记录着DDL和DML语句,但不包括查询语句。此日志对于灾难是的数据恢复起着重要作用。用log_bin指定路径。

mysqlbinlog /var/lib/mysql/mysql-bin.000038

/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!40019 SET @@session.max_insert_delayed_threads=0*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#180721 15:21:37 server id 1  end_log_pos 120 CRC32 0x02f826f3  Start: binlog v 4, server v 5.6.40-log created 180721 15:21:37 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
Ad9SWw8BAAAAdAAAAHgAAAABAAQANS42LjQwLWxvZwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAB31JbEzgNAAgAEgAEBAQEEgAAXAAEGggAAAAICAgCAAAACgoKGRkAAfMm
+AI=
'/*!*/;
# at 120
#180721 15:21:37 server id 1  end_log_pos 231 CRC32 0xc17bece2  Previous-GTIDs
# 08a5acd3-6673-11e8-b993-000c29ee89cd:1-4,
# 1fdb51e5-6242-11e8-9e40-000c293b8095:1-30026
DELIMITER ;
# End of log file
ROLLBACK /* added by mysqlbinlog */;
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;

(五)检查并确认数据库和管理系统的配置参数没有被更改。

在有多个管理员的数据库环境下,经常会发生某个管理员改动配置参数而其他管理员不知晓的情况,所以管理员需要检查数 据库相关配置文件的正确性。

将这些命令的结果输出到一个文件,文件名可写上当时的时间,比如结果文件名" MYSQL_20120315.txt" ;使用UltraEdit文件的比较功能比较昨天的配置文件有无改变。

show global variables;

(六)查看数据库程序的工作负载。(不会)

对一个在线事务处理系统(OLTP)来说,缓冲池的利用比率是非常重要的。数据仓库应用中不可能有非常高的缓冲池利用率,所以根据工作负载量来进行各项性能检查就显得很重要了。

(七)确信还有足够的剩余内存空间可供数据库使用。

察看服务器上的总内存大小和MySQL数据库占用的内存大小情况是很重要的一件事,在Unix/Linux平台下使用free命令将显示出系统的总内存大小以及被应用程序占用掉的内存大小,和当前系统剩余可用的内存大小。

free

total        used        free      shared  buff/cache   available
Mem:        1783992      585508      679272       16772      519212     1036432
Swap:       1679356         268     1679088

(八)每天建议学习MySQL的相关知识。

广泛的阅读相关资料,比如"MysQL手册"对数据库管理员有帮助。跟mysql维护的人多多交流。

二、每周做的

(一)查找新的数据库对象。

察看是否有人在你的生产型数据库中建立了新的数据库对象(比如,表、索引、存储进程)也是一件重要的事情。新对象 的出现,一般意味着服务器上有新的应用出现了,否则新出现的对象会影响到系统操作的特性。另外新对象也会消耗掉系统的一部分存储空间,如果是非管理员建立 的新数据库对象将可能会对数据库表空间和运行效率产生不良影响。

查看表状态:跟上周比较结果,分析新增表

use mysql;

show table status;

+---------------------------+--------+---------+------------+------+----------------+-------------+--------------------+--------------+-----------+----------------+---------------------+---------------------+---------------------+-------------------+----------+--------------------+-----------------------------------------+
| Name                      | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length    | Index_length | Data_free | Auto_increment | Create_time         | Update_time         | Check_time          | Collation         | Checksum | Create_options     | Comment                                 |
+---------------------------+--------+---------+------------+------+----------------+-------------+--------------------+--------------+-----------+----------------+---------------------+---------------------+---------------------+-------------------+----------+--------------------+-----------------------------------------+
| columns_priv              | MyISAM |      10 | Fixed      |    0 |              0 |           0 | 227994731135631359 |         4096 |         0 |           NULL | 2018-07-17 17:44:07 | 2018-07-17 17:44:07 | NULL                | utf8_bin          |     NULL |                    | Column privileges                       |
| db                        | MyISAM |      10 | Fixed      |    0 |              0 |        1320 | 123848989752688639 |         5120 |      1320 |           NULL | 2018-07-17 17:44:07 | 2018-07-19 23:36:43 | 2018-07-17 17:44:07 | utf8_bin          |     NULL |                    | Database privileges                     |
| event                     | MyISAM |      10 | Dynamic    |    0 |              0 |           0 |    281474976710655 |         2048 |         0 |           NULL | 2018-07-17 17:44:07 | 2018-07-17 17:44:07 | NULL                | utf8_general_ci   |     NULL |                    | Events                                  |
| func                      | MyISAM |      10 | Fixed      |    0 |              0 |           0 | 162974011515469823 |         1024 |         0 |           NULL | 2018-07-17 17:44:07 | 2018-07-17 17:44:07 | NULL                | utf8_bin          |     NULL |                    | User defined functions                  |
| general_log               | CSV    |      10 | Dynamic    |    2 |              0 |           0 |                  0 |            0 |         0 |           NULL | NULL                | NULL                | NULL                | utf8_general_ci   |     NULL |                    | General log                             |
| help_category             | MyISAM |      10 | Dynamic    |   40 |             28 |        1120 |    281474976710655 |         3072 |         0 |           NULL | 2018-07-17 17:44:07 | 2018-07-17 17:44:07 | NULL                | utf8_general_ci   |     NULL |                    | help categories                         |
| help_keyword              | MyISAM |      10 | Fixed      |  619 |            197 |      121943 |  55450570411999231 |        22528 |         0 |           NULL | 2018-07-17 17:44:07 | 2018-07-17 17:44:07 | NULL                | utf8_general_ci   |     NULL |                    | help keywords                           |
| help_relation             | MyISAM |      10 | Fixed      | 1273 |              9 |       11457 |   2533274790395903 |        20480 |         0 |           NULL | 2018-07-17 17:44:07 | 2018-07-17 17:44:07 | NULL                | utf8_general_ci   |     NULL |                    | keyword-topic relation                  |
| help_topic                | MyISAM |      10 | Dynamic    |  585 |            987 |      577724 |    281474976710655 |        22528 |         0 |           NULL | 2018-07-17 17:44:07 | 2018-07-17 17:44:07 | NULL                | utf8_general_ci   |     NULL |                    | help topics                             |
| innodb_index_stats        | InnoDB |      10 | Compact    |   21 |            780 |       16384 |                  0 |            0 |         0 |           NULL | 2018-07-17 17:44:07 | NULL                | NULL                | utf8_bin          |     NULL | stats_persistent=0 |                                         |
| innodb_table_stats        | InnoDB |      10 | Compact    |    4 |           4096 |       16384 |                  0 |            0 |         0 |           NULL | 2018-07-17 17:44:08 | NULL                | NULL                | utf8_bin          |     NULL | stats_persistent=0 |                                         |
| ndb_binlog_index          | MyISAM |      10 | Dynamic    |    0 |              0 |           0 |    281474976710655 |         1024 |         0 |           NULL | 2018-07-17 17:44:08 | 2018-07-17 17:44:08 | NULL                | latin1_swedish_ci |     NULL |                    |                                         |
| plugin                    | MyISAM |      10 | Dynamic    |    2 |             44 |          88 |    281474976710655 |         2048 |         0 |           NULL | 2018-07-17 17:44:08 | 2018-07-17 17:44:08 | NULL                | utf8_general_ci   |     NULL |                    | MySQL plugins                           |
| proc                      | MyISAM |      10 | Dynamic    |    0 |              0 |           0 |    281474976710655 |         2048 |         0 |           NULL | 2018-07-17 17:44:08 | 2018-07-17 17:44:08 | NULL                | utf8_general_ci   |     NULL |                    | Stored Procedures                       |
| procs_priv                | MyISAM |      10 | Fixed      |    0 |              0 |           0 | 239253730204057599 |         4096 |         0 |           NULL | 2018-07-17 17:44:08 | 2018-07-17 17:44:08 | 2018-07-17 17:44:08 | utf8_bin          |     NULL |                    | Procedure privileges                    |
| proxies_priv              | MyISAM |      10 | Fixed      |    2 |            693 |        1386 | 195062158860484607 |         5120 |         0 |           NULL | 2018-07-17 17:44:08 | 2018-07-17 17:44:08 | 2018-07-17 17:44:08 | utf8_bin          |     NULL |                    | User proxy privileges                   |
| servers                   | MyISAM |      10 | Fixed      |    0 |              0 |           0 | 433752939111120895 |         1024 |         0 |           NULL | 2018-07-17 17:44:09 | 2018-07-17 17:44:09 | NULL                | utf8_general_ci   |     NULL |                    | MySQL Foreign Servers table             |
| slave_master_info         | InnoDB |      10 | Compact    |    0 |              0 |       16384 |                  0 |            0 |         0 |           NULL | 2018-07-17 17:44:09 | NULL                | NULL                | utf8_general_ci   |     NULL | stats_persistent=0 | Master Information                      |
| slave_relay_log_info      | InnoDB |      10 | Compact    |    0 |              0 |       16384 |                  0 |            0 |         0 |           NULL | 2018-07-17 17:44:09 | NULL                | NULL                | utf8_general_ci   |     NULL | stats_persistent=0 | Relay Log Information                   |
| slave_worker_info         | InnoDB |      10 | Compact    |    0 |              0 |       16384 |                  0 |            0 |         0 |           NULL | 2018-07-17 17:44:09 | NULL                | NULL                | utf8_general_ci   |     NULL | stats_persistent=0 | Worker Information                      |
| slow_log                  | CSV    |      10 | Dynamic    |    2 |              0 |           0 |                  0 |            0 |         0 |           NULL | NULL                | NULL                | NULL                | utf8_general_ci   |     NULL |                    | Slow log                                |
| tables_priv               | MyISAM |      10 | Fixed      |    1 |            851 |        1702 | 239535205180768255 |         8192 |       851 |           NULL | 2018-07-17 17:44:10 | 2018-07-19 17:23:33 | 2018-07-17 17:44:10 | utf8_bin          |     NULL |                    | Table privileges                        |
| test                      | InnoDB |      10 | Compact    |    0 |              0 |       16384 |                  0 |            0 |         0 |           NULL | 2018-07-17 17:44:10 | NULL                | NULL                | latin1_swedish_ci |     NULL |                    |                                         |
| time_zone                 | MyISAM |      10 | Fixed      |    0 |              0 |           0 |   1970324836974591 |         1024 |         0 |              1 | 2018-07-17 17:44:11 | 2018-07-17 17:44:11 | NULL                | utf8_general_ci   |     NULL |                    | Time zones                              |
| time_zone_leap_second     | MyISAM |      10 | Fixed      |    0 |              0 |           0 |   3659174697238527 |         1024 |         0 |           NULL | 2018-07-17 17:44:11 | 2018-07-17 17:44:11 | NULL                | utf8_general_ci   |     NULL |                    | Leap seconds information for time zones |
| time_zone_name            | MyISAM |      10 | Fixed      |    0 |              0 |           0 |  55450570411999231 |         1024 |         0 |           NULL | 2018-07-17 17:44:11 | 2018-07-17 17:44:11 | NULL                | utf8_general_ci   |     NULL |                    | Time zone names                         |
| time_zone_transition      | MyISAM |      10 | Fixed      |    0 |              0 |           0 |   4785074604081151 |         1024 |         0 |           NULL | 2018-07-17 17:44:11 | 2018-07-17 17:44:11 | NULL                | utf8_general_ci   |     NULL |                    | Time zone transitions                   |
| time_zone_transition_type | MyISAM |      10 | Fixed      |    0 |              0 |           0 |  10696049115004927 |         1024 |         0 |           NULL | 2018-07-17 17:44:11 | 2018-07-17 17:44:11 | NULL                | utf8_general_ci   |     NULL |                    | Time zone transition types              |
| user                      | MyISAM |      10 | Dynamic    |   18 |            108 |        2488 |    281474976710655 |         2048 |       528 |           NULL | 2018-07-17 17:44:11 | 2018-07-19 23:37:06 | NULL                | utf8_bin          |     NULL |                    | Users and global privileges             |
+---------------------------+--------+---------+------------+------+----------------+-------------+--------------------+--------------+-----------+----------------+---------------------+---------------------+---------------------+-------------------+----------+--------------------+-----------------------------------------+
29 rows in set (0.00 sec)

查看索引的性能:Handler_read_key 值高表示索引效果好,Handler_read_rnd_next值高表示索引低效。

show global status like 'Handler_read%';

+-----------------------+-------+
| Variable_name         | Value |
+-----------------------+-------+
| Handler_read_first    | 6     |
| Handler_read_key      | 3     |
| Handler_read_last     | 0     |
| Handler_read_next     | 1     |
| Handler_read_prev     | 0     |
| Handler_read_rnd      | 0     |
| Handler_read_rnd_next | 567   |
+-----------------------+-------+
7 rows in set (0.00 sec)

(二)查找需要重新组织的表或索引。

当在表上插入、更新、删除记录行时,表中的数据需要重新组织,以便使索引、空间、记录等能更优化地存在。根据每个增加的表分析表结构和索引是否合理,不合理的话找相关人员修改。

(三)查找最活跃的10张表。(没有此项功能)

(四)将所有二进制日志文件归档处理。

这些日志文件需要每周做处理,保存以便将来调查分析,先压缩在删除,节省存储空间。(空闲时间维护)

二进制日志的删除:

删除所有日志文件

reset master;

删除mysql-bin.000002之前的文件

purge master logs to 'mysql-bin.000002';

删除定义时间之前的文件

purge master logs before '2018-07-21 20:35:00';

4、设置参数expire_logs_days=14,自动删除14天前的日志文件(不用,定期压缩日志,定期备份)

(五)注意检查并更新软件到新版本。

当系统平稳运行时,一般不需要升级或补丁自己的MySQL软件。可关注的MySQL的最新变化。

三、每月做的

(一)查找异常增长的指示器。

回顾表大小在过去的一个月时间里,增长了多少,发现特别消耗空间的表,以便提前做预处理。表大小=数据大小 + 索引大小;

SHOW TABLE STATUS FROM 数据库名 LIKE '数据表名';

show table status from mysql like 'user';

+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------+----------+----------------+-----------------------------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time         | Update_time         | Check_time | Collation | Checksum | Create_options | Comment                     |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------+----------+----------------+-----------------------------+
| user | MyISAM |      10 | Dynamic    |   18 |            108 |        2488 | 281474976710655 |         2048 |       528 |           NULL | 2018-07-17 17:44:11 | 2018-07-19 23:37:06 | NULL       | utf8_bin  |     NULL |                | Users and global privileges |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------+----------+----------------+-----------------------------+
1 row in set (0.00 sec)

select table_name,data_length/1024/1024/1024 as TB_DATA_LENGTH_GB from information_schema.tables order by TB_DATA_LENGTH_GB desc;

+----------------------------------------------------+-------------------+
| table_name                                         | TB_DATA_LENGTH_GB |
+----------------------------------------------------+-------------------+
| help_topic                                         |    0.000538047403 |
| help_keyword                                       |    0.000113568269 |
| slave_worker_info                                  |    0.000015258789 |
| slave_relay_log_info                               |    0.000015258789 |
| slave_master_info                                  |    0.000015258789 |
| innodb_table_stats                                 |    0.000015258789 |
| innodb_index_stats                                 |    0.000015258789 |
| test                                               |    0.000015258789 |
| test_log                                           |    0.000015258789 |
| test                                               |    0.000015258789 |
| test                                               |    0.000015258789 |
| help_relation                                      |    0.000010670163 |
| user                                               |    0.000002317131 |

(二)根据增长适当规划数据库系统的扩张问题。

比较你收集到的处理器、内存、以及磁盘利用率等系统级信息,规划MySQL数据库对象今后扩展的对策。

常用的MYSQL维护工具介绍

操作ORACLE的时候,一般都是通过plsql dev对数据库进行维护,最近在学习MYSQL,也研究了下MYSQL的一些常用的维护工具,我觉得用得最多的工具应该是下面这5个,先记录下来,后续挨个比较下。

1.Navicat

Navicat是一个桌面版MySQL数据库管理和开发工具。和微软SQLServer的管理器很像,易学易用。Navicat使用图形化的用户界面,可以让用户使用和管理更为轻松。支持中文,有免费版本提供。

2.SQLyog

SQLyog是业界著名的Webyog公司出品的一款简洁高效、功能强大的图形化MySQL数据库管理工具。使用SQLyog可以快速直观地让您从世界的任何角落通过网络来维护远端的MySQL数据库。

3.mysql-front

一款小巧的管理Mysql的应用程序.主要特性包括多文档界面,语法突出,拖拽方式的数据库和表格。可编辑/可增加/删除的域,可编辑/可插入/删除的记录,可显示的成员,可执行的SQL 脚本,提供与外程序接口,保存数据到CSV文件等。

4.phpMyAdmin

phpMyAdmin 是一个以PHP为基础,以Web-Base方式架构在网站主机上的MySQL的数据库管理工具,让管理者可用Web接口管理MySQL数据库。借由此Web接口可以成为一个简易方式输入繁杂SQL语法的较佳途径,尤其要处理大量资料的汇入及汇出更为方便。其中一个更大的优势在于由于phpMyAdmin跟其他PHP程式一样在网页服务器上执行,但是您可以在任何地方使用这些程式产生的HTML页面,也就是于远端管理MySQL数据库,方便的建立、修改、删除数据库及资料表。也可借由phpMyAdmin建立常用的php语法,方便编写网页时所需要的sql语法正确性。

5.MySQL GUI Tools

MySQL GUI Tools是MySQL官方提供的图形化管理工具,功能很强大,值得推荐,可惜的是没有中文界面,提供了四个非常好用的图形化应用程序,方便数据库管理和数据查询。这些图形化管理工具可以大大提高数据库管理、备份、迁移和查询以及管理数据库实例效率,即使没有丰富的SQL语言基础的用户也可以应用自如

MySql常用维护命令8

内容摘要:

本篇主要是对项目运行过程中会产生的一些数据维护,更新,参数设置等常用操作的记录和总结,方面在运用是有个参考。主要内容会涉及可参考目录简介。本编包含后8-10章节。本篇主要介绍数据的备份和恢复。

目录简介:

1.    数据库启停及状态检查

2.    CREATE操作项目

3.    ALTER操作项目

4.    数据库参数查看和设置

5.    客户端权限管理

6.    事件调度/临时触发器/定制任务

7.    触发器、存储过程

8.    数据备份和恢复

9.    数据库表空间文件维护

10.  性能优化

标签:

MySql,Create,Alter,ShowParameter,Event,Trigger,Procedure,Privilige,mysqldump,source

8.  数据备份和恢复

一:备份的作用

1.灾难恢复:硬件故障、一个不经意的bug导致数据损坏或者服务器机器数据由于某些原因不可获取或者无法使用

2.人们改变想法:例如删除数据后又想恢复这些数据

3.测试:基于实际数据来测试的方法是,定期用最新的生产环境数据更新测试服务器。

二:备份策略

1.首先要确定是事务性还是非事务性,两种不同的存储引擎备份方式在处理数据一致性方面是不一样的;

2.确定使用全备份还是增量备份;

3.可以采用复制的方法做异地备份,但是,复制不能代替备份,它对数据库的误操作也无能为力;

4.要定期的做备份,备份的周期要充分考虑系统可以承受的恢复时间,备份要在系统负载较小的时候进行;

5.确保MySQL打开log-bin选项,有了BINLOG,MySQL才可以在必要的时候做完整恢复,或基于时间点的恢复,或基于位置的恢复。

三:备份种类

1.离线备份

离线备份,是关闭MySQL做备份,是一种简单而且安全的备份方法。它不用关注InnoDB缓冲池中的脏页或者其他缓存。也不需要担心数据在尝试备份的过程中被修改,并且因为服务器不对应用提供访问,所以可以很快的完成备份,但是在高负载和高并发下对MySQL进行关闭和重启的时间还是无法容忍的,这会导致昂贵的代价。

2.在线备份

在线备份是不需要生产服务器停机的备份。但是由于一致性的要求,对服务器进行在线备份的时候仍然会有明显的服务中断。MyISAM引擎的数据库,一般系统会使用FLUSH TABLES WITH READ LOCK操作,这会导致MySQL关闭并锁住所有的表,将MyISAM的数据文件刷新到磁盘上,并且刷新查询缓存。

3.逻辑备份

逻辑备份是将数据导出到相应的文件中,以一种MySQL能够解析的形式进行保存。

逻辑备份的优点:

1. 可以使用编辑器像grep和sed之类的命令查看和操作的普通文件;

2. 可以通过网络来备份和恢复;

3. 与存储引擎无关;

4. 有助于避免数据损坏。

逻辑备份的缺点:

1. 必须由数据库服务器生成逻辑备份的工作,会消耗很多的CPU周期;

2.逻辑备份在某些场景下比数据库文件本身更大;

3.从逻辑备份中还原需要MySQL加载与解释语句,转化为存储格式,并重建索引,所有这一切会很慢。

4.物理备份

物理备份是直接复制原始文件的方式进行备份。原始文件是指存在于硬盘上的文件。

物理备份的优点:

1. 基于文件的物理备份,只需要将需要的文件复制到其他地方即可完成备份。不需要其他额外的工作来生成原始文件。

2. 从物理备份中恢复比较快速,因为MySQL服务器不需要执行任何SQL或构建索引。

物理备份的缺点:

1. InnoDB的原始文件通常比相应的逻辑备份要大很多;

2. 物理备份不总是可以跨平台、操作系统及MySQL版本。

5.混合备份

建议混合使用物理和逻辑两种方式来做备份:先使用物理复制,以此数据启动MySQL服务器实例并运行mysqlcheck。

6.增量备份

增量备份是自从任意类型的上次备份后所有修改做的备份。增量备份对减少服务器开销、备份时间及备份空间而言都很适合。

增量备份的缺点包括增加恢复复杂度,额外的风险,以及更长的恢复时间。如果可以做全备,考虑到简便性,做好使用全备份。

四:一致性

数据一致性

在线备份,需要所有的相关表的一致性备份。如果使用的不是事务型存储引擎,需要在备份时候使用LOCK TABLES来锁住所有要一起备份的表,备份完成后再释放锁。InnoDB需要在服务器上使用REPEATABLE READ事务隔离级别,并且没有任何DDL以及基于时间点的数据快照,切回备份过程中不会阻塞任何后续的工作。

复制

复制不是备份。备库对生成备份是一个干涉较少的源,但它不是备份本身。对于RAID卷,SAN和文件系统快照,也同样如此。从备库中备份最大的好处是可以不干扰主库,避免在主库上增加额外的负载。

五:备份内容

1.    物理备份

1.1生成物理备份

MySQL中的每一个数据库和数据表分别对应文件系统中的目录和其下的文件。在Linux下数据库文件的存放目录一般为/var/lib/mysql。在Windows下这个目录视MySQL的安装路径而定,DiaHosting的技术员一般为客户安装在D:\server\soft\mysql下。如,有一个名为bbs的数据库,那么bbs的数据库文件会存放在/var/lib/mysql/bbs(linux)或者D:\server\soft\mysql\bbs(Windows)下。

物理备份主要是备份数据(包括表,索引,视图等逻辑对象所在的物理文件)文件到备份目录,以便需要恢复时使用。备份按照冷备和热备介绍。

冷备份

冷备份就是停掉数据库服务,cp数据文件的方法,这种方法对MyISAM和InnoDB存储引擎都适合。但是一般很少用,因为很多应用是不允许长时间停机的。进行备份的操作是:暂停MySQL服务,在操作系统级别备份MySQL的数据文件和日志文件到备份目录。

备份文件前,需要将MySQL服务停止,然后将数据库目录拷贝即可。

热备份

1.MyISAM存储引擎

MyISAM存储引擎的热备份是有很多方法,但是其实质就是将要备份的表加读锁,然后再cp数据文件到备份目录。

方法一:使用mysqlhotcopy工具

mysqlhotcopy是MySQL自带的一个热备份工具,使用方法很简单:这个工具是不赞成的,在MySQL 5.6.20,在MySQL 5.7被删除了。

shell>mysqlhotcopy db_name[/path/to/new_directory]

方法二:手工锁表copy

首先数据库中所有表加读锁

flush tables with read lock;

然后cp数据文件到备份目录即可。完成之后,执行unlock tables;解锁。

2.InnoDB存储引擎

Percona XtraBackup工具是InnoDB进行热备份的工具。它是开源并且免费的,除了核心备份工具外,还有一个用Perl写的封装脚本,可以提供更多高级功能,它支持类似流、增量、压缩和多线程备份操作。也有许多特别的功能,用以降低在高负载的系统上备份的影响。

1.2物理备份恢复

物理备份的恢复是针对备份的反向过程,需要两个步骤。针对冷热恢复区别只是在于对物理文件恢复时数据服务是否启动。

1.    将备份的数据库目录中的文件还原回数据系统所在的数据库文件目录,数据还原到物理备份点。

2.    使用mysqlbinlog工具恢复自备份以来的所有BINLOG。(为了保证数据的一致性和可恢复到备份点到当前时间内的任一时间段。这个就是为什么要打开binlog的原因)

在对BINLOG恢复时,可以更精确的控制还原点,参考如下:

时间点恢复:

1. 如果上午 10点发生了误操作,可以用以下语句用备份和 binglog将数据恢复到故障前:

mysqlbinlog --stop-date="2015-04-20 9:59:59"

/var/log/mysql/bin.123456 |mysql -u root -p mypwd

2. 跳过故障时的时间点,继续执行后面的 binlog,完成恢复

mysqlbinlog --start-date="2015-04-20 10:01:00"

/var/log/mysql/bin.123456 |mysql -u root -p mypwd \

位置恢复:

和时间点恢复类似,但是更精确,步骤如下:

mysqlbinlog --start-date="2015-04-20 9:55:00" --stop-date="2015-04-20 10:05:00" /var/log/mysql/bin.123456 > /tmp/mysql_restore.sql

该命令将在/tmp目录创建小的文本文件,编辑此文件,找到出错语句前后的位置号,例如前后位置号分别是368312 和368315。恢复了以前的备份文件后,你应从命令行输入下面内容:

mysqlbinlog --stop-position="368312" /var/log/mysql/bin.123456 \
|mysql -u root -p mypwd

mysqlbinlog --start-position="368315" /var/log/mysql/bin.123456 \
|mysql -u root -p mypwd \

上面的第1行将恢复到停止位置为止的所有事务。下一行将恢复从给定的起始位置直到二进制日志结束的所有事务。因为mysqlbinlog 的输出包括每个SQL 语句记录之前的SET TIMESTAMP 语句,恢复的数据和相关MySQL 日志将反应事务执行的原时间。

2.    逻辑备份

2.1生成逻辑备份

有两种类型的逻辑备份:SQL导出和符号分割文件。

SQL导出

我们一般使用mysqldump方式进行SQL导出的操作。如下图是使用默认参数的mysqldump得到的输出结果。导出数据包括表结构和数据,都以有效的SQL命令形式写出。其中参数-l表示给所有表加一个读锁,-F表示生成一个新的日志文件。

备份单个库:mysqldump -u root -p --set-gtid-purged=OFF mysql -F > /home/mysql.sql

备份某些表:mysqldump -u root -p --set-gtid-purged=OFF mysql user db > /home/mysql.user_db.sql

备份多个库:mysqldump -u root -p --set-gtid-purged=OFF --databases mysql sbtest > /home/mysql_sbtest.sql

备份所有库:mysqldump -u root -p --set-gtid-purged=OFF --all-databases > /home/all-databases.sql

备份数据库结构:mysqldump -u root -p --set-gtid-purged=OFF --no-data --databases mysql sbtest > /home/no-data-mysql-sbtest.sql

SQL还原

方法1.

mysqldump -u root -p mysql < /home/mysql.sql

方法2.

mysql -u root -p

use mysql;

source /home/mysql.sql;

符号分割文件备份

使用SQL命令SELECT INTO OUTFILE以符号分隔文件格式创建数据的逻辑备份。符号分隔文件包含以ASCII展示的原始数据,没有SQL、注释和列名。

select * into outfile '/home/xiaoboluo.test.txt' fields terminated by ',' optionally enclosed by '"' lines terminated by '\n' from xiaoboluo.test;

ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

符号分割文件还原

如果是通过SELECT INTO OUTFILE导出的符号分隔文件,可以使用LOADDATA INFILE通过相同的参数来加载,也可以使用mysqlimport,这是LOADDATA INFILE的一个包装,这种方式依赖命令约定决定从哪里加载一个文件的数据。

Mysql>loaddata infile '/tmp/user.txt'

->into datacrawldb.users_user

->fields terminated by ',' optionallyenclosed by '"'

->lines terminated by '\n'

mysqlimport可以单独查询相关资料

注:不管是逻辑备份还是物理备份,恢复时只能恢复到备份点。若在备份点之后的某个时间出现误操作要基于时间点恢复,需要用到BINLOG作为备份恢复的辅助。

MySQL日常维护(超级大杂烩)相关推荐

  1. MySQL日常维护工具-备份

    目录 1.mysql字符集 1.1.字符集介绍 1.2.MySQL数据库常见字符集介绍 1.3.MySQL怎样选择合适的字符集 1.4.查看MySQL支持的字符集 1.5.查看MySQ当前的字符集设置 ...

  2. MySQL Cluster 日常维护

    在前面几篇文章已经详细介绍了MySQL Cluster的搭建,配置讲解.而且相信大家都掌握了基本用法.现在我们来看看Cluster的日常维护.熟悉日常维护,将有助于工作中更好的管理和使用Cluster ...

  3. mysql维护 运维_MySQL运维之--日常维护操作

    MySQL运维之--日常维护操作 http://blog.csdn.net/guoyjoe/article/details/46697825 一.Linux内核和发行版本 uname -a cat / ...

  4. MHA 日常维护命令集

    MHA 日常维护命令集 1.查看ssh登陆是否成功 masterha_check_ssh --global_conf=/etc/masterha/masterha_default.conf --con ...

  5. 3个最常见案例详解DBA日常维护

    导读:DBA的大部分工作都是围绕着对数据库的维护而展开的,常规的日常维护更是占了绝大多数.本节将围绕日常维护中最常见的三个案例展开讲解,与大家分享排查此类问题的思路. 作者:叶桦 徐浩 张梦颖 应以峰 ...

  6. 集群资源分配_推荐一款MySQL日常运维和集群管理的自动化平台--Arkcontrol

    概述 今天主要推荐Arkcontrol这个平台,比inception还要强大,目前主要是用在mysql上,如果大家有玩mysql的话,不烦一起来看看吧~ Arkcontrol Arkcontrol是极 ...

  7. 交换机服务器维护,网络交换机日常维护技巧

    网络交换机日常维护技巧 网络交换机,是一个扩大网络的器材,能为子网络中提供更多的连接端口,以便连接更多的计算机.随着通信业的发展以及国民经济信息化的推进,网络交换机市场呈稳步上升态势.下面给大家介绍网 ...

  8. IBM小型机日常维护命令

    一:开机.关机命令 1.开机    1)在开机之前,先检查电源是否插好:然后,按下前面板上白色电源开关后,主机会进入硬件自检和引导阶段:       此时,前面板上的液晶会有代码跳动,每一个代码表示自 ...

  9. 网众无盘不能和主服务器同步,无盘系统日常维护与.doc

    无盘系统日常维护与 常见故障(网众) 工作原理: 用一块启动芯片来远程引导:而今大多数主板都集成千兆网卡并带有启动代码,目前网众无盘可以完美兼容任何一款集成千兆网卡.因为还原机制不同,每次客户机重起时 ...

最新文章

  1. 使用VB.NET加快代码开发速度
  2. Mysql如何创建短索引(前缀索引)
  3. 从JavaScript数组获取随机值
  4. python 内建比较函数详解
  5. Git根据远程分支建立条新的远程分支
  6. SqlServer-COMPUTE BY
  7. 软件开发过程中的思维方式 -- 如何分析问题
  8. Springboot实现邮件发送(2020最新版)
  9. 大型网站技术架构(六)--网站的伸缩性架构(转)
  10. 修改mac地址_交换机工作基础——MAC地址表的构成与安全
  11. python深度学习第二讲——用python写深度学习损失函数
  12. 人跟人的格局真的是不一样的
  13. 经典实用数据库新书推荐-关于mysql和oracle【转孟光】
  14. 设备log导入oracle,oracle imp 导入数据库出错 请看log!
  15. matlab调用system,求助 system函数用法要点
  16. SSM流程及核心原理
  17. html5网页制作的基本步骤,网页制作流程介绍
  18. 原来苹果也自带语音输入功能,快速的语音输入方法,日常都能用到
  19. PLsql oracle 误删除 恢复
  20. 共享经济-共享汽车市场调研报告

热门文章

  1. markdown/latex 教程大归纳
  2. Image Optimizer Pro - Compres‪s for Mac(简单易用的图像压缩器)
  3. 综合案例-智能无人超市
  4. java socket简,javasocket简单示例
  5. 7-28 猴子选大王 (20 分),从中学习约瑟夫环
  6. hbo流媒体地址大全_为什么HBO有这么多的流媒体服务?
  7. 嵌入式课程 之 定时器实验
  8. 2021人大附中高考成绩查询,人大附中2020-2021年度学科竞赛成绩出炉!学霸聚集地!...
  9. 《中台架构与实现》读书笔记
  10. FSL——FLIRT使用配准与降采样 registration and resample