mysql数据库自动备份和恢复的步骤

mysql数据库自动备份和恢复的步骤

巴适小编
2024-01-02 / 0 评论 / 6 阅读 / 正在检测是否收录...

数据库的重要性不言而喻了吧。今天分享下我的mysql数据库的备份和恢复的步骤。
数据无价,谨慎操作。
python定期备份代码:

DB_USER = ''
DB_USER_PASSWD = ''
BACKUP_PATH = ''
DB_NAME = []
day=3

class Run_backups:

def __init__(self):
    self.DATETIME = time.strftime('%Y%m%d-%H%M%S')
    self.TODAYBACKUPPATH = BACKUP_PATH + '/' + self.DATETIME
    #创建备份文件夹
    if not os.path.exists(self.TODAYBACKUPPATH):
        os.makedirs(self.TODAYBACKUPPATH)
    self.run()

def run_backup(self):
    for dbname in DB_NAME:
        dumpcmd = "mysqldump -u" + DB_USER + " -p" + DB_USER_PASSWD + " " + dbname + " > " + self.TODAYBACKUPPATH + "/" + dbname + ".sql"
        os.system(dumpcmd)

#执行压缩的函数
def run_tar(self):
    make_zip(self.TODAYBACKUPPATH,BACKUP_PATH+'/'+str(self.DATETIME)+'.zip')
    #删除备份文件夹
    shutil.rmtree(self.TODAYBACKUPPATH)

#备份数据库文件存在就执行备份和压缩,否则退出
def run(self):
    self.run_backup()
    self.run_tar()
        

def rmAssignDir(path, day=3):

dirs = os.listdir(path)
current_date = datetime.utcnow()+timedelta(hours=8)
for dir in dirs:
    _date = dir.split('-')[0]
    _date = datetime.strptime(_date,"%Y%m%d")+timedelta(days=day)
    if _date < current_date:
        os.remove(path+'/'+dir)
        print('已删除超过%s 天的备份:  %s'%(day,path+dir))
            

def make_zip(source_dir, output_filename):

zipf = zipfile.ZipFile(output_filename, 'w')
dirlist = os.listdir(source_dir)
for file in dirlist:
    zipf.write(os.path.join(source_dir, file))
zipf.close()

def job(path, day):

Run_backups()
rmAssignDir(path, day)

定时任务代码

def runSchedule(job, path, day):

schedule.every().day.at("23:00").do(job, path, day)
# 备份图片代码
schedule.every().day.at("23:30").do(runbkfile)

def runbackup():

#打印执行信息
runSchedule(job, BACKUP_PATH, day)
while True:
    schedule.run_pending()
    time.sleep(1)

mysql数据库恢复
mysql -u root -p;

set dbname;

use names utf8;

source ;

0

评论 (0)

取消