Handling accents in Oracle from Python
<p>I have the following code:</p>

<pre><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()
</code></pre>

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

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

<p>I've tried the solutions from some other questions here:</p>

<pre><code>query.decode('utf-8')
query.encode('utf-8')
query.decode('unicode')
query.encode('unicode')
</code></pre>

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

<p>Because of this my query doesn't get to Oracle how it should.</p>

<p><strong>ADDITIONAL INFO:</strong></p>

<p>Based on <a href="http://So%20your%20variable%20either%20contains%20a%20unicode%20string%20or%20a%20byte%20string.%20If%20it%20is%20a%20unicode%20string%20you%20can%20just%20do%20appName.encode(%22utf-8%22).">this</a> answer I thought mystring.encode('utf-8) would work.</p>

<p>I cheked the type of my string with <a href="http://stackoverflow.com/questions/4987327/how-do-i-check-if-a-string-is-unicode-or-ascii">this</a> method just in case and the result is 'ordinary string'.</p>

<p>Adding this to my python code solved it. </p>

<pre><code>import os
os.environ["NLS_LANG"] = "SPANISH_SPAIN.UTF8"
</code></pre>

python oracle unicode ascii