MySQL批量修改相同尾碼表名

來源:互聯網
上載者:User

標籤:解釋   object   range   today   mysql   strftime   str   .com   bst   

執行步驟

  1.用concat批量產生修改表名的語句

SELECT CONCAT( ‘ALTER TABLE ‘, table_name, ‘ RENAME TO ‘, substring(table_name,1,locate(‘_postfix‘,table_name)),‘_new_postfix‘,‘;‘ ) FROM information_schema.tables Where table_name LIKE ‘%_postfix‘;

  2.將產生的語句執行一遍即可完成修改

—————————————————————————————————————————————————————————————————————————————————————————————————

MySQL函數解釋:

  1.substring(str,index,num)        從指定字串(str) 截取指定的子串(從index開始截取num個字元)。

  樣本:

select substring(‘class_name‘,2,5) ;

  執行結果為 ‘lass_’

 

  2.locate(cstr,str[,position])    尋找子字串(cstr)在字串(str)中的座標,選擇性參數position意為尋找的起始位置

  樣本:

SELECT locate(‘s‘,‘students_name‘) SELECT locate(‘s‘,‘students_name‘,5) 

  第1條語句執行結果為:1

  第2條語句執行結果為:8

 python指令碼批量修改表名

   工作中的測試環境每天要做初始化工作,需將部分表的名稱由昨天改成當天,故將修改表名的工作寫成了指令碼。

   因表頭已知且一般不會改變,故直接定義了表頭列表inittable_prefix,而沒有使用上述SQL方法(substring)

import MySQLdbimport datetimeimport tracebacktoday = datetime.date.today().strftime(‘%Y%m%d‘)yesterday = (datetime.date.today() - datetime.timedelta(days=1)).strftime(‘%Y%m%d‘)inittable_prefix = [‘exam_table1_‘,‘exam_table2_‘,‘exam_table3_‘,                ‘exam_table4_‘,‘exam_table5_‘,‘exam_table6_‘]today_list = [i+today for i in inittable_prefix]lastday_list = [i+yesterday for i in inittable_prefix]sqllit = [‘ALTER TABLE %s RENAME TO %s‘ % (lastday_list[i],today_list[i]) for i in range(len(inittable_prefix))]class mymysql(object):    def __init__(self):        self.conn = MySQLdb.connect(            host = ‘127.0.0.1‘,            port = 3306,            user = ‘root‘,            passwd = ‘root‘,            db = ‘xt‘)    def renameTable(self,sql_list):        for sql in sql_list:            cur = self.conn.cursor()            try:                cur.execute(sql)                self.conn.commit()            except:                self.conn.rollback()                traceback.print_exc()            finally:                cur.close()    def closeConn(self):        self.conn.close()if __name__ ==‘__main__‘:    co = mymysql()    co.renameTable(sqllit)    co.closeConn()

 

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.