该实例下所有分区表分区规则相同
#!/usr/bin/python
#-*- coding:utf-8 -*-
import pymysql
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
class mysql_connection:
def __init__(self):
self.conn = pymysql.connect(host="xx x.xxx.xxx.xxx",port=3306,user="xxx",password="xxxxxx",database="sbtest")
self.cur = self.conn.cursor()
def sql_statement(self, sql):
try:
self.conn.begin()
self.cur.execute(sql)
return self.cur.fetchall()
self.conn.commit()
except Exception as err:
print("Error %s for execute sql: %s" % (err, sql))
self.conn.close()
if __name__ == '__main__':
mysql = mysql_connection()
table_names = mysql.sql_statement("SELECT distinct concat(table_schema,'.',table_name) FROM INFORMATION_SCHEMA.PARTITIONS where table_schema not in ('information_schema','performance_schema','mysql','sys');")
max_partition = mysql.sql_statement("SELECT REPLACE(partition_name,'p','') FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA='sbtest' and table_name='test1' ORDER BY partition_ordinal_position DESC LIMIT 1;")
min_partition = mysql.sql_statement("SELECT REPLACE(partition_name,'p','') FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA='sbtest' and table_name='test1' ORDER BY partition_ordinal_position LIMIT 1;")
min_date = str(min_partition[0][0])
max_date = str(max_partition[0][0])
min_partition_name = (datetime.strptime(min_date, "%Y%m%d") - relativedelta(months=-0)).strftime("%Y%m%d")
max_partition_name = (datetime.strptime(max_date, "%Y%m%d") - relativedelta(months=-1)).strftime("%Y%m%d")
max_partition_value = (datetime.strptime(max_date, "%Y%m%d") - relativedelta(months=-2)).strftime("%Y%m%d")
for i in range(len(table_names)):
mysql = mysql_connection()
mysql.sql_statement('ALTER TABLE '+str(table_names[i][0])+' ADD PARTITION (PARTITION p'+max_partition_name+' VALUES LESS THAN ('+max_partition_value+') ENGINE = InnoDB);')
mysql.sql_statement('ALTER TABLE '+str(table_names[i][0])+' DROP PARTITION p'+min_partition_name+';')