Python批量删除只保留最近几天table的代码实例
Python批量删除table,只保留最近几天的table
代码如下:
#!/usr/bin/python3
"""
批量删除table,只保留最近几天的table
"""
importpymysql
importre
defconn_(host='',usr='',passwd='',db='',port=3306,):
conn=pymysql.connect(host,usr,passwd,db,port,charset='utf8')
returnconn
defdel_table(conn_,table_pre='',table_suff='%Y%m%d',keep_count=3):
date_form=None
iftable_suff=="%Y%m%d":
date_form="_(\d{4}\d{1,2}\d{1,2})$"
date_len=8
eliftable_suff=="%Y-%m-%d":
date_form="_(\d{4}-\d{1,2}-\d{1,2})$"
date_len=10
eliftable_suff=="%Y%m":
date_form="_(\d{4}\d{1,2})$"
date_len=6
eliftable_suff=="%Y-%m":
date_form="_(\d{4}-\d{1,2})$"
date_len=7
else:
raiseException("暂时不支持其他类型的时间后缀")
curs=conn_.cursor()
curs.execute('SHOWTABLES')
data=curs.fetchall()
table_=r'%s'%table_pre+date_form
list_table=[]
i=0
fortableindata:
mt=re.search(table_,table[0])
ifmt:
iflen(mt.groups()[0])==date_len:
list_table.append((table[0],mt.groups()[0]))
i+=1
sorted(list_table,key=lambdadate:date[1])#按照表结构后缀时间升序排序
forjinrange(i-keep_count):
sql='DROPTABLEifexists%s'%list_table[j][0]
curs.execute(sql)
curs.close()
conn_.close()
if__name__=='__main__':
table_pre="tree_product"
table_suff="%Y%m%d"
#table_suff="%Y-%m-%d"
#table_suff="%Y%m"
#table_suff="%Y-%m"
conn=conn_('10.0.0.11','root','sctele@root','sxf',port=3306)
del_table(conn,table_pre=table_pre,table_suff=table_suff,keep_count=1)
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接