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:<blockquote>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xd3' in position 49: ordinal not in range(128)</blockquote>
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.
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)." rel="nofollow noreferrer">this</a> answer I thought mystring.encode('utf-8) would work.
I cheked the type of my string with <a href="https://stackoverflow.com/questions/4987327/how-do-i-check-if-a-string-is-unicode-or-ascii" rel="nofollow">this</a> method just in case and the result is 'ordinary string'.Answer1:
Adding this to my python code solved it.
import os os.environ["NLS_LANG"] = "SPANISH_SPAIN.UTF8"