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

Gul*_*tin 13 python mysql collation utf-8 python-3.x

我使用Python3,并尝试使用mysql.com中的MySQL Connector/Python

我有UTF-8编码表,当我获取行时,我的所有字符列都返回像bytearray一样.这让人有些困惑.

我怎么能直接获取str?

UPD:

# -*- 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()
Run Code Online (Sandbox Code Playgroud)

输出:

(bytearray(b'ezsp.ru'),)
(bytearray(b'eazyshop.ru'),)
(bytearray(b'127.0.0.1:8080'),)
(bytearray(b'rmsvet.ru'),)
Run Code Online (Sandbox Code Playgroud)

我想要:

('ezsp.ru',)
('eazyshop.ru',)
('127.0.0.1:8080',)
('rmsvet.ru',)
Run Code Online (Sandbox Code Playgroud)

UPD2:

我的表使用COLLATE utf8_bin

dan*_*elo 5

当您使用二进制排序规则时,似乎会发生这种情况,至少对我来说也是一样。要将字节数组转换为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=...)
Run Code Online (Sandbox Code Playgroud)


LSE*_*LSE -1

我不认为你可以让光标返回字符串。MySQL连接器文档表示,他们选择返回字节数组,这样他们只需为 Python2 和 Python3 维护一个代码库:

\n\n
\n

使用 \xe2\x80\x9craw\xe2\x80\x9d 游标时,返回值是 bytearray 类型。这是让 Python 2 和 3 返回相同数据所必需的。

\n
\n\n

我使用列表理解来解码行中的每个字节数组解决了这个问题:

\n\n
for row in cursor:\n    type_fixed_row = tuple([el.decode(\'utf-8\') if type(el) is bytearray else el for el in row])\n    print( type_fixed_row )\n
Run Code Online (Sandbox Code Playgroud)\n

  • *raw* 默认情况下不启用,所以我觉得这很令人费解。[文档](https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html#idm140343529540800)说“默认情况下,来自MySQL的字符串作为Python Unicode文字返回。” (2认同)