to_sql() error: TypeError: expected bytes, str found
to_sql() error: TypeError: expected bytes, str found
我正在尝试从 python 上传一个 df 到 sql 服务器
步数:
- 从 excel 导入的文件 (xlsx)- OK
- sql炼金引擎- OK
错误:
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 table 中,列类型是 [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 服务器成功
我正在尝试从 python 上传一个 df 到 sql 服务器
步数:
- 从 excel 导入的文件 (xlsx)- OK
- sql炼金引擎- OK
错误:
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 table 中,列类型是 [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 服务器成功