python - 为什么mysql.connecter python准备语句返回字节数组中的字符串

标签 python prepared-statement mariadb

环境:Python 3.5.2,MySQL.Connector 2.0.4,MariaDB 服务器 10.1.14

为什么准备游标返回字节数组中的字符串值,而标准游标返回普通字符串?

对于相同实例的相同调用,我的准备光标输出:

[(11, bytearray(b'1234567890'), None),
 (17, bytearray(b'1234567799'), bytearray(b'abc@outlook.com'))]

虽然标准 版本提供了所需的输出:

[(11, '1234567890', None),
 (17, '1234567799', 'abc@outlook.com')]

标准版代码:

def query_userdb(query, arg):
    retVal = None
    cnx = mariadb.connect(**DB_CONFIG_USERS)
    cursor = cnx.cursor()
    cursor.execute(query, arg)
    if cursor.rowcount != 0:
        retVal = cursor.fetchall()
    cnx.commit()
    cnx.close()
    return retVal

对于准备好的版本,我只将游标声明更改为

    cursor = cnx.cursor(prepared=True)

如何让准备好的游标正确返回字符串?

最佳答案

要获取字符串,您可以使用:

my_bytearray.decode("utf-8")

在您使用列表理解的情况下:

retVal = [(id,col2.decode("utf-8"),col3.decode("utf-8") for id,col2,col3 in retVal]

或者更好地处理第三列中的 None 值:

retVal = [(id,col2.decode("utf-8"),(col3 if col3 is None else col3.decode("utf-8")) for id,col2,col3 in retVal]

关于python - 为什么mysql.connecter python准备语句返回字节数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38288862/

相关文章:

python - 将 .py 文件编译为 .pyo 而不求助于包装器脚本

java - 准备好的声明有问题

php - mysqli_stmt::bind_param():变量数量与准备好的语句中的参数数量不匹配

mysql - 使用变量时慢的sql语句

python - 复制具有 unicode 名称的文件

python - 返回作为参数传递的相同值的模拟方法

mysql - R:RMariaDB 不适用于 3.4.0 - 如何从 R v 3.4.0 连接到 MySQL?

mysql - utf8_bin 和 latin1_general_cs 有什么区别

python - numpy.distutils 对架构的奇怪选择

PHP Postgres 使用带间隔的特殊输入值