MySQL backup python code

OS Import, Time, pymysql, the shutil 

from timer task apscheduler.schedulers.blocking # Import BlockingScheduler


DEF getDatabaseNames ():
"" "
connected database
returns the specified database table all
" ""
Conn = pymysql.connect (= '10 .100 Host. 102.224 ', Port = 3316, DB =' INDEXDB ', = User' the root ', the passwd =' the root ')
CUR = conn.cursor ()
cur.execute (' Show Tables; ')
Tables cur.fetchall = ()
CUR .close ()
conn.Close ()
return tables


DEF db_bf (path):
"" "
creating the storage path
and the backup database table specified in
" ""
path = path.strip ()
path path.rstrip = ( "\\")

IF Not os.path.exists (path): # The system determines the presence of the path
os.makedirs (path) #, does not exist, create
Tables getDatabaseNames = ()
for Tables in Table:
the try:
TableName = Table [0]
# export DB
cmd = "% S -H -u the mysqldump -p% S% S% S>% S /% s.sql "% (.100.102.224 '10 ',' the root ',' INDEXDB ', TableName, Folder, TableName)
Print (cmd)
the os.system (cmd)

the except Exception AS E:
Print (E )
return True
the else:
return False


DEF mysql_rm (path, of TIMESTR):
"" "
under the directory to delete the backup files over a certain length of time
." ""
# list all the backup directory
f = list (os.listdir(path))
print(f)
of TIMESTR = now_time [0:. 8]
# Set over time
Days =. 3
for I in F:

exit_time = I [0:. 8]
UPDATE_TIME = int (exit_time) Days +
# IF UPDATE_TIME <int (now_time) or exit_time == now_time :
# if the data exceeds a predetermined number of days delete the backup
IF UPDATE_TIME <int (now_time):
shutil.rmtree (I + path)
# with Open (Self .__ filerm_log, 'a') AS file_log:
# file_log.write ( " % s delete the backup file% s \ n-, "% (of TIMESTR [0:. 8], I))


# DEF hf_bf (path, DB):
#" ""
# restore the data backed up to the specified database
# "" "
# List = F (the os.listdir (path))
#
# # for X in F:
Cmd = # "MySQL -p-U% S% S% S <S% / S%"% ( 'the root', 'the root', DB, path, F [0])
# Print (cmd)
# the os.system (cmd)


IF the __name__ == '__main__':
# create a backup storage path,
of TIMESTR the time.strftime = ( "the Y% m%% D% H% m% S", time.localtime (the time.time ()))
= Folder "mysql_data_bak /" of TIMESTR +
db_bf (Folder)
# restore a database backup
# hf_bf ( "mysql_data_bak / 20,191,028,114,943", 'ceshi')
Scheduler BlockingScheduler = ()
# 6 will function, 7, 8, 11, December the third Friday of 1,2,3 operating point
# scheduler.add_job (db_bf, args = [ folder,], trigger = 'cron', month = '6-8,11-12', day = '3rd fri ', hour =' 0-3 ')
# 2019-12-30 00:00:00 As of 5:30 run every Monday through Friday morning
# scheduler.add_job(db_bf,args=[folder,], trigger='cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2019-12-31')
# 每天14.39执行任务
scheduler.add_job(db_bf, args=[folder, ], trigger='cron', hour=14, minute=39)
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass

Guess you like

Origin www.cnblogs.com/guofeng-1016/p/11762731.html