Python script --- back up MySQL database, python script --- mysql
Reprinted please indicate the source: http://blog.csdn.net/guoyjoe/article/details/45848057
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
# Import module
Import MySQLdb
Import time
Import datetime
Import OS
"""
Purpose: Back up the 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 ")
# Identify all database names in 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 -- 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
Failed t MySQLdb. Error, err_msg:
Print "MySQL error msg:", err_msg