Python批量刪除mysql中千萬級大量數(shù)據(jù)的腳本分享
場景描述
線上mysql數(shù)據(jù)庫里面有張表保存有每天的統(tǒng)計結(jié)果,每天有1千多萬條,這是我們意想不到的,統(tǒng)計結(jié)果咋有這么多。運維找過來,磁盤占了200G,最后問了運營,可以只保留最近3天的,前面的數(shù)據(jù),只能刪了。刪,怎么刪?
因為這是線上數(shù)據(jù)庫,里面存放有很多其它數(shù)據(jù)表,如果直接刪除這張表的數(shù)據(jù),肯定不行,可能會對其它表有影響。嘗試每次只刪除一天的數(shù)據(jù),還是卡頓的厲害,沒辦法,寫個Python腳本批量刪除吧。
具體思路是:
- 每次只刪除一天的數(shù)據(jù);
- 刪除一天的數(shù)據(jù),每次刪除50000條;
- 一天的數(shù)據(jù)刪除完,開始刪除下一天的數(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ù)刪除開始'%(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)
以上就是Python批量刪除mysql中千萬級大量數(shù)據(jù)的腳本的詳細內(nèi)容,更多關于python 刪除MySQL數(shù)據(jù)的資料請關注腳本之家其它相關文章!
- MyBatis批量插入/修改/刪除MySql數(shù)據(jù)
- mysql利用mysqlbinlog命令恢復誤刪除數(shù)據(jù)的實現(xiàn)
- mysql5.7.33誤刪除ibdata文件找回數(shù)據(jù)的方法
- mysql數(shù)據(jù)庫刪除重復數(shù)據(jù)只保留一條方法實例
- mysql 大表批量刪除大量數(shù)據(jù)的實現(xiàn)方法
- 淺談為什么MySQL不建議delete刪除數(shù)據(jù)
- Mysql刪除數(shù)據(jù)以及數(shù)據(jù)表的方法實例
- MySQL刪除數(shù)據(jù),表文件大小依然沒變的原因
- MySQL 快速刪除大量數(shù)據(jù)(千萬級別)的幾種實踐方案詳解
- MySQL Delete 刪數(shù)據(jù)后磁盤空間未釋放的原因
相關文章
Python數(shù)據(jù)結(jié)構(gòu)之雙向鏈表的定義與使用方法示例
這篇文章主要介紹了Python數(shù)據(jù)結(jié)構(gòu)之雙向鏈表的定義與使用方法,結(jié)合實例形式分析了Python雙向鏈表的概念、原理、使用方法及相關注意事項,需要的朋友可以參考下2018-01-01
python函數(shù)與方法的區(qū)別總結(jié)
在本篇文章里小編給大家整理了關于python函數(shù)與方法的區(qū)別的相關知識點代碼內(nèi)容,需要的朋友們學習下。2019-06-06
python進程管理工具supervisor的安裝與使用教程
supervisor是用python寫的一個進程管理工具,用來啟動,重啟,關閉進程。下面這篇文章主要給大家介紹了關于python實現(xiàn)的進程管理工具supervisor的安裝與使用的相關資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-09-09

