如何使用mysql.connector从MySQL返回str? [英] How to return str from MySQL using mysql.connector?
本文介绍了如何使用mysql.connector从MySQL返回str?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将mysql.com中的MySQL Connector/Python与Python 3配合使用.
I'm trying to use MySQL Connector/Python from mysql.com with Python 3.
我有采用UTF-8编码的表,并且当我获取行时,我所有的char列都像bytearray
一样返回.这有点令人困惑.
I have tables in UTF-8 coding, and when I fetch the rows, all my chars columns returned like bytearray
. This is make some confusion.
如何直接获取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()
输出:
(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',)
UPD2:
我的表使用COLLATE utf8_bin
.
推荐答案
使用二进制排序规则时似乎会发生这种情况,至少对我来说也是一样.要将字节数组转换为Unicode字符串,可以添加一个自定义转换器类:
Seems like this happens when you use binary collation, at least the same happened to me. To convert the bytearrays to Unicode strings, you can add a custom converter class:
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=...)
这篇关于如何使用mysql.connector从MySQL返回str?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文