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('{}\n    {}:{}'.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=.\backup
keepday=7

代码打包

转载于:https://www.cnblogs.com/xkxjy/p/3672254.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值