本文實例講述了Python實現備份MySQL數據庫的方法。分享給大家供大家參考,具體如下:
#!/usr/bin/env python# -*- coding:utf-8 -*-#導入模塊import MySQLdbimport timeimport datetimeimport 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 %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相關內容感興趣的讀者可查看本站專題:《Python+MySQL數據庫程序設計入門教程》、《Python常見數據庫操作技巧匯總》、《Python數學運算技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答