標籤:解釋 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批量修改相同尾碼表名