首页 > 解决方案 > UnicodeEncodeError:在 python 中使用 to_sql 时

问题描述

我正在尝试使用 to_sql 将数据框插入到 oracle 数据库中。下面是代码:

engine = create_engine('oracle+cx_oracle://'+username+':'+password+'@'+host+':'+port+'/'+sid) df.to_sql(name = table.lower(),schema=schema ,con =engine,if_exists = 'replace', index=False)

我收到以下错误:UnicodeEncodeError: 'ascii' codec can't encode character '\u2013' in position 81: ordinal not in range(128)

有人可以帮忙吗?

标签: pythonoracle

解决方案


可能您的数据库是 UTF8 并且您没有在会话中导出 NLS_LANG 变量:

所以我会尝试首先将您的 NLS_LANG 导出到您在数据库中拥有的字符集:

#export NLS_LANG=American_America.AL32UTF8

然后我会尝试在 cx_Oracle.connect 方法中更改您的连接:

connection = cx_Oracle.connect("user/password@connectString",
    encoding="UTF-8", nencoding="UTF-8")

当您使用 to_sql 时,您可以在尝试连接之前尝试此操作

import os
os.environ["NLS_LANG"] = 'YOUR_NLS_LANG_VARIABLE'

推荐阅读