日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python批量刪除mysql中千萬(wàn)級(jí)大量數(shù)據(jù)

系統(tǒng) 2189 0

場(chǎng)景描述

線上 mysql 數(shù)據(jù)庫(kù)里面有張表保存有每天的統(tǒng)計(jì)結(jié)果,每天有1千多萬(wàn)條,這是我們意想不到的,統(tǒng)計(jì)結(jié)果咋有這么多。運(yùn)維找過(guò)來(lái),磁盤(pán)占了 200G ,最后問(wèn)了運(yùn)營(yíng),可以只保留最近3天的,前面的數(shù)據(jù),只能刪了。刪,怎么刪?
因?yàn)檫@是線上數(shù)據(jù)庫(kù),里面存放有很多其它數(shù)據(jù)表,如果直接刪除這張表的數(shù)據(jù),肯定不行,可能會(huì)對(duì)其它表有影響。嘗試每次只刪除一天的數(shù)據(jù),還是卡頓的厲害,沒(méi)辦法,寫(xiě)個(gè)Python腳本批量刪除吧。
具體思路是:

  1. 每次只刪除一天的數(shù)據(jù);
  2. 刪除一天的數(shù)據(jù),每次刪除50000條;
  3. 一天的數(shù)據(jù)刪除完,開(kāi)始刪除下一天的數(shù)據(jù);

Python代碼

          
            # -*-coding:utf-8 -*-

import sys

# 這是我們內(nèi)部封裝的Python Module
sys.path.append('/var/lib/hadoop-hdfs/scripts/python_module2')
import keguang.commons as commons
import keguang.timedef as timedef
import keguang.sql.mysqlclient as mysql


def run(starttime, endtime, regx):
    tb_name = 'statistic_ad_image_final_count'
    days = timedef.getDays(starttime,endtime,regx)
    # 遍歷刪除所有天的數(shù)據(jù)
    for day in days:
        print '%s 數(shù)據(jù)刪除開(kāi)始'%(day)
        mclient = getConn()
        sql = '''
        select 1 from %s where date = '%s' limit 1
        '''%(tb_name, day)
        print sql
        result = mclient.query(sql)
        # 如果查詢到了這一天的數(shù)據(jù),繼續(xù)刪除
        while result is not ():
            sql = 'delete from %s where date = "%s" limit 50000'%(tb_name, day)
            print sql
            mclient.execute(sql)
            sql = '''
            select 1 from %s where date = '%s' limit 1
            '''%(tb_name, day)
            print sql
            result = mclient.query(sql)
        print '%s 數(shù)據(jù)刪除完成'%(day)
        mclient.close()


# 返回mysql 連接
def getConn():
    return mysql.MysqlClient(host = '0.0.0.0', user = 'test', passwd = 'test', db= 'statistic')

if __name__ == '__main__':
    regx = '%Y-%m-%d'
    yesday = timedef.getYes(regx, -1)
    starttime = '2019-08-17'
    endtime ='2019-08-30'
    run(starttime, endtime, regx)
          
        

循環(huán)判斷數(shù)據(jù),如果有,繼續(xù)刪除當(dāng)天 50000 條數(shù)據(jù);否則,開(kāi)始刪除下一天的數(shù)據(jù)。花了半個(gè)小時(shí),終于刪除完了。


歡迎關(guān)注我的微信公眾號(hào)
Python批量刪除mysql中千萬(wàn)級(jí)大量數(shù)據(jù)_第1張圖片


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦!!!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 贵州省| 赤峰市| 海晏县| 黑山县| 会理县| 丰镇市| 金坛市| 江都市| 高唐县| 金溪县| 双鸭山市| 邹平县| 英超| 镇沅| 江永县| 安丘市| 北京市| 随州市| 布尔津县| 芦山县| 海原县| 宜章县| 三都| 江门市| 嘉峪关市| 沛县| 新密市| 原阳县| 衡阳县| 邻水| 炉霍县| 安平县| 涟水县| 宁海县| 诸暨市| 吉林省| 金坛市| 海淀区| 开阳县| 辽源市| 西宁市|