Handling accents in Oracle from Python

喜欢而已 提交于 2020-01-07 02:39:06

问题


I have the following code:

 #!/usr/bin/python
 # coding=UTF-8

import cx_Oracle

def oracle_connection(user, passwd, host, port, service):

    oracle_con_details = user+'/'+passwd+'@'+host+':'+port+'/'+service

    try:

        oracle_connection = cx_Oracle.connect(oracle_con_details)

    except cx_Oracle.DatabaseError as e:

        error, = e.args
        if error.code == 1017:
            log.warning('Please check your credentials.')
        else:
            log.error('Database connection error: ')
            log.error(e)

    return oracle_connection

user_oracle =  "user"
passw_oracle =  "pass"
host_oracle =  "host"
port_oracle =  "port"
service_oracle =  "service"

con_oracle = oracle_connection(user_oracle, passw_oracle, host_oracle, port_oracle, service_oracle)

query = """ SELECT COUNT(*) FROM TABLE WHERE MYDATA = 'REUNIÓN'"""

cursor_oracle = con_oracle.cursor()
cursor_oracle.execute(query)
data_tuple = cursor_oracle.fetchall()

Of course, Oracle credentials and query are just examples. Notice the query has 'Ó' character. This is the one giving me the following error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xd3' in position 49: ordinal not in range(128)

I've tried the solutions from some other questions here:

query.decode('utf-8')
query.encode('utf-8')
query.decode('unicode')
query.encode('unicode')

I understand my string (query) is encoded in unicode but I just don't understand why decoding it in utf-8 doesn't work.

Because of this my query doesn't get to Oracle how it should.

ADDITIONAL INFO:

Based on this answer I thought mystring.encode('utf-8) would work.

I cheked the type of my string with this method just in case and the result is 'ordinary string'.


回答1:


Adding this to my python code solved it.

import os
os.environ["NLS_LANG"] = "SPANISH_SPAIN.UTF8"


来源:https://stackoverflow.com/questions/39975885/handling-accents-in-oracle-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!