我正在使用Pandas、MySQL和SQLAlchemy。
我正在使用pandas.to_sql()将包含非ASCII文本的pandas数据帧提交到MySQL数据库。注意,对于我使用过的其他数据帧,我的过程工作得很好
但是,对于非ascii文本,以下调用会引发错误:
df.to_sql(
name='tableOne',
con=engine,
index=False,
if_exists='replace')
结果错误(最后一行):
UnicodeEncodeError: 'ascii' codec can't encode character '\xe5' in position 143: ordinal not in range(128)
在阅读了类似的文章之后,我发现答案是在引擎中指定“utf8”,如下所示:
engine = create_engine(f'mysql+mysqldb://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DATABASE}?charset=utf8', encoding="utf8")
我已经尝试了我能想到的一切,我能在网上找到的一切。我把我的引擎改成包括所有的“utf8”、“utf-8”等。我试过手动将DF的每个文本列编码为utf-8。这些都不管用
我已经完成了以下其他类似的SO帖子,这些帖子似乎有类似的问题,因此也有类似的解决方案,但是没有什么对我有效:
Another UnicodeEncodeError when using pandas method to_sql with MySQL
How to handle encoding in Python 2.7 and SQLAlchemy 🏴ââ ï¸
How do I get SQLAlchemy to correctly insert a unicode ellipsis into a mySQL table?
convert pandas dataframe to utf8
谢谢你的帮助!
编辑:fixed brainfart:'Unicode'->'ascii'