您好,登錄后才能下訂單哦!
小編給大家分享一下Python如何批量刪除只保留最近幾天table,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
Python批量刪除table,只保留最近幾天的table
代碼如下:
#!/usr/bin/python3 """ 批量刪除table,只保留最近幾天的table """ import pymysql import re def conn_(host='',usr='',passwd='',db='',port=3306,): conn = pymysql.connect(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("暫時不支持其他類型的時間后綴") curs = conn_.cursor() curs.execute('SHOW TABLES') data = curs.fetchall() table_ = r'%s'%table_pre+date_form list_table = [] i = 0 for table in data: mt = re.search(table_, table[0]) if mt: if len(mt.groups()[0]) == date_len: list_table.append((table[0], mt.groups()[0])) i += 1 sorted(list_table, key=lambda date: date[1]) #按照表結(jié)構(gòu)后綴時間升序排序 for j in range(i-keep_count): sql = 'DROP TABLE if exists %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)
看完了這篇文章,相信你對“Python如何批量刪除只保留最近幾天table”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。