表歸檔腳本腳本

這兩天用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
logger.info("任務開始...")
logger.info(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
    logger.info("result_select_begin 查詢無數值 請調節 interval 參數")
else:
    result_select_begin = result_tmp1[0][0]
    logger.info("result_select_begin :%s" % result_select_begin)
try:
    cursor.execute(sql_insert)
except pymysql.err.IntegrityError as Duplicate:
    logger.info("MySQL data Error: %s" % Duplicate)
#sql_select_new
cursor.execute(sql_select_new)
result_select_new = cursor.fetchall()[0][0]
logger.info("result_select_new :%s" % result_select_new)
if result_select_begin == result_select_new:
    logger.info("數據遷移成功,開始清除原表歷史數據")
    #sql_delete,sql_alter
    cursor.execute(sql_delete)
    logger.info("原表數據清理完成,開始回收空間碎片")
    cursor.execute(sql_alter)
    logger.info("空間碎片回收完畢。。。。")
    logger.info("任務完畢。。。\n")
else:
    logger.info("數據遷移失敗,請查看!!!!\n")
conn.commit()
conn.close()
---------------


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章