0

我只有在使用连接连接到具有数据库的python script本地测试机器时运行良好。 返回像 ('1', '2015-01-02 23:11:19', '25.00') 这样的元组。MySQL 5.6Windows 8.1pymysqlSelect query / fetchal()

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

知道为什么,我怎样才能让它返回tuples没有“b”前缀的列值?

4

2 回答 2

0

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)
...
于 2015-01-09T06:47:14.307 回答
0

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

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() 函数?如果有人知道,请提出来帮助我进一步理解这一点。

于 2015-01-10T06:52:06.240 回答