首页 > 解决方案 > Pandas To_SQL 给出 DataError: (pyodbc.DataError) ('22018', "[22018] [Microsoft][ODBC SQL Server Driver][SQL Server]

问题描述

我正在尝试使用 sqlalchemy to_sql 在 SQL 服务器中加载 excel 文件。当我运行代码时,它给了我以下错误。

quoted = urllib.parse.quote_plus("Driver={SQL Server};"
                                 "Server=XYZ;"
                                 "Database=SNOW;"
                                 "Trusted_Connection=yes;")
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted))

data = pd.read_excel(r'I:\ESS_ITRS_STATS_DATA.xlsx')
# rename columns
data = data.rename(columns={'Gateway': 'Gateway',
                            'Severity': 'Severity',
                            'Country': 'Country',
                            'CSIID': 'CSI_ID',
                            'NetProbe': 'NetProbe',
                            'Entity': 'Entity',
                            'Sampler': 'Sampler',
                            'Variable': 'Variable',
                            'Hostname': 'Hostname',
                            'Absolute_path': 'Absolute_path',
                            'Date': 'Date',
                            'Description': 'Description',
                            'InsertedDateTime': 'InsertedDateTime'})
df = pd.DataFrame(data, columns=['Gateway','Severity','Country','CSI_ID','NetProbe','Entity','Sampler','Variable','Hostname','Absolute_path','Date','Description','InsertedDateTime'])
df['InsertedDateTime'] = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
df = df.fillna(value=0)
df['CSI_ID'] = df['CSI_ID'].astype(str)
table_name='ITRSALERTS_TEMP'
df.to_sql(table_name,engine,index=False,if_exists="append",schema="dbo", chunksize=25,dtype={col_name: NVARCHAR for col_name in df})

我收到以下错误

DataError: (pyodbc.DataError) ('22018', "[22018] [Microsoft][ODBC SQL Server Driver][SQL Server] 将 nvarchar 值 '95.89' 转换为数据类型 int 时转换失败。(245) (SQLExecDirectW) ")

以下是我的excel中的内容

网关 严重性 国家 CSIID NetProbe 实体采样器变量 主机名 Absolute_path 日期 描述 InsertedDateTime

SST_ISSUER01_NAM_PROD 关键美国 0 XYZ-1 XYZ-H-1 CPU _Total.%processorTime XYZ-H-1 0 2020-09-20T15:12:35 95.89 2020-09-21 18:12:57

标签: pythonpandas

解决方案


显然数据库中的数据类型和数据框中的数据类型不匹配:数据库期望值 '95.89' 是数字,并作为字符串发送。您应该将其转换为适当的类型,可能会以与 CSI_ID 列相同的方式对其进行舍入(取决于数据库表定义):

df['Description'] = df['Description'].astype(float)

推荐阅读