Example of how to back up a MySQL database using Python: pythonmysql
This example describes how to back up a MySQL database using Python. We will share this with you for your reference. The details are as follows:
#! /Usr/bin/env python #-*-coding: UTF-8-*-# import module import MySQLdbimport timeimport datetimeimport OS "Purpose: backup database Created: 2015/5/12 Modified: 192 @ author: guoyJoe "" dbUser = 'root' dbPasswd = 'root' dbHost = '2017. 168.1.6 'dbcharset = 'utf8' backupDir = '/u02/backup/mysql' backupDate = time. strftime ("% Y % m % d") # Check all MySQL database names 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 -- 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') # exception timeout t MySQLdb. error, err_msg: print "MySQL error msg:", err_msg