mysql常用脚本记录

-- select * from information_schema.processlist 
show processlist; -- 查看用户链接  show full processlist; kill id;
/**
     查看状态
   Connections,试图连接到(不管是否成功)MySQL服务器的连接数。
   Max_used_connections,服务器启动后已经同时使用的连接的最大数量。
   Threads_connected,当前的连接数。
 */
show status like '%Connections%';

show variables like '%connect%'; -- max_connections,最大连接数

-- 重置计数器 max_connection_errors 错误连接数
FLUSH HOSTS;

/**
1、MySQL查询次数(status)
Com_select;Com_update;Com_insert;Com_delete;Com_change_db

2、查询缓存空间大小:query_cache_size(variables)
查询缓存最大查询数据集大小:query_cache_limit(variables);
缓存中的查询个数:Qcache_inserts(status);
查询缓存命中率:(Qcache_hits/(Qcache_hits+Qcache_inserts))*100% (status)

3、索引缓存命中率
索引缓存空间大小:key_buffer_size (variables)
索引缓存命中率:(Key_reads/Key_read_requests)*100% (status)

4、并发连接数
最大充许连接数:max_connections(variables)
实际最大连接数:max_used_connections(status)
当前连接数:Threads_connected(status)
活跃连接数:Threads_running(status)
缓存连接数:Threads_cache(status)

5、流量统计(status)
Bytes_received ,Bytes_sent(status)

6、连接次数
每秒连接次数:Connections(status)
每秒实际创建连接次数:Threads_created(status)

7、表锁定统计
立即释放的表锁数:Table_locks_immediate(status)
需要等待的表锁数:Table_locks_waited(status)
*/

EXPLAIN 优化语句

-- 创建用户 privileges - 用户的操作权限,如SELECT , INSERT , UPDATE .如果要授予所的权限则使用ALL.;databasename - 数据库名,tablename-表名,如果要授予该用户对所有数据库和表的相应操作权限则可用*表示, 如*.*. 
GRANT privileges ON databasename.tablename TO 'username'@'host'; 

-- 用以上命令授权的用户不能给其它用户授权,如果想让该用户可以授权,用以下命令: 
GRANT privileges ON databasename.tablename TO 'username'@'host' WITH GRANT OPTION; 

GRANT ALL ON xz.* TO 'xz'@'192.168.%' WITH GRANT OPTION;
GRANT ALL ON xz.* TO 'xz'@'localhost' WITH GRANT OPTION;

-- 设置密码
SET PASSWORD FOR 'xz'@'192.168.18.%' = PASSWORD("xz"); 
SET PASSWORD FOR 'xz'@'localhost' = PASSWORD("xz"); 

flush privileges;

my.cnf
max_connections
  最大并发连接数。当MySQL的并发连接达到这个设定值时,新的连接将会被拒绝。当发现MySQL有能力处理更多的并发的时候, 建议调大这个值,相应给服务器带来更高的负载(CPU/IO/内存)。
  默认值:100, 参考设置:900

back_log
  TCP/IP连接队列的最大值。当MySQL同时有大量连接请求的时候,MySQL会尝试用当前现有的线程处理这些请求,如果处理不过来,MySQL会把连接先放到一个队列里面,然后起新的线程处理。这个过程会很快, 但是并发请求很多的话,需要调高这个值,否则新来的连接请求会被拒绝。在一次压测的时候发现客户端返回大量的“Lost connection to MySQL”, 就是因为back_log的默认值太小导致的。增大这个值会增大CPU负载并消耗更多的内存。
  默认值:50, 参考设置:200

skip-name-resolve
  关闭反向域名解析。MySQL默认会对每个客户端连接作反向域名解析,强烈建议关闭反向域名解析。关闭的方法是在my.cnf里面加一行skip-name-resolve

innodb_file_per_table
如果使用innodb, 强烈建议打开这个设置,否则所有的innodb表共享一个文件,并且这个文件的大小不会因为表数据的减少而减小,时间长了会把磁盘搞爆,这是mysql的一个bug:http://bugs.mysql.com/bug.php?id=1341

max_connect_errors
  当客户端连接服务端超时(超过connect_timeout), 服务端就会给这个客户端记录一次error,当出错的次数达到max_connect_errors的时候,这个客户端就会被锁定。除非执行FLUSH HOSTS命令。绝对是个地雷!
  默认值:10, 参考设置:1844674407370954751(能设多大,设多大)

connect_timeout
  连接超时的秒数。
  默认值:5, 参考设置:15
  
slave_net_timeout
  MySQL主从复制的时候, 当Master和Slave之间的网络中断,但是Master和Slave无法察觉的情况下(比如防火墙或者路由问题)。Slave会等待slave_net_timeout设置的秒数后,才能认为网络出现故障,然后才会重连并且追赶这段时间主库的数据。默认是3600秒,相信一个小时之后,黄花菜都凉了。
  默认值:3600, 参考设置:30

wait_timeout
  连接过期秒数。当一个连接SLEEP超过wait_timeout秒后,MySQL服务端会中断这个连接。这个值设置的过长有可能会导致大量的SLEEP链接占用系统资源,过小会导致“MySQL has gone away”的错误。
  默认值:28800, 参考设置:288000

key_buffer
  主键缓存。如果发现有大量的slow log,可以尝试调高这个值,相应会带来更高的内存开销。

table_cache
  给经常访问的表分配的内存。调大这个值,一般情况下可以降低磁盘IO, 但是相应会占用更多的内存。


导出sql脚本
mysqldump -u 用户名 -p 数据库名 > 存放位置
mysqldump -u root -p test > c:/a.sql

--no-create-info-t 
只导出数据,而不添加 CREATE TABLE 语句。

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

--opt 
这只是一个快捷选项,等同于同时添加 --add-drop-tables --add-locking --create-option --disable-keys --extended-insert --lock-tables --quick --set-charset 选项。本选项能让 mysqldump 很快的导出数据,并且导出的数据能很快导回。该选项默认开启,但可以用 --skip-opt 禁用。注意,如果运行 mysqldump 没有指定 --quick 或 --opt 选项,则会将整个结果集放在内存中。如果导出大数据库的话可能会出现问题。

--quick,-q 
该选项在导出大表时很有用,它强制 mysqldump 从服务器查询取得记录直接输出而不是取得所有记录后将它们缓存到内存中。

--routines,-R 
导出存储过程以及自定义函数。



导入sql脚本 
mysqldump -u 用户名 -p 数据库名 < 存放位置
mysqldump -u root -p test < c:/a.sql




1.只查看第一个binlog文件的内容 
show binlog events;

2.查看指定binlog文件的内容 
show binlog events in 'mysql-bin.000002' from 123 limit 1,2;

3.查看当前正在写入的binlog文件 
show master status\G

4.获取binlog文件列表 
show binary logs;


5.导出sql
mysqlbinlog  binlog.001128 binlog.001129 binlog.001130 --start-datetime='2015-12-09 00:00:00' --stop-datetime='2015-12-18 18:00;00' --database=xz > /backup/xz_log.sql | mysql -uroot -p 

6.过滤sql
  less xz_log.sql |grep  -i -E 'insert|update|delete' -C2 |grep  -i dbk_hotcommon
  导出直接过滤)
  mysqlbinlog  binlog.001130 --start-datetime='2015-12-09 00:00:00' --stop-datetime='2015-12-18 18:00;00' --database=xz |grep -i -w insert -C2 |grep -i -w dbk_hotcommon > /backup/xz_log_insert.sql | mysql -uroot -p

分区表维护脚本

-- 删除分区
alter table sens_sensitive drop partition pm;
-- 增加分区
alter table sens_sensitive add partition (partition p6 values less than (2,'2014-06-01 00:00:00'));

-- 查询分区状况
select table_name,partition_name,partition_description from information_schema.partitions where table_schema = 'fwpt'

-- 重建分区: 这和先删除保存在分区中的所有记录,然后重新插入它们,具有同样的效果。它可用于整理分区碎片。 
alter table t1 rebuild partition p0, p1;

-- 分析分区:读取并保存分区的键分布。
alter table t1 analyze partition p3;

-- 修补分区: 修补被破坏的分区。  
alter table t1 repair partition p0,p1;

-- 检查分区: 可以使用几乎与对非分区表使用check table 相同的方式检查分区。  
alter table sens_sensitive check partition p1_201312;

-- 优化分区:如果从分区中删除了大量的行,或者对一个带有可变长度的行(也就是说,有varchar,blob,或text类型的列)作了许多修改,可以使用“alter table ... optimize partition”来收回没有使用的空间,并整理分区数据文件的碎片。 
-- 在一个给定的分区表上使用“optimize partition”等同于在那个分区上运行check partition检查分区,analyze partition分析分区,和repair partition修补分区。
alter table sens_sensitive optimize partition p1_201312,p1_201401;

自动扩展分区-存储过程脚本

-- delimiter $$ -- 命令解释器,默认是分号,根据实际情况使用
drop procedure if exists create_partition;  -- $$
create procedure create_partition (in databasename varchar(50),in tablename varchar(50))  
l_end:begin 
        declare max_partition_description varchar(255) default 0;  -- 存储分区表达式字符串
        declare max_partition_description_date varchar(255) default 0;  -- 存储日期表达式部分
        declare max_partition_description_organid varchar(255) default 0;  -- 存储机构部分
        declare p_name varchar(255) default 0; -- 分区命名
        declare p_description varchar(255) default 0; -- 分区表达式
        declare partition_name_delete varchar(100); -- 不存在机构,将要被删除的分区
        declare i int default 1; -- 循环变量
    declare stop int default 0; -- 游标停止标识

        -- 查询无效分区,机构不存在的
        declare cur_delete cursor for (select partition_name from information_schema.partitions where table_schema = databasename and table_name = tablename and not exists(select 1 from sys_department where departmentlevel = 1 and partition_description like concat(departmentid,',%') limit 1 ));
        -- 查询所有机构分区
    declare cur cursor for (select p.* from (select max(partition_description) from information_schema.partitions where table_schema = databasename and table_name = tablename and exists ( select 1 from sys_department where departmentlevel = 1 and partition_description like concat(departmentid, ',%') limit 1)group by substr(partition_description,1,position(',' in partition_description)) union select concat(departmentid,',\'1999-09-09 00:00:00\'')  from sys_department where departmentlevel = 1 and not exists(select 1 from information_schema.partitions where partition_description like concat(departmentid, ',%') and  table_schema = databasename and table_name = tablename limit 1)) p );

    declare continue handler for sqlstate '02000' set stop=1; -- 循环结束控制

        /**   清理已删除、不存在的机构的数据分区  **/
    open cur_delete; -- 开启游标
    fetch cur_delete into partition_name_delete; -- 第一个要删除的分区
    while stop <> 1 do
                if partition_name_delete is not null then
           set @del_sql=concat('alter table ',tablename,' drop partition ',partition_name_delete); -- 组织删除分区语句
           select @del_sql; -- 输出删除脚本
                     /** 执行删除 **/
           prepare stmt1 from @del_sql;
           execute stmt1;
           deallocate prepare stmt1;
                end if;
        fetch cur_delete into partition_name_delete; -- 下一个删除的分区
    end while;
    close cur_delete;


        /**** 拓展分区 ****/
    set stop = 0;
    open cur; -- 开启游标
    fetch cur into max_partition_description; -- 第一个处理数据
    while stop <> 1 do

                -- 机构id部分
                set max_partition_description_organid = substr(max_partition_description,1,position("," in max_partition_description) - 1);
                -- 时间分区部分
                set max_partition_description_date = substr( max_partition_description,(position("," in max_partition_description)+2),19);

                -- 分区表还剩余3个月分区时才创建分区
                if max_partition_description_date > adddate(now(), interval 3 month) then  
                    select concat("organid ",max_partition_description_organid," partition table is enough...") as "***info*****************************";
                else
                    set i = 0;
                    while i <= 6 do -- 拓展6个月
                        if max_partition_description_date < now() then
                            -- 最大分区已经小于当前时间,从当前月开始分区
                            set max_partition_description_date = substr(now(),1,10);
                        end if;

                        -- 分区名称p+机构id+年月 (年月是上限,实际数据是上一月)
                        set p_name = concat('p',max_partition_description_organid,'_',substr(replace(max_partition_description_date, '-', ''),1,6)); 

                        -- 设置新月份+1
                        set max_partition_description_date = adddate(max_partition_description_date, interval 1 month);

                        -- 循环创建6个分区-每次+1月(年月是上限,实际数据是上一月)
                        set p_description = concat(max_partition_description_organid,',\'',substr(max_partition_description_date,1,8),'01 00:00:00\'');
                        set @s=concat('alter table ',tablename,' add partition  (partition ',p_name,' values less than (',p_description,'))');  
                        select @s as "***info*****************************";
                        prepare stmt2 from @s;  
                        execute stmt2;  
                        deallocate prepare stmt2;  
                        set i = i + 1 ;  
                    end while;
                end if; 

        fetch cur into max_partition_description; -- 下一个处理数据
    end while;
    close cur;


end l_end;  -- $$
-- delimiter ;

自动扩展事件脚本

DELIMITER || 
CREATE EVENT auto_set_partitions ON SCHEDULE EVERY 15 DAY DO -- 15天执行一次

BEGIN
    CALL create_partition ( 'fwpt' , 'sens_sensitive'); -- 敏感信息数据表
  CALL create_partition ( 'fwpt' , 'sens_sensitive_wb'); -- 微博信息数据表
  CALL create_partition ( 'fwpt' , 'issue_yq_info_doc'); -- 话题相关文档表
  CALL create_partition ( 'fwpt' , 'issue_wb_info_doc'); -- 话题相关文档表
END; || 
DELIMITER || 

猜你喜欢

转载自blog.csdn.net/slzs_zyt/article/details/59093107