河曲智叟 发表于 2024-12-25 17:18:19

使用python脚本,批量修改mysql数据库表字段名称

前提:搭建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('(.)(+)', r'\1_\2', name)
    return re.sub('()()', r'\1_\2', s1).lower()

# 获取命令行参数,如果存在则使用指定表名,否则为空
specified_table = sys.argv 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
    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
      column_type = column
      is_nullable = "NULL" if column == "YES" else "NOT NULL"
      default_value = f"DEFAULT {column}" if column else ""
      extra = column
      column_comment = column
      
      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企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 使用python脚本,批量修改mysql数据库表字段名称