使用python脚本,批量修改mysql数据库表字段名称
前提:搭建python相关环境
目的:
将驼峰式命名或混合大小写的字段名转换为下划线分隔的小写字段名。 例如:UserName -> user_name, userName -> user_name
一、新建脚本 update_table_column_names.py
import pymysql import re import sys def to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() # 获取命令行参数,如果存在则使用指定表名,否则为空 specified_table = sys.argv[1] if len(sys.argv) > 1 else None # 连接数据库 conn = pymysql.connect(host='192.168.1.1', port=3306, user='root', password='123456', db='test') cursor = conn.cursor() if specified_table: tables = [(specified_table,)] else: # 获取所有表名 cursor.execute("SHOW TABLES") tables = cursor.fetchall for table in tables: original_table_name = table[0] new_table_name = to_snake_case(original_table_name) if original_table_name != new_table_name: # 使用 ALTER TABLE 语句修改表名 cursor.execute(f"ALTER TABLE `{original_table_name}` RENAME TO `{new_table_name}`") # 获取表的所有列及其详细信息,包括注释 cursor.execute(f"SHOW FULL COLUMNS FROM `{new_table_name}`") columns = cursor.fetchall() for column in columns: column_name = column[0] column_type = column[1] is_nullable = "NULL" if column[3] == "YES" else "NOT NULL" default_value = f"DEFAULT {column[5]}" if column[5] else "" extra = column[6] column_comment = column[8] new_column_name = to_snake_case(column_name) if column_name != new_column_name: # 保留注释、默认值等元数据 cursor.execute(f"""ALTER TABLE `{new_table_name}` CHANGE COLUMN `{column_name}` `{new_column_name}` {column_type} {is_nullable} {default_value} {extra} COMMENT '{column_comment}'""") conn.commit() cursor.close() conn.close()
二、执行脚本命令
注意:默认不写表名称,则更新所有的表
py .\update_table_column_names.py table_name
本文作者:lwqblog
本文链接:https://www.cnblogs.com/lwqstyle/p/18631079
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2017-12-25 Python 爬虫 校花网
2017-12-25 Python 环境搭建