Python to_sql()错误:TypeError:需要字节,找到str

Python to_sql()错误:TypeError:需要字节,找到str,python,pandas,sqlalchemy,pyodbc,Python,Pandas,Sqlalchemy,Pyodbc,我正在尝试将df从Python上传到sql server 步骤: 从excel(xlsx)导入的文件--OK sqlalchemy引擎-正常 错误: SystemError:返回了一个带有错误集的结果。 需要字节,找到str df.info()给出: col1 5490 non-null int64 col2 5414 non-null object col3 5490 non-null object col4

我正在尝试将df从Python上传到sql server

步骤:

  • 从excel(xlsx)导入的文件--OK
  • sqlalchemy引擎-正常
  • 错误: SystemError:返回了一个带有错误集的结果。 需要字节,找到str

    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 server成功

    粘贴整个错误堆栈跟踪。
    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