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

yipeiwu_com6年前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使用百度文字识别功能方法详解

介绍python使用百度智能去的文字识别功能,可以识别截图中的文,登陆路验证码等等。, 登陆百度智能云,选择产品服务。 选择“人工智能”---文字识别。 点击创建应用。 如图下面有关...

python之pyqt5通过按钮改变Label的背景颜色方法

python之pyqt5通过按钮改变Label的背景颜色方法

使用setStyleSheet方法修改得到自己想要的字体,大小,颜色 self.lab = QLabel("标签字体大小颜色", self) self.lab.setGeometry...

Pytorch实现GoogLeNet的方法

Pytorch实现GoogLeNet的方法

GoogLeNet也叫InceptionNet,在2014年被提出,如今已到V4版本。GoogleNet比VGGNet具有更深的网络结构,一共有22层,但是参数比AlexNet要少12倍...

python 列表,数组,矩阵两两转换tolist()的实例

通过代码熟悉过程: # -*- coding: utf-8 -*- from numpy import * a1 =[[1,2,3],[4,5,6]] #列表 print('a1 :...

使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件及出现问题解决方法

使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件及出现问题解决方法

下面看下通过Pyinstaller打包Pygame库写的小游戏程序出现的问题解决方法 # -基于Python的Pygame库的GUI游戏 游戏内容是通过飞船发射子弹来射击外星人 空格键为...