You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将指定嵌套列表写入SQL Server数据库表?

实现将嵌套列表写入SQL Server的Python代码

核心思路

  • 修正文件读取逻辑:原文件内容是标准Python列表格式,不能用split(':')解析,需用ast.literal_eval直接解析每行的列表结构。
  • 将嵌套列表转为字典,方便提取字段与对应值。
  • 使用pyodbc库连接SQL Server,完成表创建(按需)和数据批量插入操作。

完整代码

import ast
import pyodbc

# 1. 读取并解析文件中的嵌套列表
data_list = []
with open('files.txt', 'r') as file:
    for line in file:
        line = line.strip()
        if not line:
            continue
        # 直接解析每行的Python列表格式内容
        nested_list = ast.literal_eval(line)
        # 转成字典,方便后续提取字段值
        data_dict = dict(nested_list)
        data_list.append(data_dict)

# 2. 连接SQL Server并插入数据
# 替换为你的数据库连接参数
server = '你的服务器名称'
database = '你的数据库名称'
username = '你的用户名'
password = '你的密码'
conn_str = f'DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'

try:
    # 建立数据库连接
    conn = pyodbc.connect(conn_str)
    cursor = conn.cursor()

    # 先创建目标表(如果表不存在)
    create_table_sql = """
    IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'StudentScores')
    CREATE TABLE StudentScores (
        ID VARCHAR(10) NOT NULL,
        Name VARCHAR(50) NOT NULL,
        Score INT NOT NULL,
        Semester VARCHAR(20) NOT NULL
    )
    """
    cursor.execute(create_table_sql)
    conn.commit()

    # 批量插入数据
    insert_sql = """
    INSERT INTO StudentScores (ID, Name, Score, Semester)
    VALUES (?, ?, ?, ?)
    """
    # 整理成SQL插入需要的元组列表
    insert_values = [(item['ID'], item['Name'], int(item['Score']), item['Semester']) for item in data_list]
    cursor.executemany(insert_sql, insert_values)
    conn.commit()

    print(f"成功插入{len(insert_values)}条数据")

except Exception as e:
    print(f"操作失败: {str(e)}")
finally:
    # 关闭数据库连接
    if conn:
        cursor.close()
        conn.close()

注意事项

  • 先安装依赖库:执行pip install pyodbc安装SQL Server驱动工具。
  • 代码中的服务器、数据库、账号密码需替换为你的实际信息。
  • 若想保留Score的字符串类型,去掉int()转换,同时将表结构中Score的类型改为VARCHAR(10)。

内容的提问来源于stack exchange,提问作者Aftab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:16:05