Python batch delete table, only retain the last few days of the table
The code is as follows:
#!/usr/bin/python3 """ Batch delete tables, keep only tables from the last few days """ import pymysql import re def conn_(host='',usr='',passwd='',db='',port=3306,): conn = (host, usr, passwd, db, port,charset='utf8') return conn def del_table(conn_,table_pre='',table_suff='%Y%m%d',keep_count=3): date_form = None if table_suff == "%Y%m%d": date_form = "_(\d{4}\d{1,2}\d{1,2})$" date_len = 8 elif table_suff == "%Y-%m-%d": date_form = "_(\d{4}-\d{1,2}-\d{1,2})$" date_len = 10 elif table_suff == "%Y%m": date_form = "_(\d{4}\d{1,2})$" date_len = 6 elif table_suff == "%Y-%m": date_form = "_(\d{4}-\d{1,2})$" date_len = 7 else: raise Exception("Other types of time suffixes are not supported at this time.") curs = conn_.cursor() ('SHOW TABLES') data = () table_ = r'%s'%table_pre+date_form list_table = [] i = 0 for table in data: mt = (table_, table[0]) if mt: if len(()[0]) == date_len: list_table.append((table[0], ()[0])) i += 1 sorted(list_table, key=lambda date: date[1]) # Sort the table structure in ascending chronological order of suffixes for j in range(i-keep_count): sql = 'DROP TABLE if exists %s'%list_table[j][0] (sql) () 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)
summarize
Above is the entire content of this article, I hope the content of this article for your study or work has a certain reference learning value, thank you for your support. If you want to know more about the content please check the following related links