to_sql错误:TypeError:预期的字节,找到str

问题描述

我正在尝试将pythhon中的df上传sql server

步骤:

    从Excel(xlsx)导入的
  1. 文件-确定
  2. sqlalchemy引擎-确定

错误: 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服务器