环境: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/