Python Pandas To_SQL给出了DataError:(pyodbc.DataError)(';22018';,“[22018][Microsoft][ODBC SQL Server驱动程序][SQL Server]
我正在尝试使用sqlalchemy在SQL server中加载excel文件,以加载SQL。当我运行代码时,它给出以下错误Python Pandas To_SQL给出了DataError:(pyodbc.DataError)(';22018';,“[22018][Microsoft][ODBC SQL Server驱动程序][SQL Server],python,pandas,Python,Pandas,我正在尝试使用sqlalchemy在SQL server中加载excel文件,以加载SQL。当我运行代码时,它给出以下错误 quoted = urllib.parse.quote_plus("Driver={SQL Server};" "Server=XYZ;" "Database=SNOW;"
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驱动程序][SQL Server]将nvarchar值'95.89'转换为数据类型int.(245)(SQLExecDirectW)”时转换失败)
下面是我的excel中的内容
网关严重性国家/地区CSID NetProbe实体采样器变量主机名绝对路径日期描述插入数据时间
SST_ISSUER01_NAM_PROD CRITICAL UNITED STATES 0 XYZ-1 XYZ-H-1 CPU总计。%processorTime XYZ-H-1 0 2020-09-20T15:12:35 95.89 2020-09-21 18:12:57显然数据库和数据帧中的数据类型不匹配:数据库期望值“95.89”为数字,并将其作为字符串发送。您应该将其强制转换为适当的类型,即m可以采用与CSI_ID列相同的方式对其进行舍入(取决于数据库表定义):
df['Description'] = df['Description'].astype(float)
显然,数据库中的数据类型与dataframe中的数据类型不匹配:数据库希望值“95.89”为数字,并将其作为字符串发送。您应该将其转换为适当的类型,可能会按照您对CSI_ID列所做的相同方式对其进行四舍五入(取决于数据库表定义):
df['Description'] = df['Description'].astype(float)