Example of Python implementing a method to back up an MySQL database

  • 2020-07-21 08:37:56
  • OfStack

This article illustrates how Python can backup MySQL databases. To share for your reference, specific as follows:


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# The import module 
import MySQLdb
import time
import datetime
import os
"""
 Purpose:  Backup database 
 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")
# Find out MySQL All database names in 
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')
# abnormal 
except MySQLdb.Error,err_msg:
  print "MySQL error msg:",err_msg

More about Python related topics: interested readers to view this site "Python + MySQL database programming tutorial", "common database operations Python skills summary", "Python mathematical operation skills summary", "Python data structure and algorithm tutorial", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful in Python programming.


Related articles: