python3删除mysql上月分区数据(脚本)

本文介绍了一种使用Python批量清空MySQL数据库中特定分区数据的方法,通过获取上个月的时间戳,构造SQL语句来清空指定的分区,适用于需要定期清理历史数据的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import datetime
import pymysql
import pymysql.cursors

tables_schdule=["talbe1","table2","table3","table4","table5"]

x = datetime.date.today().replace(day=1)
y = datetime.timedelta(days=1)
last_month = (x-y).strftime("%Y%m")
#print(last_month)

drop_tables=[]
for i in range(5):
    drop_tables.append("ALTER TABLE {} TRUNCATE PARTITION P{};".format(tables_schdule[i],last_month))

#print(drop_tables)

connection=pymysql.connect('127.0.0.1','root','duzhaoqi2015','eos')

try:
#获取一个游标
    with connection.cursor() as cursor:
        # sql='select * from test'
        # cursor.execute(sql)
        for i in drop_tables:
            #print(i)
            cursor.execute(i)
        # for row in cursor.fetchall():
        #     print("ID:" + str(row[0]) + '  名字:' + row[1])
        # connection.commit()
finally:
    connection.close()

 

转载于:https://www.cnblogs.com/duzhaoqi/p/11451048.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值