Python实现备份MySQL数据库的方法示例
本文实例讲述了Python实现备份MySQL数据库的方法。分享给大家供大家参考,具体如下:
#!/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 %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程序设计有所帮助。
相关推荐
huavhuahua 2020-11-20
weiiron 2020-11-16
cakecc00 2020-11-15
千锋 2020-11-15
JakobHu 2020-11-14
guangcheng 2020-11-13
xirongxudlut 2020-11-10
solarLan 2020-11-09
pythonxuexi 2020-11-08
文山羊 2020-11-07
susmote 2020-11-07
wuShiJingZuo 2020-11-05
Pythonjeff远 2020-11-06
jacktangj 2020-11-04
lousir 2020-11-04
Noneyes 2020-11-10
ailxxiaoli 2020-11-16
chensen 2020-11-14
Nostalgiachild 2020-11-13