【发布时间】:2020-09-23 15:40:49
【问题描述】:
我正在尝试使用 sqlalchemy to_sql 在 SQL Server 中加载 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
【问题讨论】: