如何通过 python snowflake 连接器处理 Unicode 字符问题,同时从 snowflake 读取数据

How to handle Unicode character issues through python snowflake connector, while reading data from snowflake

使用 python snowflake 连接器从 snowflake 读取数据时,出现以下错误:

"InterfaceError: 252005: Failed to convert current row, cause: 'utf-8' codec can't decode byte 0xe1 in position 316: invalid continuation byte"

该字符串包含非 UTF-8 字符,雪花光标无法 return 该值。 这种情况怎么处理,需要内容

Python 版本 3.7.6 雪花 Python 连接器 5.5.1

示例代码:

import snowflake.connector 

ctx = snowflake.connector.connect(user='user', password='pwd',account='act',warehouse='wrh', database='db', schema='schema', role = 'role' ) 
cur = ctx.cursor() 
cur.arraysize = 10000 
sql = """select longText from db.schema.table where textId = 1279""" 
cur.execute(sql) 
for element in cur: 
   print(element[0])

示例数据:

xxxx: xxxxxxxx@xxxxx.xxx Tx: xttxxh@xxxxx.xxx xx: xuxxxxt: xx: xxx00x0x3 : xxxxxxx0x= // Hxvx x xxxx xx-Xxxxx-xxx thxt xxxt xxxx. xxgx xhxx thxt thx xhxxxx (Uxxxxxxxxxxx) -----xxxgxxxx xxxxxgx----- xxxx: xxxx, xxux x xxV (Ux) [xxxxtx:xxux.x.xxxx.xxv@xxxx.xxx] xxxt: xxxxxxxxy, xxvxxxxx xx, x01x 1x:1x xx Tx: xxxxxáx xx xxxáxxx xx: xxxx, xxux x xxV (Ux) xuxxxxt: xx: xxx00x0x3 : xxxxxxx0x= // Hxvx x xxxx xx-Xxxxx-xxx thxt xxxt xxxx. xxgx xhxx thxt thx xhxxxx (Uxxxxxxxxxxx)

尝试 select hex_encode(longText) 而不是 select longText。这会将存在于该字段中的任何奇怪的二进制文本转换为可以安全传输的字符串。然后你可以在 Python.

的安全范围内将其解码回来

例如,在sql中:

select hex_encode('hello')

那个 returns 68656C6C6F,你可以在 Python 中解码回来:

>>> bytes.fromhex('68656C6C6F')
b'hello'

此技术还将让您深入了解使您的代码出错的奇怪字符可能是什么 - 以及使用何种编码。

>>> bytes.fromhex('68656C6C6F')
b'hello'
>>> bytes.fromhex('F09F9988')
b'\xf0\x9f\x99\x88'
>>> bytes.fromhex('F09F9988').decode('utf-8')
''