Python--增量迴圈刪除MySQL表資料

來源:互聯網
上載者:User

標籤:

需求情境:

有一業務資料庫,使用MySQL 5.5版本,每天會寫入大量資料,需要不定期將多表中“指定時期前“的資料進行刪除,在SQL SERVER中很容易實現,寫幾個WHILE迴圈就搞定,雖然MySQL中也存在類似功能,怎奈自己不精通,於是採用Python來實現

 

話不多少,上指令碼:

# coding: utf-8import MySQLdbimport time# delete configDELETE_DATETIME = ‘2016-08-31 23:59:59‘DELETE_ROWS = 10000EXEC_DETAIL_FILE = ‘exec_detail.txt‘SLEEP_SECOND_PER_BATCH = 0.5DATETIME_FORMAT = ‘%Y-%m-%d %X‘# MySQL Connection ConfigDefault_MySQL_Host = ‘localhost‘Default_MySQL_Port = 3358Default_MySQL_User = "root"Default_MySQL_Password = ‘[email protected]‘Default_MySQL_Charset = "utf8"Default_MySQL_Connect_TimeOut = 120Default_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 conndef 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_countdef 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 = """SELECTMAX(ID) AS MAX_ID,MIN(ID) AS MIN_ID,COUNT(1) AS Total_CountFROM {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_countdef 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的周期,反正都指令碼化,再智能化點又何妨!

 

本文重點依舊是妹子,不能讓諸位看官白跑一趟,是不!!!

Python--增量迴圈刪除MySQL表資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.