从Python处理Oracle中的重音 [英] Handling accents in Oracle from Python

查看:68
本文介绍了从Python处理Oracle中的重音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

 #!/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()

当然,Oracle凭证和查询只是示例.注意查询具有Ó"字符.这是给我以下错误的人:

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'编解码器无法在其中编码字符u'\ xd3' 位置49:序数不在范围内(128)

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')

我知道我的字符串(查询)是用unicode编码的,但我只是不明白为什么在utf-8中解码它不起作用.

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

由于这个原因,我的查询无法到达Oracle应该的状态.

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

其他信息:

基于这个答案,我认为mystring.encode('utf-8)可以工作.

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'.

推荐答案

将其添加到我的python代码中即可解决该问题.

Adding this to my python code solved it.

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

这篇关于从Python处理Oracle中的重音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆