ITPub博客

首页 > 数据治理 > 数据治理 > PYTHON3 cx-Oracle 字符集 转换错误的解决方案

PYTHON3 cx-Oracle 字符集 转换错误的解决方案

原创 数据治理 作者:babyyellow 时间:2020-04-01 16:40:11 0 删除 编辑

Python 3.x 里面 默认的 字符串是  unicode了.


cx-oracle    在支持到 py3.0 的时候,  遇到了字符集转换问题. 


因为 gbk 编码里, 是很多时候, 是可以存一下半个汉子的字符.  


数据库里存储了这些字符, 那么在从数据库到py 的转换过程中就会出现  


字符集转换错误: 


UnicodeDecodeError: 'gbk' codec can't decode byte 0xaa in position 14: illegal multibyte sequence 


很经典的错误. 


当排除了, 环境变量字符集,   数据库连接池字符集后. 


还有其他方法可以用吗? 


是的.  


oracle 的cx-oracle 已经给准备好了. 


cx-oracle.Connection   


跟 cx-oracle.cursor

类  增加了一个   回调函数.   来处理这种异常. 



当然也可以 实现反人类的  . 突破默认 类型转换的 黑客方法. 


  1.     oracle  从float  转换为 python  的 decimal


          

OutputTypeHandleri1(cursor, , defaultType, size, , ):
    defaultType (cx_Oracle.STRING, cx_Oracle.FIXED_CHAR):
        cursor.var(binary, size, cur.arraysize, =OutConverter)
cursor.outputtypehandler = OutputTypeHandler
可以吧字符串转为 binary
2.  字符集转换错误.  
def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
    if defaultType == cx_Oracle.STRING:
        return cursor.var(defaultType, size, arraysize=cursor.arraysize,
                          encodingErrors='surrogateescape')
                          
    connection.outputtypehandler = OutputTypeHandler
    
    或者  
    
    cursor. outputtypehandler = OutputTypeHandler
    
    
    
   3.  要求 . 
   
               要cx-oracle  6.4  以后版本.  
               
               
       之前的版本 , 基本无解了.






















来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/133735/viewspace-2683925/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
oracle MySQL Postgresql 专职数据库dba。 系统架构师。 mysql 官方认知dba 。 15年专职dba 经验。 潜意识沟通实证者 心理咨询师。 禅修布道者, 禅修指导员。 禅定实证者。

注册时间:2010-12-02

  • 博文量
    367
  • 访问量
    1908882