Python实现备份MySQL数据库的方法示例

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Python实现字符串逆序输出功能示例

本文实例讲述了Python实现字符串逆序输出功能。分享给大家供大家参考,具体如下: 1、有时候我们可能想让字符串倒序输出,下面给出几种方法 方法一:通过索引的方法 >>&...

使用Python paramiko模块利用多线程实现ssh并发执行操作

1.paramiko概述 ssh是一个协议,OpenSSH是其中一个开源实现,paramiko是Python的一个库,实现了SSHv2协议(底层使用cryptography)。 有了Pa...

Python正则表达式实现截取成对括号的方法

本文实例讲述了Python正则表达式实现截取成对括号的方法。分享给大家供大家参考,具体如下: strs = '1(2(3(4(5(67)6)7)8)9)0' reg1 = re.co...

Python3简单实现串口通信的方法

如下所示: import serial import sys import os import time import re def wait_for_cmd_OK(): &nb...

python中logging模块的一些简单用法的使用

python中logging模块的一些简单用法的使用

用Python写代码的时候,在想看的地方写个print xx 就能在控制台上显示打印信息,这样子就能知道它是什么了,但是当我需要看大量的地方或者在一个文件中查看的时候,这时候print就...