我试图将MySQL.com中的MySQL Connector/Python与Python 3一起使用。
我有UTF-8编码的表,当我获取行时,所有chars列都像bytearray
一样返回。这让人有些困惑。
如何直接获取str
?
升级版:
# -*- coding: utf-8 -*-
import mysql.connector
con = mysql.connector.connect( user ="root", db = "vg_site_db", charset = 'utf8' )
cursor = con.cursor()
sql = """select caption from domains
"""
cursor.execute( sql )
row = cursor.fetchone()
while row is not None:
print( row )
row = cursor.fetchone()
输出:
(bytearray(b'ezsp.ru'),)
(bytearray(b'eazyshop.ru'),)
(bytearray(b'127.0.0.1:8080'),)
(bytearray(b'rmsvet.ru'),)
我想要:
('ezsp.ru',)
('eazyshop.ru',)
('127.0.0.1:8080',)
('rmsvet.ru',)
升级版2:
我的表使用COLLATE utf8_bin
。
当你使用二进制排序规则时,似乎会发生这种情况,至少在我身上也是如此。要将bytearray转换为Unicode字符串,可以添加自定义转换器类:
在requirements.txt中添加
mysql-connector-python==8.0.17
解决了这个问题。当使用二进制排序规则定义各个列时,MySQL连接器将字符串(使用
CHAR
、VARCHAR
和TEXT
数据类型存储)返回为bytearray
(例如utf8_bin
)。必须对值调用.decode()
,才能获取Python字符串,例如:也就是说,除非您有使用
utf8_bin
的特定要求,否则最好在数据库级别使用带排序规则的utf8mb4_unicode_ci
字符集。这将解决您的问题,并允许完全的Unicode支持。有关详细信息,请参见this和this。相关问题 更多 >
编程相关推荐