2017-06-17 97 views
0

免责声明解码字节0×81:我有编码的斗争。SQLAlchemy的编解码器无法与Oracle WE8ISO8859P1编码

我使用SQLAlchemy的拉从Oracle 12数据库中的某些数据与WE8ISO8859P1字符集(根据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:[email protected]: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机器,但我看到UTF-8与其他Windows客户端)
  2. 尝试更改编码create_engine脚本? (我试图通过encoding='WE8ISO8859P1',并没有接受
  3. 尝试捕获错误并将值更改为其他

奖金:?究竟是什么0×81也许这甚至不应该在一个人的名字编码

+1

请注明完整回溯cx_Oracle将自动完成转换的字符串。 –

回答

0

您有几种选择:?

conn = cx_Oracle.connect("user/[email protected]", encoding = "ISO-8859-1", nencoding = "UTF-8") 

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

NLS_LANG=.WE8ISO8859P1 
NLS_LNCHAR=AL32UTF8 

请注意,还可以使用编码= “UTF-8” 在cx_Oracle连接()方法,作为ISO-8859-1被容易地转换为UTF-8。如果你正在使用Python 3

相关问题