如何使用MySQL.connector从MySQL返回str?

2024-05-17 19:44:17 发布

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

我试图将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


Tags: dbsqlconnectorrumysqlutf8concursor
3条回答

当你使用二进制排序规则时,似乎会发生这种情况,至少在我身上也是如此。要将bytearray转换为Unicode字符串,可以添加自定义转换器类:

class MyConverter(mysql.connector.conversion.MySQLConverter):

    def row_to_python(self, row, fields):
        row = super(MyConverter, self).row_to_python(row, fields)

        def to_unicode(col):
            if isinstance(col, bytearray):
                return col.decode('utf-8')
            return col

        return[to_unicode(col) for col in row]

sql = mysql.connector.connect(converter_class=MyConverter, host=...)

在requirements.txt中添加mysql-connector-python==8.0.17解决了这个问题。

当使用二进制排序规则定义各个列时,MySQL连接器将字符串(使用CHARVARCHARTEXT数据类型存储)返回为bytearray(例如utf8_bin)。必须对值调用.decode(),才能获取Python字符串,例如:

for row in cursor:
    caption = row[0].decode()

也就是说,除非您有使用utf8_bin的特定要求,否则最好在数据库级别使用带排序规则的utf8mb4_unicode_ci字符集。这将解决您的问题,并允许完全的Unicode支持。有关详细信息,请参见thisthis

相关问题 更多 >