码迷,mamicode.com
首页 > 数据库 > 详细

Python脚本---备份MySQL数据库

时间:2015-05-19 19:01:46      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

转载请注明出处:http://blog.csdn.net/guoyjoe/article/details/45848057


#!/usr/bin/env python

# -*- coding:utf-8 -*-


#导入模块
import MySQLdb
import time
import datetime
import os

"""
  Purpose: 备份数据库
  Created: 2015/5/12
  Modified:2015/5/12
  @author: guoyJoe
"""


dbUser=‘root‘
dbPasswd=‘root‘
dbHost=‘192.168.1.6‘
dbCharset = ‘utf8‘
backupDir = ‘/u02/backup/mysql‘
backupDate =  time.strftime("%Y%m%d")


#查出MySQL中所有的数据库名称
sqlStr1 = "show databases like ‘db%‘"
try:
    connDB= MySQLdb.connect("192.168.1.6","root","root","test" )
    connDB.select_db(‘test‘)
    curSql1=connDB.cursor()
    curSql1.execute(sqlStr1)
    allDatabase = curSql1.fetchall()
    print ‘The database backup to start! %s‘   %time.strftime(‘%Y-%m-%d %H:%M:%S‘)
    for db in allDatabase:
        dbName = db[0]
        fileName = ‘%s/%s_%s.sql‘ %(backupDir,backupDate,dbName)
        print fileName
        if os.path.exists(fileName):
                os.remove(fileName)
        os.system("mysqldump -h%s -u%s -p%s -d %s --default_character-set=%s > %s/%s_%s.sql" %(dbHost,dbUser,dbPasswd,dbName,dbCharset,backupDir,backupDate,dbName))


    print ‘The database backup success! %s‘  %time.strftime(‘%Y-%m-%d %H:%M:%S‘)


#异常
except MySQLdb.Error,err_msg:
    print "MySQL error msg:",err_msg

Python脚本---备份MySQL数据库

标签:

原文地址:http://blog.csdn.net/guoyjoe/article/details/45848057

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!