99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python增量循環(huán)刪除MySQL表數(shù)據(jù)的方法
Python增量循環(huán)刪除MySQL表數(shù)據(jù)的方法
2018-03-24
收藏

Python增量循環(huán)刪除MySQL表數(shù)據(jù)的方法

有一業(yè)務(wù)數(shù)據(jù)庫,使用MySQL 5.5版本,每天會寫入大量數(shù)據(jù),需要不定期將多表中“指定時期前“的數(shù)據(jù)進(jìn)行刪除,在SQL SERVER中很容易實(shí)現(xiàn),寫幾個WHILE循環(huán)就搞定,雖然MySQL中也存在類似功能,怎奈自己不精通,于是采用Python來實(shí)現(xiàn)

話不多少,上腳本:

# 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: 要轉(zhuǎn)換成字符串的時間
: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指定的文件中
請先創(chuàng)建文件所在的目錄
: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():
"""
根據(jù)默認(rèn)配置返回數(shù)據(jù)庫連接
:return: 數(shù)據(jù)庫連接
"""
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):
"""
執(zhí)行傳入的腳本,返回影響行數(shù)
:param sql_script:
:param sql_param:
:return: 腳本最后一條語句執(zhí)行影響行數(shù)
"""
try:
conn = get_mysql_connection()
print_info("在服務(wù)器{0}上執(zhí)行腳本:{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):
"""
執(zhí)行傳入的SQL腳本,并返回查詢結(jié)果
:param sql_script:
:param sql_param:
:return: 返回SQL查詢結(jié)果
"""
try:
conn = get_mysql_connection()
print_info("在服務(wù)器{0}上執(zhí)行腳本:{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):
"""
按照傳入的表獲取要刪除數(shù)據(jù)最大ID、最小ID、刪除總行數(shù)
:param table_name: 要刪除的表
:return: 返回要刪除數(shù)據(jù)最大ID、最小ID、刪除總行數(shù)
"""
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]
# 此處有一坑,可能出現(xiàn)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("影響行數(shù):{0}".format(row_count))
current_percent = (temp_id - min_id) * 1.0 / (max_id - min_id)
print_info("當(dāng)前進(jìn)度{0}/{1},剩余{2},進(jìn)度為{3}%".format(temp_id, max_id, max_id - temp_id, "%.2f" % current_percent))
time.sleep(SLEEP_SECOND_PER_BATCH)
print_info("當(dāng)前表{0}已無需要刪除的數(shù)據(jù)".format(table_name))
delete_data('TB001')
delete_data('TB002')
delete_data('TB003')


執(zhí)行效果:

實(shí)現(xiàn)原理:

由于表存在自增ID,于是給我們增量循環(huán)刪除的機(jī)會,查找出滿足刪除條件的最大值ID和最小值ID,然后按ID 依次遞增,每次小范圍內(nèi)(如10000條)進(jìn)行刪除。

實(shí)現(xiàn)優(yōu)點(diǎn):

實(shí)現(xiàn)“小斧子砍大柴”的效果,事務(wù)小,對線上影響較小,打印出當(dāng)前處理到的“ID”,可以隨時關(guān)閉,稍微修改下代碼便可以從該ID開始,方便。

實(shí)現(xiàn)不足:

為防止主從延遲太高,采用每次刪除SLEEP1秒的方式,相對比較糙,最好的方式應(yīng)該是周期掃描這條復(fù)制鏈路,根據(jù)延遲調(diào)整SLEEP的周期,反正都腳本化,再智能化點(diǎn)又何妨!


數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }