zoukankan      html  css  js  c++  java
  • python备份mysql数据库

    介绍使用python结合mysqldump对mysql数据库进行备份

    import os
    import sys
    import configparser
    import time
    
    def test_file_path(fp):
      if not os.path.exists(fp):
        raise RuntimeError('file {} not found'.format(fp))
    
    def backup_mysqldb(backup_param):
      test_file_path(backup_param['mysql']['dump'])
      test_file_path(backup_param['bak']['cmd_zip'])
      cmd1 = '{dump} -u{user} -p{password} -h{hostip} 
      -P{port} {dbname}'.format(**backup_param['mysql'])
      print(cmd1)
      backup_name = time.strftime('mysqlbackup%Y%m%d_%H%M%S')
      backup_param['bak']['backup_name'] = backup_name
      cmd2 = backup_param['bak']['cmd_bak'].format(**backup_param['bak'])
      print(cmd2)
      cmd = cmd1 + ' | ' + cmd2
      print(cmd)
      os.system(cmd)
    
    def del_old_backup(backup_param):
      backup_path = backup_param['bak']['backuppath']
      print(int(backup_param['bak']['keepday']))
      t = time.time() - int(backup_param['bak']['keepday']) * 24 * 60 * 60
      last_day = time.strftime('%Y%m%d', time.localtime(t))
      for fn in os.listdir(backup_path):
        fp = os.path.join(backup_path, fn)
        print(fp)
        if os.path.isfile(fp):
          file_day = get_time_from_name(fn)
          print(file_day, last_day)
          if file_day < last_day:
            print('del file ', fn)
            os.remove(fp)
    
    def get_time_from_name(fn):
      # mysqlbackup20140211_172713.7z
      import re
      pattern = r'.*(d{8})_d*'
      m = re.match(pattern, fn)
      return m.group(1)
      
    if __name__ == '__main__':  
      current_dir = sys.argv[0]
      current_dir = os.path.abspath(current_dir)
      current_dir = os.path.dirname(current_dir)
      os.chdir(current_dir)
      print(os.getcwd())
      config = configparser.ConfigParser()
      config.read_file(open(current_dir + r'config.ini'))
      for k,v in config.items():
        for k1,v1 in v.items():
          print('{}
        {}:{}'.format(k, k1, v1))
      backup_mysqldb(config)
      del_old_backup(config)
    
    

    配置文件

    [mysql]
    hostip=localhost
    user=root
    password=12345
    port=3306
    dbname=test
    dump=path_to_mysqldump.exe
    [bak]
    cmd_zip=.7z.exe
    cmd_bak={cmd_zip} a {backuppath}{backup_name}.7z -si{backup_name}.bak
    backuppath=.ackup
    keepday=7

    代码打包

  • 相关阅读:
    音乐播放器
    对象的单体模式和面向对象
    箭头函数详解及this指向
    ES6的基础语法
    房贷灵活计算器
    [译文] SQL JOIN,你想知道的应该都有
    [Perl] 删除数组中重复元素
    [Qt] 自定义 滚动条 样式
    nodejs之异步思想
    导致人生失败的31种原因(转自csdn博客)
  • 原文地址:https://www.cnblogs.com/xkxjy/p/3672254.html
Copyright © 2011-2022 走看看