这两天用python谢了个表数据的归档脚本,记录一下。
[root@monitor python_scripts]# crontab -l
# 表数据归档
30 21 * * * cd /root/python3/ && source bin/activate && cd /opt/sh/python_scripts/ && python mysql_pigeonhole.py
---------------------
[root@monitor python_scripts]# cat execute_mysql_pigeonhole.sh
#!/bin/sh
cd /root/python3/ && source bin/activate && cd /opt/sh/python_scripts/ && python mysql_pigeonhole.py
---------------------
[root@monitor python_scripts]# cat mysql_pigeonhole.py
#!/usr/bin/env python3
#-*- coding:utf8 -*-
#author:
import pymysql,time,logging
from datetime import datetime
#设置日志
import logging.config
logging.config.fileConfig("logging.conf")
logger = logging.getLogger("dev")
#date_time = datetime.now().strftime("%Y-%m-%d")
#设置间隔时间,目前单位为天:day
interval = 7
("任务开始...")
(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
conn = pymysql.connect(host="",user="",password="",database="",port=,charset="utf8")
cursor = conn.cursor()
#查询迁移前的最后一条数据id
sql_select_begin = "select id from t_rank_log where created < unix_timestamp(current_date() - interval %d day) order by id desc limit 1;" % (interval)
#迁移数据sql
sql_insert = "insert into t_rank_log_pigeonhole select * from t_rank_log where created < unix_timestamp(current_date() - interval %d day) ;" % (interval)
#迁移后新表查询
sql_select_new = "select id from t_rank_log_pigeonhole order by id desc limit 1;"
#原表数据清除、空间整理
sql_delete = "delete from t_rank_log where created < unix_timestamp(current_date() - interval %d day) ;" % (interval)
sql_alter = "alter table t_rank_log engine=innodb"
#依次执行SQL
#sql_select_begin
cursor.execute(sql_select_begin)
result_tmp1 = cursor.fetchall()
if result_tmp1 is ():
result_select_begin = None
("result_select_begin 查询无数值 请调节 interval 参数")
else:
result_select_begin = result_tmp1[0][0]
("result_select_begin :%s" % result_select_begin)
try:
cursor.execute(sql_insert)
except pymysql.err.IntegrityError as Duplicate:
("MySQL data Error: %s" % Duplicate)
#sql_select_new
cursor.execute(sql_select_new)
result_select_new = cursor.fetchall()[0][0]
("result_select_new :%s" % result_select_new)
if result_select_begin == result_select_new:
("数据迁移成功,开始清除原表历史数据")
#sql_delete,sql_alter
cursor.execute(sql_delete)
("原表数据清理完成,开始回收空间碎片")
cursor.execute(sql_alter)
("空间碎片回收完毕。。。。")
("任务完毕。。。\n")
else:
("数据迁移失败,请查看!!!!\n")
conn.commit()
conn.close()
---------------表归档脚本脚本
原创
©著作权归作者所有:来自51CTO博客作者浮生凤年的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
日归档脚本
目录#OP
hive Arc Backup -
nginx日志定期归档脚本
nginx日志定期归档脚本
日志 nginx 定期 -
Oracle 删除归档日志脚本
归档日志记录着数据库的操作记录,是做数据恢复的依据,如果数据库开启了归档模式rchive.sh
oracle 脚本 数据库 平台 windows -
RMAN 简单的删除归档脚本
[oracle@sjzx00 ~]$ cat clear_arch.sh export O
oracle hive 环境变量 -
Oracle RMAN删除归档日志脚本
每天一个 DBA 小知识,助你更进一步!
oracle linux hive bash -
Oracle自动清理归档日志脚本
本文介绍oracle自动删除归档日志脚本。
oracle 自动删除备份 -
postgresql手动清理归档的方法及归档清理脚本postgresql pg_archivecleanup 清理归档 清理脚本
-
【CentOS】Shell脚本案例:归档文件
Shell脚本案例:归档文件
centos linux 运维 Shell hive
















