Python script --- back up MySQL database, python script --- mysql

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.