UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 54: ordinal not in range(128)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 54: ordinal not in range(128)
我知道,已经被问过好几次了,但是 none 的答案给了我一个解决方案
这是代码 (Python 2.7):
import cx_Oracle
import pandas as pd
connstr = 'MyConstr'
conn = cx_Oracle.connect(connstr)
cur = conn.cursor()
xl = pd.ExcelFile("C:\TEMP\for_kkod.xlsx")
df = xl.parse(0)
for i in df.index:
s = u"insert into MY_TABLE values({0}, '{1}')".format(int(df.iloc[i]['kkod']), df.iloc[i]['kkodnev'])
print s
print type(s)
cur.execute(s)
2 次打印的结果是:
insert into MY_TABLE values(10, 'Készítés')
<type 'unicode'>
如您所见,s 的类型是 unicode,但我仍然收到此错误消息:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 54: ordinal not in range(128)
我试过使用和不使用 u"",使用和不使用所有可能的方式进行编码和解码,但仍然出现相同的错误消息
有什么想法吗?
您正在向 cursor.execute()
提供 Unicode SQL 语句。该方法只能采用 bytestring SQL 语句.
您不应使用字符串插值将您的 Unicode 值插入 SQL 查询(它本身只是 ASCII)。始终使用查询参数!
s = "insert into MY_TABLE values(:0, :1)"
cur.execute(s, (int(df.iloc[i]['kkod']), df.iloc[i]['kkodnev']))
现在要插入的值作为参数传入,由数据库适配器负责编码这些正确性(以及正确转义值以规避 SQL 注入问题)。
以上使用编号(位置)参数,你也可以使用命名参数,传入字典中的值与匹配的键:
s = "insert into MY_TABLE values(:kkod, :kkodnev)"
cur.execute(s, {'kkod': int(df.iloc[i]['kkod']), 'kkodnev': df.iloc[i]['kkodnev']})
您必须确保您的连接和 table 列都正确配置为处理 Unicode。例如,您必须设置 NLS_LANG
选项:
import os
os.environ['NLS_LANG'] = '.AL32UTF8'
只需使用以下参数进行连接:
connection = cx_Oracle.connect(connectString, encoding="UTF-8",nencoding="UTF-8")
我知道,已经被问过好几次了,但是 none 的答案给了我一个解决方案
这是代码 (Python 2.7):
import cx_Oracle
import pandas as pd
connstr = 'MyConstr'
conn = cx_Oracle.connect(connstr)
cur = conn.cursor()
xl = pd.ExcelFile("C:\TEMP\for_kkod.xlsx")
df = xl.parse(0)
for i in df.index:
s = u"insert into MY_TABLE values({0}, '{1}')".format(int(df.iloc[i]['kkod']), df.iloc[i]['kkodnev'])
print s
print type(s)
cur.execute(s)
2 次打印的结果是:
insert into MY_TABLE values(10, 'Készítés')
<type 'unicode'>
如您所见,s 的类型是 unicode,但我仍然收到此错误消息:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 54: ordinal not in range(128)
我试过使用和不使用 u"",使用和不使用所有可能的方式进行编码和解码,但仍然出现相同的错误消息
有什么想法吗?
您正在向 cursor.execute()
提供 Unicode SQL 语句。该方法只能采用 bytestring SQL 语句.
您不应使用字符串插值将您的 Unicode 值插入 SQL 查询(它本身只是 ASCII)。始终使用查询参数!
s = "insert into MY_TABLE values(:0, :1)"
cur.execute(s, (int(df.iloc[i]['kkod']), df.iloc[i]['kkodnev']))
现在要插入的值作为参数传入,由数据库适配器负责编码这些正确性(以及正确转义值以规避 SQL 注入问题)。
以上使用编号(位置)参数,你也可以使用命名参数,传入字典中的值与匹配的键:
s = "insert into MY_TABLE values(:kkod, :kkodnev)"
cur.execute(s, {'kkod': int(df.iloc[i]['kkod']), 'kkodnev': df.iloc[i]['kkodnev']})
您必须确保您的连接和 table 列都正确配置为处理 Unicode。例如,您必须设置 NLS_LANG
选项:
import os
os.environ['NLS_LANG'] = '.AL32UTF8'
只需使用以下参数进行连接:
connection = cx_Oracle.connect(connectString, encoding="UTF-8",nencoding="UTF-8")