飞机飞过天空,天空之城|

lwqblog

园龄:9年7个月粉丝:10关注:23

2024-12-25 17:41阅读: 113评论: 0推荐: 0

使用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 中国大陆许可协议进行许可。

posted @   lwqblog  阅读(113)  评论(0编辑  收藏  举报
历史上的今天:
2017-12-25 Python 爬虫 校花网
2017-12-25 Python 环境搭建
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起