Vertica Python 读取结果抛出 UnicodeDecodeError

hel*_*loB 2 python encode

我只是在做一个数据库表的下拉并尝试将它读入python,如下所示:

with query(full_query_string) as cur: arr = cur.fetchall()

这会产生以下错误fetchall()

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 4: invalid continuation byte

如果我select *收到此错误,而如果我限制为少量行,则不会收到此错误。我尝试在这个 SO post UnicodeDecodeError, invalid continuation byte之后用一些编码来支付但没有一个能做到这一点。在我不知道编码如何出错的大数据库表中,处理这个问题的最有效方法是什么?此外,没有特定的行是必须的,但我宁愿获得所有行,而不是有此编码问题的行。

res*_*ate 5

嘿,我知道这是一个超级晚的答案,但在尝试调试类似问题时,我从 vertica-python README 中找到了此修复程序:

虽然 Vertica 期望存储为 UTF-8 编码的 varchar,但有时无效字符串会进入数据库。您可以使用 unicode_error 连接选项指定如何处理读取这些字符。这使用与 unicode 类型相同的值(https://docs.python.org/2/library/functions.html#unicode

尝试将连接参数中的 'unicode_error' 键从或strict更改为:replaceignore

cur = vertica_python.Connection({..., 'unicode_error': 'strict'}).cursor() 
cur.execute(r"SELECT E'\xC2'") cur.fetchone()
# caught 'utf8' codec can't decode byte 0xc2 in position 0: unexpected end of data

cur = vertica_python.Connection({..., 'unicode_error': 'replace'}).cursor() 
cur.execute(r"SELECT E'\xC2'") cur.fetchone()
# ?

cur = vertica_python.Connection({..., 'unicode_error': 'ignore'}).cursor() 
cur.execute(r"SELECT E'\xC2'") cur.fetchone()
#
Run Code Online (Sandbox Code Playgroud)