python 大量刪除mysql首碼相同的表

來源:互聯網
上載者:User

標籤:模糊比對   .com   提交   lin   維護   mysq   遊戲   2016年   結果   

1,一般遊戲log資料庫會儲存大量的玩家行為日誌,一種行為一張表,每天產生一張新表,一天會有30+張不同行為的表,通常會保留玩家日誌1年左右,對於超過1年的日誌需要刪除

2,log資料庫一年會儲存1W多張表格,用python寫個工具,來高效批量的刪除表格

 

解決思路:

1,分析表名,找出相同的規律,本人維護的遊戲log庫表名尾碼通常是以 年+月+日產生的,有了這個規律就好辦了

2,用一條sql文法產生出drop table 表名

#下面這條文法是模糊比對找出2016年的所有表,然後產生‘drop table ‘, table_name, ‘;‘刪除文法

select CONCAT( ‘drop table ‘, table_name, ‘;‘ ) FROM information_schema.tables Where table_name LIKE ‘%_16%‘;

執行結果如下:

drop table LogAccLogout_160401;
drop table LogAccLogout_160402;
drop table LogAccLogout_160403;

drop table OpTradeInfo_160421;

drop table OpTradeInfo_160422;
drop table OpTradeInfo_160423;
drop table OpTradeInfo_160424;

 

3,先把執行的結果儲存在檔案中,用來給python指令碼讀取用的

4,python迴圈逐行讀取剛剛儲存的檔案,然後mysql模組登陸mysql伺服器

用模組是MySQLdb,安裝方法:yum -y install MySQL-python*

 

代碼如下:

#!/usr/bin/python# -*- coding: UTF-8 -*-import MySQLdbdb = MySQLdb.connect("192.168.135.156","mysql_user","mysql_password","game_log" )cursor = db.cursor() #獲得mysql遊標open_file = open(‘jieguo_result_201_17.txt‘,‘r‘) #先開啟已儲存的檔案for line in open_file.readlines():  #for迴圈逐行讀取每條    try:        print line,        cursor.execute(line) #執行sql刪除文法        db.commit()    #提交請求    except Exception as e:        print e        if e:      #遇到錯誤直接跳過,繼續執行後面的刪除文法            continuedb.close()open_file.close()

 

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.