需求情境:
有一業務資料庫,使用MySQL 5.5版本,每天會寫入大量資料,需要不定期將多表中“指定時期前“的資料進行刪除,在SQL SERVER中很容易實現,寫幾個WHILE迴圈就搞定,雖然MySQL中也存在類似功能,怎奈自己不精通,於是採用Python來實現
話不多少,上指令碼:
# coding: utf-8
import MySQLdb
import time
# delete config
DELETE_DATETIME = '2016-08-31 23:59:59'
DELETE_ROWS = 10000
EXEC_DETAIL_FILE = 'exec_detail.txt'
SLEEP_SECOND_PER_BATCH = 0.5
DATETIME_FORMAT = '%Y-%m-%d %X'
# MySQL Connection Config
Default_MySQL_Host = 'localhost'
Default_MySQL_Port = 3358
Default_MySQL_User = "root"
Default_MySQL_Password = 'roo@01239876'
Default_MySQL_Charset = "utf8"
Default_MySQL_Connect_TimeOut = 120
Default_Database_Name = 'testdb001'
def get_time_string(dt_time):
"""
擷取指定格式的時間字串
:param dt_time: 要轉換成字串的時間
:return: 返回指定格式的字串
"""
global DATETIME_FORMAT
return time.strftime(DATETIME_FORMAT, dt_time)
def print_info(message):
"""
將message輸出到控制台,並將message寫入到記錄檔
:param message: 要輸出的字串
:return: 無返回
"""
print(message)
global EXEC_DETAIL_FILE
new_message = get_time_string(time.localtime()) + chr(13) + str(message)
write_file(EXEC_DETAIL_FILE, new_message)
def write_file(file_path, message):
"""
將傳入的message追加寫入到file_path指定的檔案中
請先建立檔案所在的目錄
:param file_path: 要寫入的檔案路徑
:param message: 要寫入的資訊
:return:
"""
file_handle = open(file_path, 'a')
file_handle.writelines(message)
# 追加一個換行以方便瀏覽
file_handle.writelines(chr(13))
file_handle.close()
def get_mysql_connection():
"""
根據預設配置返回資料庫連接
:return: 資料庫連接
"""
conn = MySQLdb.connect(
host=Default_MySQL_Host,
port=Default_MySQL_Port,
user=Default_MySQL_User,
passwd=Default_MySQL_Password,
connect_timeout=Default_MySQL_Connect_TimeOut,
charset=Default_MySQL_Charset,
db=Default_Database_Name
)
return conn
def mysql_exec(sql_script, sql_param=None):
"""
執行傳入的指令碼,返回影響行數
:param sql_script:
:param sql_param:
:return: 指令碼最後一條語句執行影響行數
"""
try:
conn = get_mysql_connection()
print_info("在伺服器{0}上執行指令碼:{1}".format(
conn.get_host_info(), sql_script))
cursor = conn.cursor()
if sql_param is not None:
cursor.execute(sql_script, sql_param)
row_count = cursor.rowcount
else:
cursor.execute(sql_script)
row_count = cursor.rowcount
conn.commit()
cursor.close()
conn.close()
except Exception, e:
print_info("execute exception:" + str(e))
row_count = 0
return row_count
def mysql_query(sql_script, sql_param=None):
"""
執行傳入的SQL指令碼,並返回查詢結果
:param sql_script:
:param sql_param:
:return: 返回SQL查詢結果
"""
try:
conn = get_mysql_connection()
print_info("在伺服器{0}上執行指令碼:{1}".format(
conn.get_host_info(), sql_script))
cursor = conn.cursor()
if sql_param != '':
cursor.execute(sql_script, sql_param)
else:
cursor.execute(sql_script)
exec_result = cursor.fetchall()
cursor.close()
conn.close()
return exec_result
except Exception, e:
print_info("execute exception:" + str(e))
def get_id_range(table_name):
"""
按照傳入的表擷取要刪除資料最大ID、最小ID、刪除總行數
:param table_name: 要刪除的表
:return: 返回要刪除資料最大ID、最小ID、刪除總行數
"""
global DELETE_DATETIME
sql_script = """
SELECT
MAX(ID) AS MAX_ID,
MIN(ID) AS MIN_ID,
COUNT(1) AS Total_Count
FROM {0}
WHERE create_time <='{1}';
""".format(table_name, DELETE_DATETIME)
query_result = mysql_query(sql_script=sql_script, sql_param=None)
max_id, min_id, total_count = query_result[0]
# 此處有一坑,可能出現total_count不為0 但是max_id 和min_id 為None的情況
# 因此判斷max_id和min_id 是否為NULL
if (max_id is None) or (min_id is None):
max_id, min_id, total_count = 0, 0, 0
return max_id, min_id, total_count
def delete_data(table_name):
max_id, min_id, total_count = get_id_range(table_name)
temp_id = min_id
while temp_id <= max_id:
sql_script = """
DELETE FROM {0}
WHERE id <= {1}
and id >= {2}
AND create_time <='{3}';
""".format(table_name, temp_id + DELETE_ROWS, temp_id, DELETE_DATETIME)
temp_id += DELETE_ROWS
print(sql_script)
row_count = mysql_exec(sql_script)
print_info("影響行數:{0}".format(row_count))
current_percent = (temp_id - min_id) * 1.0 / (max_id - min_id)
print_info("當前進度{0}/{1},剩餘{2},進度為{3}%".format(temp_id, max_id, max_id - temp_id, "%.2f" % current_percent))
time.sleep(SLEEP_SECOND_PER_BATCH)
print_info("當前表{0}已無需要刪除的資料".format(table_name))
delete_data('TB001')
delete_data('TB002')
delete_data('TB003')
執行效果:
實現原理:
由於表存在自增ID,於是給我們增量迴圈刪除的機會,尋找出滿足刪除條件的最大值ID和最小值ID,然後按ID 依次遞增,每次小範圍內(如10000條)進行刪除。
實現優點:
實現“小斧子砍大柴”的效果,事務小,對線上影響較小,列印出當前處理到的“ID”,可以隨時關閉,稍微修改下代碼便可以從該ID開始,方便。
實現不足:
為防止主從延遲太高,採用每次刪除SLEEP1秒的方式,相對比較糙,最好的方式應該是周期掃描這條複製鏈路,根據延遲調整SLEEP的周期,反正都指令碼化,再智能化點又何妨!