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

2024-09-29 21:58:37 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python snowflake connector从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字符,雪花光标无法返回该值。 如何处理这种情况,内容是必需的

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)

Tags: inconnectorschemabytexxxctxxxxxxxx
1条回答
网友
1楼 · 发布于 2024-09-29 21:58:37

请尝试select hex_encode(longText),而不是select longText。这将把该字段中存在的任何奇怪的二进制文本转换为可安全传输的字符串。然后,您可以在Python的安全范围内对其进行解码

例如,在sql中:

select hex_encode('hello')

返回68656C6C6F,您可以用Python对其进行解码:

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

这项技术还将让您了解代码中出现的奇怪字符可能是什么,以及使用什么编码

enter image description here

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

相关问题 更多 >

    热门问题