Python批量删除只保留最近几天table的代码实例

yipeiwu_com5年前Python基础

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]) #按照表结构后缀时间升序排序
  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设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

python切片的步进、添加、连接简单操作示例

本文实例讲述了python切片的步进、添加、连接简单操作。分享给大家供大家参考,具体如下: 步进切片: #coding:utf-8 a="123456" print a[::-1]...

Python数组定义方法

本文实例讲述了Python数组定义方法。分享给大家供大家参考,具体如下: Python中没有数组的数据结构,但列表很像数组,如: a=[0,1,2] 这时:a[0]=0, a[...

python自带tkinter库实现棋盘覆盖图形界面

python自带tkinter库实现棋盘覆盖图形界面

python实现棋盘覆盖图形界面,供大家参考,具体内容如下 一、解决方案和关键代码 工具: python tkinter库 问题描述:   在一个2^k×2...

Python之指数与E记法的区别详解

不要把自乘得到幂(也称为求幂)和E记法弄混了 3**5表示3的5次幂,也就是3*3*3*3*3,等于243 3e5表示3乘以10的5次幂,也就是3*10*10*10*10*10,结果等于...

python中的字典使用分享

字典中的键使用时必须满足一下两个条件: 1、每个键只能对应一个项,也就是说,一键对应多个值时不允许的(列表、元组和其他字典的容器对象除外)。当有键发生冲突时(即字典键重复赋值),取最后的...