无法从oracle数据库读取特殊字符

not able to read Special characters from oracle database

我正在 python 中从 oracle 数据库中读取一些文本数据。我必须标记具有一些特殊字符的值,并根据其值将其更改为特定的值 有些名字有 ±、Ł 等特殊字符。

虽然有些人正在按原样阅读。但是 ± 被读取为 A。因此,即使数据库中的数据值是特殊字符,我的 python 代码也没有标记它。

我什至尝试在连接到数据库时使用 encoding='iso-8859-1',但它没有按原样读取和显示字符,而是显示倒置的问号。

请帮助我如何按原样阅读 python 中的这些字符。

我正在使用 cx_Oracle 连接到数据库。 数据库中的列有一个值:Mąrią。

在连接到数据库时不使用任何编码,python 正在以 Maria 的身份读取此值。 但我希望它的形式与数据库中的形式相同 即 Expected_output : Mąrią。 如果我添加 encoding='iso-8859-1' 我得到的输出是 'M¿ri¿'

import cx_Oracle
conn=cx_Oracle.connect('username','pwd','hostname/servicename')
c=conn.cusrsor()
sql='select name from con where id='123' #output of this in db is :Mąrią
z=pd.read_sql(sql,conn)

输出 python:玛丽亚

预期输出:与 DB 中的相同,即:Mąrią

如果我将连接更改为: conn=cx_Oracle.connect('username','pwd','hostname/servicename',encoding='iso- 8859-1')

在python中的输出:'M¿ri¿'

预期输出:与 DB 中的相同,即:Mąrią

我会使用对象连接的编码和 nencoding 属性,而且我会在执行连接之前加载你的 NLS_LANG 变量(如果你在 8.0 之前使用 cx_Oracle。如果你使用cx_Oracle 8.0,你不需要这样做)。最好始终使用 UTF-8,因为它是迄今为止最合适的。

import os
import cx_Oracle
os.environ["NLS_LANG"] = 'YOUR_NLS_LANG_VARIABLE'
conn=cx_Oracle.connect('username','pwd','hostname/servicename',encoding="UTF-8", nencoding="UTF-8")
c=conn.cusrsor()
sql='select name from con where id='123' #output of this in db is :Mąrią
z=pd.read_sql(sql,conn)

例子

我的python程序

import os
import cx_Oracle
os.environ["NLS_LANG"] = 'american_america.al32utf8'
connection = cx_Oracle.connect("TEST", "test_1", "180.22.128.47:60995/odcgrc1r" , encoding="UTF-8", nencoding="UTF-8")
cur = connection.cursor()
cur.execute("select 'Maria and ÄeÜöI' from dual")
while True:
    row = cur.fetchone()
    if row is None:
        break
    print(row)

运行 我的 windows

 c:\python>python.exe c:\python\examples\testoracle.py
('Maria and ÄeÜöI',)

c:\python>

更新

如果您使用的是 cx_Oracle 8.0,则默认值为 UTF-8:

设置客户端字符集 在 cx_Oracle8 中,用于所有字符数据的默认编码更改为“UTF-8”。这种通用编码适用于大多数应用程序。如果有特殊需求,可以将encoding和nencoding参数传给cx_Oracle.connect()