import pyodbc
import re

# 连接到数据库
def get_db_connection(server, port, database, username, password):
    # 使用指定的端口连接数据库
    conn = pyodbc.connect(f'DRIVER={{SQL Server}};SERVER={server},{port};DATABASE={database};UID={username};PWD={password}')
    return conn

# 将驼峰命名转换为下划线命名
def camel_to_snake(camel_str):
    return re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', camel_str).lower()

# 获取表的字段名
def get_column_names(conn, table_name):
    cursor = conn.cursor()
    cursor.execute(f"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{table_name}'")
    columns = [row[0] for row in cursor.fetchall()]
    return columns

# 修改字段名
def rename_column(conn, table_name, old_column, new_column):
    cursor = conn.cursor()
    try:
        cursor.execute(f"EXEC sp_rename '{table_name}.{old_column}', '{new_column}', 'COLUMN';")
        print(f"成功将字段 {old_column} 修改为 {new_column}")
    except Exception as e:
        print(f"修改字段 {old_column} 失败: {e}")

# 批量修改表的字段名
def rename_columns_in_table(conn, table_name):
    columns = get_column_names(conn, table_name)
    
    for column in columns:
        new_column = camel_to_snake(column)
        if new_column != column:  # 如果新字段名与原字段名不同,才进行修改
            rename_column(conn, table_name, column, new_column)

if __name__ == '__main__':
    # 数据库连接信息
    server = '你的服务器地址'       # 例如:'localhost' 或 '192.168.1.100'
    port = '你的数据库端口'         # 例如:'1433'
    database = '你的数据库名称'      # 例如:'my_database'
    username = '你的用户名'         # 例如:'sa'
    password = '你的密码'           # 例如:'your_password'

    # 表名
    table_name = '你的表名'         # 例如:'SalaryMGT_pieceworksalary'

    try:
        # 连接到数据库
        conn = get_db_connection(server, port, database, username, password)
        print(f"成功连接到数据库 {database}")

        # 批量修改字段名
        rename_columns_in_table(conn, table_name)

        # 提交并关闭连接
        conn.commit()
        conn.close()

    except Exception as e:
        print(f"发生错误: {e}")