Python批量刪除mysql中千萬(wàn)級(jí)大量數(shù)據(jù)的腳本分享
場(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腳本批量刪除吧。具體思路是:
每次只刪除一天的數(shù)據(jù); 刪除一天的數(shù)據(jù),每次刪除50000條; 一天的數(shù)據(jù)刪除完,開(kāi)始刪除下一天的數(shù)據(jù);Python代碼
# -*-coding:utf-8 -*-import sys# 這是我們內(nèi)部封裝的Python Modulesys.path.append(’/var/lib/hadoop-hdfs/scripts/python_module2’)import keguang.commons as commonsimport keguang.timedef as timedefimport keguang.sql.mysqlclient as mysqldef 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)
以上就是Python批量刪除mysql中千萬(wàn)級(jí)大量數(shù)據(jù)的腳本的詳細(xì)內(nèi)容,更多關(guān)于python 刪除MySQL數(shù)據(jù)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?2. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)車輛管理系統(tǒng)3. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算4. ASP.Net MVC利用NPOI導(dǎo)入導(dǎo)出Excel的示例代碼5. jstl 字符串處理函數(shù)6. JSP動(dòng)態(tài)網(wǎng)頁(yè)開(kāi)發(fā)原理詳解7. PHP中為什么使用file_get_contents("php://input")接收微信通知8. .Net core Blazor+自定義日志提供器實(shí)現(xiàn)實(shí)時(shí)日志查看器的原理解析9. IOS蘋(píng)果AppStore內(nèi)購(gòu)付款的服務(wù)器端php驗(yàn)證方法(使用thinkphp)10. XML CDATA是什么?
