使用python脚本连接SQL Server数据库导出表结构

一. 准备工作

Mac 系统安装freetds

复制代码
brew install freetds

安装pymssql

复制代码
pip3 install pymssql

二.导出指定表的结构:

复制代码
import pymssql

# 配置数据库连接参数(根据实际情况修改)
server = ''      # 内网服务器地址或IP
database = ''  # 数据库名称
port = '1433'
username = ''       # 登录账号
password = ''       # 登录密码
table_name = ''   # 需要导出结构的表名
output_file = 'table_structure.txt'  # 输出文件名

try:
    conn = pymssql.connect(server=server, port=port, user=username, password=password, database=database,tds_version="7.0")
    # 创建游标对象
    cursor = conn.cursor()

    # 查询表结构
    query = (
        "SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE "
        "FROM INFORMATION_SCHEMA.COLUMNS "
        f"WHERE TABLE_NAME = '{table_name}'"
        )
    cursor.execute(query)
    columns = cursor.fetchall()


    if not columns:
        print(f"表 '{table_name}' 不存在或没有列信息")
    else:
        # 构建输出内容
        output = []
        output.append(f"表结构:{table_name}\n")
        header = "列名 | 数据类型 | 最大长度 | 允许空 | 主键"
        separator = "--- | --- | --- | --- | ---"
        output.extend([header, separator])

        for col in columns:
            col_name, data_type, max_len, is_null = col
            col_info = [
                col_name,
                data_type,
                str(max_len) if max_len else "N/A",
                "是" if is_null == 'YES' else "否"
            ]
            output.append(" | ".join(col_info))

        # 写入文件
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(output))

        print(f"表结构已成功导出到 {output_file}")

except pymssql.Error as e:
    print(f"数据库连接错误: {str(e)}")
except Exception as e:
    print(f"发生错误: {str(e)}")
finally:
    # 确保关闭数据库连接
    if 'conn' in locals():
        conn.close()

注意修改脚本中的以下参数值:

server = ''

database = ''

port = '1433'

username = ''

password = ''

同时要注意提供的username要有指定数据库的权限。

三. 导出指定数据库的所有非空表的结构,包含字段名称,类型,注释。

复制代码
import pymssql

# 配置数据库连接参数(根据实际情况修改)
server = ''
database = ''
port = '1433'
username = ''
password = ''
output_file = 'table_structure.txt'

try:
    # 建立数据库连接
    conn = pymssql.connect(server=server, port=port, user=username, password=password, database=database,
                           tds_version="7.0")
    cursor = conn.cursor()

    # 获取所有表名和对应的架构
    cursor.execute("SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'")
    all_tables = cursor.fetchall()

    tables_with_data = []
    for schema, table_name in all_tables:
        try:
            # 查询表是否有数据
            data_query = f"SELECT COUNT(*) FROM [{schema}].[{table_name}]"
            cursor.execute(data_query)
            count = cursor.fetchone()[0]
            if count > 0:
                # 查询表注释
                comment_query = f"""
                    SELECT ISNULL(ep.value, '')
                    FROM sys.extended_properties ep
                    WHERE ep.major_id = OBJECT_ID('[{schema}].[{table_name}]') AND ep.minor_id = 0
                """
                cursor.execute(comment_query)
                result = cursor.fetchone()
                # 处理表注释为空的情况
                table_comment = result[0] if result else ""
                tables_with_data.append((schema, table_name, table_comment))
        except pymssql.Error as e:
            print(f"查询表 {schema}.{table_name} 时出现数据库错误: {str(e)}")

    if not tables_with_data:
        print("未找到有数据的表")
    else:
        output = []
        for schema, table_name, table_comment in tables_with_data:
            output.append(f"表名:{schema}.{table_name}")
            output.append(f"表注释:{table_comment}")
            output.append("表结构:")

            try:
                # 查询表结构及字段备注
                column_query = f"""
                    SELECT 
                        c.COLUMN_NAME, 
                        c.DATA_TYPE, 
                        c.CHARACTER_MAXIMUM_LENGTH, 
                        c.IS_NULLABLE,
                        ISNULL(ep.value, '') AS COLUMN_COMMENT
                    FROM 
                        INFORMATION_SCHEMA.COLUMNS c
                    LEFT JOIN 
                        sys.extended_properties ep 
                    ON 
                        ep.major_id = OBJECT_ID('[{schema}].[{table_name}]') 
                        AND ep.minor_id = c.ORDINAL_POSITION
                    WHERE 
                        c.TABLE_NAME = '{table_name}' 
                        AND c.TABLE_SCHEMA = '{schema}'
                """
                cursor.execute(column_query)
                columns = cursor.fetchall()

                header = "列名 | 数据类型 | 最大长度 | 允许空 | 字段备注"
                separator = "--- | --- | --- | --- | ---"
                output.extend([header, separator])

                for col in columns:
                    col_name, data_type, max_len, is_null, col_comment = col
                    col_info = [
                        col_name,
                        data_type,
                        str(max_len) if max_len else "N/A",
                        "是" if is_null == 'YES' else "否",
                        col_comment
                    ]
                    output.append(" | ".join(col_info))
            except pymssql.Error as e:
                print(f"查询表 {schema}.{table_name} 的结构时出现数据库错误: {str(e)}")

            output.append("\n")

        # 写入文件
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(output))

        print(f"有数据的表结构已成功导出到 {output_file}")

except pymssql.Error as e:
    print(f"数据库连接错误: {str(e)}")
except Exception as e:
    print(f"发生未知错误: {str(e)}")
finally:
    # 确保关闭数据库连接
    if 'conn' in locals():
        conn.close()

同样注意修改以下内容:

server = ''

database = ''

port = '1433'

username = ''

password = ''

相关推荐
PXM的算法星球40 分钟前
数据库分库分表实战指南:从原理到落地
数据库
我科绝伦(Huanhuan Zhou)1 小时前
Redis再次开源!reids8.0.0一键安装脚本分享
数据库·redis·开源
Kookoos1 小时前
基于 PostgreSQL 的 ABP vNext + ShardingCore 分库分表实战
数据库·docker·postgresql·c#·.net
Y3174291 小时前
Python Day 22 学习
python·学习
czhc11400756631 小时前
Linux511SSH连接 禁止root登录 服务任务解决方案 scp Vmware三种模式回顾
运维·服务器·数据库
正在走向自律2 小时前
Python 自动化脚本开发秘籍:从入门到实战进阶(6/10)
开发语言·python
白熊1882 小时前
【计算机视觉】基于Python的相机标定项目Camera-Calibration深度解析
python·数码相机·计算机视觉
仙人掌_lz2 小时前
深入理解深度Q网络DQN:基于python从零实现
python·算法·强化学习·dqn·rl
码农黛兮_462 小时前
数据库备份与策略【全量备份、增量备份、日志恢复】
数据库
向哆哆2 小时前
Hibernate 性能优化:告别慢查询,提升数据库访问性能
java·数据库·性能优化·hibernate