zoukankan      html  css  js  c++  java
  • MySQL批量修改相同后缀表名

    执行步骤

      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 MySQLdb
    import datetime
    import traceback
    
    today = 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()
  • 相关阅读:
    mybatis:SQL拦截器
    eclipse:插件安装总结
    eclpse:安装explorer或eExplorer插件
    Spring Tools4
    nginx+tomcat:动静分离+https
    Tomcat:3DES解密时中文乱码
    wireshark如何抓取localhost包
    nginx: 应用访问默认采用https
    windows :config windows update … 一直处于假死状态
    EHCache:Eelment刷新后,timeToLiveSeconds失效了?
  • 原文地址:https://www.cnblogs.com/zeke-python-road/p/9140105.html
Copyright © 2011-2022 走看看