首页 > 解决方案 > 使用 Python cx_Oracle 库查询时出现解码错误

问题描述

使用 pd.read_sql 时出现解码错误。我正在查询 Oracle DB 并使用 cx_oracle 库。

我尝试在 Oracle 连接字符串中传递编码参数,如下所示。

cx_oracle.connect(user=user_name, password=pwd, dsn=dsn_tns,encoding="UTF-8")

我尝试过的编码选项和每次 pd.read_sql 运行时出现的错误如下:

  1. 使用 encoding = 'UTF-8', error is utf-8' codec can't decode byte 0xc3 in position 34: unexpected end of data

  2. 使用 encoding="UTF-8",nencoding="UTF-8",错误是 utf-8' 编解码器无法解码位置 34 中的字节 0xc3:数据意外结束

  3. 使用 encoding="UTF-16", nencoding="UTF-16",错误是 ORA-29275: partial multibyte character

NLS_CHARACTERSET 是 AL32UTF8。

哪位遇到过这个问题并解决了,请指教。

谢谢

标签: pythonoracleencodingutf-8cx-oracle

解决方案


如果您有损坏的数据,请尝试 cx_Oracle 文档Querying Corrupt Data中建议的方法:

def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
    if defaultType == cx_Oracle.STRING:
        return cursor.var(defaultType, size, arraysize=cursor.arraysize,
                encodingErrors="replace")

cursor.outputtypehandler = OutputTypeHandler

cursor.execute("select column1, column2 from SomeTableWithBadData")

推荐阅读