环境:MariaDB Server 10.1.14上的Python 3.5.2,MySQL.Connector 2.0.4
为什么准备好的光标返回字节数组中的字符串值,而标准光标返回普通字符串?
对于具有相同实例的相同调用,我的Prepared光标输出:
[(11, bytearray(b'1234567890'), None),
(17, bytearray(b'1234567799'), bytearray(b'[email protected]'))]
虽然standard版本会提供所需的输出:
[(11, '1234567890', None),
(17, '1234567799', '[email protected]')]
标准版本代码:
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
对于prepared版本,我只将游标声明更改为
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]