【问题标题】:to_sql() error: TypeError: expected bytes, str foundto_sql() 错误:TypeError:预期字节,找到 str
【发布时间】:2020-12-18 18:15:37
【问题描述】:

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

步骤:

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

错误: SystemError: 返回带有错误集的结果。 预期字节数,str 找到

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 找到

【问题讨论】:

  • 粘贴整个错误堆栈跟踪。

标签: python pandas sqlalchemy pyodbc


【解决方案1】:

我的解决办法是改变 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成功

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2020-05-29
    相关资源
    最近更新 更多