前提:搭建python相关情况
目的:- <strong> 将驼峰式命名或混合大小写的字段名转换为下划线分隔的小写字段名。
- 例如:UserName -> user_name, userName -> user_name</strong>
复制代码 一、新建脚本 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
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |