Mysql检查表进行repair、optimize

来源:互联网 发布:usb端口检测软件 编辑:程序博客网 时间:2024/04/25 12:12

有时候服务器突然断电之类的,然后mysql表坏掉了,可能还不止一个,再然后repair了一个又一个,然后手动去repair是肯定很不理想的,还是用脚本解决吧:

Shell脚本如下:

  1. #!/bin/bash
  2.  
  3. host_name=192.168.10.3
  4. user_name=lucky
  5. user_pwd=123.com
  6. database=my_db_name
  7. need_optmize_table=true
  8. tables=$(mysql -h$host_name -u$user_name -p$user_pwd $database -A -Bse "show tables")
  9.  
  10. for table_name in $tables
  11. do
  12. check_result=$(mysql -h$host_name -u$user_name -p$user_pwd $database -A -Bse "check table $table_name" | awk '{ print $4 }')
  13. if [ "$check_result" = "OK" ]
  14. then
  15. echo "It's no need to repair table $table_name"
  16. else
  17. echo $(mysql -h$host_name -u$user_name -p$user_pwd $database -A -Bse "repair table $table_name")
  18. fi
  19.  
  20. # 优化表,可提高性能
  21. if [ $need_optmize_table = true ]
  22. then
  23. echo $(mysql -h$host_name -u$user_name -p$user_pwd $database -A -Bse "optimize table $table_name")
  24. fi
  25. done

Php脚本如下:

  1. <?php
  2. while(1){
  3.     $link = mysql_connect('192.168.10.3:3306','user','password');
  4.     $sql = "show slave status";
  5.     $result = mysql_query($sql,$link);
  6.     $row = mysql_fetch_assoc($result);
  7.     $error_no = $row['Last_SQL_Errno'];
  8.     if($error_no == 0)
  9.     {
  10.         sleep(10);
  11.          continue;
  12.     }
  13.     $string = $row['Last_SQL_Error'];
  14.     $Table = preg_match('/Table/',$string);
  15.     $Duplicate = preg_match('/*.Duplicate.*/i',$string);
  16.     $Incorrect = preg_match('/Incorrect key file for table/i',$string);
  17.     if($Incorrect){
  18.         $pattern_db = '/.*Incorrect.*.\/(\w+)\/(\w+).*/';
  19.         preg_match($pattern_db,$string,$match);
  20.         $db=$match[1];
  21.         $table=$match[2];
  22.     }
  23.     if($Table){
  24.         $pattern = '/.*database:\s\'(\w+).*Query:\s\'\w+\s(\w+).*/';
  25.         preg_match($pattern,$string,$match);
  26.         $db = $match[1];
  27.         $pattern = '/.*Table\s\'(\w+).*Query:\s\'\w+\s\w+\s(\w+).*/';
  28.         preg_match($pattern,$string,$match);
  29.         $table = $match[1];
  30.     } else{
  31.         $update = preg_match('/*.update.*/i',$string);
  32.         if($update){
  33.             $pattern = '/.*database:\s\'(\w+).*Query:\s\'\w+\s(\w+).*/';
  34.         }else{
  35.             $pattern = '/.*database:\s\'(\w+).*Query:\s\'\w+\s\w+\s(\w+).*/';
  36.         }
  37.         preg_match($pattern,$string,$match);
  38.         $db = $match[1];
  39.         $table = $match[2];
  40.     }
  41.     $repair_sql = "repair table $db.".$table;
  42. var_dump($repair_sql);
  43.     mysql_query($repair_sql,$link);
  44.     mysql_query("start slave",$link);
  45. }

 


0 0
原创粉丝点击