备份数据库的命令 mysqldump(操作系统的命令)
import os,datetime
class BakDB(object):
def __init__(self,ip,username,password,port=3306,path='/tmp/db_bak'): # path传的是linux系统的路径
self.ip=ip
self.username=username
self.password=password
self.port=port
self.path=path
self.path_exist()
def path_exist(self):
if not os.path.isdir(self.path):
os.mkdir(self.path)
def bak_db(self):
# mysqldump -uroot -p123456 -A > nhy123.sql
# mysqldump -u%s -p%s -P%s -h%s -A > filename
filename=str(datetime.date.today())+'.sql'
abs_file = os.path.join(self.path,filename)
command = '''mysqldump -u{username} -p{password} -P{port} -h{ip} -A > {filename}'''.format(
username=self.username,
password=self.password,
port=self.port,
filename=abs_file,
ip=self.ip)
os.system(command)
print('数据库已备份完成!')
a=BakDB('127.0.0.1','root','123456')
a.bak_db()