Python脚本---备份MySQL数据库
转载请注明出处: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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。