我通过以下解决方法解决了这个问题。它涉及处理从远程数据库列返回的字节文字,如下面的示例所示,我创建该示例来解释答案。
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() 函数?如果有人知道,请提出来帮助我进一步理解这一点。