问题描述
我正在尝试将pythhon中的df上传到sql server
步骤:
错误:
SystemError:
from sqlalchemy import create_engine
import urllib
import pandas as pd
df.to_sql('table_name',con=engine,if_exists='replace',index=False)
df.info()
给出:
col1 5490 non-null int64
col2 5414 non-null object
col3 5490 non-null object
col4 5490 non-null object
col5 3921 non-null object
col6 5490 non-null object
col7 5490 non-null int64
col8 5490 non-null object
col9 5490 non-null object
col10 5490 non-null object
在sql表中,列类型为[int]
和[varchar](max)
错误回溯 TypeError:预期的字节数,找到的str
解决方法
对我来说,解决方案是更改df对象的编码,如下所示:
for name,values in df.iteritems():
if df[name].dtype == 'object':
print(name)
print(df[name].dtype)
df[name] = df[name].str.encode('utf-8')
#print(chardet.detect(df[name][0])['encoding'])
return df
在对utf-8进行编码之后,成功上传到sql服务器