SQLAlchemy编解码器无法使用Oracle WE8ISO8859P1编码

时间:2017-06-17 01:10:55

标签: python oracle encoding sqlalchemy cx-oracle

免责声明:我为编码而烦恼。

我使用SQLAlchemy从带有 WE8ISO8859P1 字符集的Oracle 12数据库中提取一些数据(根据 NLS_CHARACTERSET

在某个地方,数据库中有一个值(假设一个人的名字),当值传递给Python时,它会抛出错误。

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 4: character maps to <undefined>

代码是:

Base = declarative_base()

class Person(Base):
    __tablename__= 'PERSON'

    id = Column(Integer,primary_key=True)
    lastname = Column(String)
    firstname = Column(String)
    middlename = Column(String)
    active = Column(Integer)  
    sex = Column(String)
    dateofbirth = Column(String)

engine = create_engine('oracle://USER:PASS@xxx.xxx.xxx.xxx:1521/ORCL', echo=True)

Session = sessionmaker(bind=engine)

session = Session()

testList = []


for user in session.query(Person).all():
    testList.append(user)

签入oracle v $ session_connect_info我看到运行此代码的客户端正在连接字符集 WE8MSWIN1252

我知道Python使用Unicode,所以看起来我有3种不同的编码不匹配,我真的不知道从哪里开始。

我应该......

  1. 尝试更改oracle客户端上的编码(Windows机器,但我看到其他Windows客户端使用UTF-8连接)
  2. 尝试更改create_engine脚本中的编码? (我试图通过encoding='WE8ISO8859P1'并且它没有接受。
  3. 尝试捕获错误并将值更改为其他内容。
  4. 奖励:0x81究竟是什么?也许这不应该以一个人的名字编码?

1 个答案:

答案 0 :(得分:1)

您有几个选择:

conn = cx_Oracle.connect("user/pw@tns", encoding = "ISO-8859-1", nencoding = "UTF-8")

或者您可以简单地设置环境变量NLS_LANG和NLS_NCHAR

NLS_LANG=.WE8ISO8859P1
NLS_LNCHAR=AL32UTF8

请注意,您还可以使用encoding =&#34; UTF-8&#34;在cx_Oracle connect()方法中,ISO-8859-1很容易转换为UTF-8。如果您使用的是Python 3,cx_Oracle将自动处理转换为字符串。