pymysql 连接 select 查询和 fetchall return 元组具有像 b'25.00' 这样的字节文字而不是像 '25.00' 这样的字符串

pymysql connection select query and fetchall return tuple that has byte literals like b'25.00' rather than strings like '25.00'

我有一个 python script,仅当使用 pymysql 连接连接到我在 Windows 8.1 上具有 MySQL 5.6 数据库的本地测试机器时运行良好。 Select query / fetchal() returns 元组,如 ('1', '2015-01-02 23:11:19', '25.00').

但是,当我使用稍微修改过的相同脚本以包含与在 Linux 服务器上运行的远程 MySQL 5.0.96 生产数据库的第二个连接时,它 returns tuples like (b'1', b'2015-01-02 23:11:19', b'25.00') 并且脚本无法正确运行,因为匹配条件和使用 returned 元组的查询失败.

知道为什么,以及如何使 return 具有没有 "b" 前缀的列值的 tuples

b 前缀表示 Python3 中的字节文字。尝试将其转换为字符串。

...
res = (b'1', b'2015-01-02 23:11:19', b'25.00')
new_res = []
for i in res:
    new_res.append(i.decode(encoding='utf-8'))

new_res = tuple(new_res)
...

我通过以下解决方法解决了这个问题。它涉及处理从远程数据库列返回的字节文字,如下面我为解释答案而创建的示例所示。

conn = pymysql.connect(host=myHost, port=myPort, user=myUser, passwd=myPassword, database=myDatabase, charset="utf8")
cur = conn.cursor()

theDateTime = re.sub( r' ', '-', str(datetime.now()))
theDateTime = theDateTime[0:10] + " " + theDateTime[11:19]

productName = 'abc'
myMaxPrice = 100.0

try:
    # The below query to the remote database returned tuples like (b'1', b'2015-01-02 23:11:19', b'25.00') for MySQL DB tableA columns: ID, date_changed, price
    query = "SELECT IFNULL(ID,''), IFNULL(date_changed,''), IFNULL(price, '') FROM tableA WHERE product = '" + productName + "';"   
    cur.execute(query)
    for r in cur.fetchall():
        # Given the returned result tuple r[] from the remote DB included byte literals instead of strings, I had to encode the '' strings in the condition below to make them byte literals
        # However, I did not have to encode floats like mMaxyPrice and float(r[2]) as they were not a string; float calculations were working fine, even though the returned float values were also byte literals within the tuple
        if not r[1] and float(r[2]) >= myMaxPrice: 
            #Had to encode and then decode r[0] below due to the ID column value r[0] coming back from the remote DB query / fetchall() as a byte literal with a "b" prefix
            query = "UPDATE tableA SET date_changed = '" + theDateTime + "', price = " + str(myMaxPrice) + " WHERE ID = " + r[0].decode(encoding='utf-8') + ";"  
            cur.execute(query)
            conn.commit()
except pymysql.Error as e:
    try:
        print("\nMySQL Error {0}: {1}\n".format(e.args[0], e.args[1]))
    except IndexError:
        print("\nMySQL Index Error: {0}\n".format(str(e)))
    print("\nThere was a problem reading info from the remote database!!!\n") 

感谢 m170897017 指出这些是字节文字,感谢 Neha Shukla 帮助澄清。我仍然有兴趣弄清楚为什么远程数据库返回字节文字,而不是本地数据库返回的字符串。是否需要使用某种编码来连接到远程数据库以及如何连接?是远程数据库中使用的 MySQL 的旧版本导致的吗?是 Linux 远程与 Windows 本地的区别吗?还是引入字节文字的 fetchall() 函数?如果有人知道,请提出来帮助我进一步了解这一点。