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

将Pandas数据导入SQL Server遇INT转BIGINT不支持错误求助

Pandas导入SQL Server表的类型错误解决方法

你遇到的问题有两个核心原因,对应以下修复方案:

1. 修复INSERT语句的语法错误

你的SQL语句存在括号不闭合的语法问题,这会导致执行报错,同时也可能干扰类型转换的判断逻辑。修正后的语句如下:

cursor.execute("INSERT INTO my_table (account, info, start_date) VALUES(?, ?, ?)", values)

2. 解决INT到BIGINT的类型转换问题

SQL Server的bigint字段需要匹配Python原生int类型,而Pandas的int64在通过pyodbc传递时,可能被识别为不兼容的参数类型,你可以通过两种方式解决:

方式一:逐行插入时显式转换account类型

构造参数时,将account转为Python原生int类型:

for index, row in combined_df.iterrows():
    # 显式转换account为Python int
    values = (int(row.account), row.info, row.start_date)
    cursor.execute("INSERT INTO my_table (account, info, start_date) VALUES(?, ?, ?)", values)

如果account列存在空值(NaN),需要先处理空值再转换:

import pandas as pd

for index, row in combined_df.iterrows():
    account_val = int(row.account) if pd.notna(row.account) else None
    values = (account_val, row.info, row.start_date)
    cursor.execute("INSERT INTO my_table (account, info, start_date) VALUES(?, ?, ?)", values)

方式二:使用Pandas to_sql批量导入(更高效)

逐行插入效率极低,推荐用to_sql批量处理,它会自动适配大部分类型映射:

from sqlalchemy import create_engine

# 替换为你的SQL Server连接信息
conn_str = "mssql+pyodbc://用户名:密码@服务器名/数据库名?driver=ODBC+Driver+17+for+SQL+Server"
engine = create_engine(conn_str)

# 追加数据到现有表,index=False不导入索引列
combined_df.to_sql('my_table', engine, if_exists='append', index=False)

如果仍有类型匹配问题,可通过dtype参数强制指定映射关系:

from sqlalchemy.types import BigInteger, NVARCHAR, DateTime

combined_df.to_sql(
    'my_table',
    engine,
    if_exists='append',
    index=False,
    dtype={
        'account': BigInteger(),
        'info': NVARCHAR(length=500),
        'start_date': DateTime()
    }
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:15:16