我只有python script
才能正常运行,仅使用MySQL 5.6
连接连接到Windows 8.1
pymysql
数据库的本地测试计算机。
Select query / fetchal()
返回元组,如('1','2015-01-02 23:11:19','25 .00')。
但是,当我使用略微修改的相同脚本来包含与MySQL 5.0.96
服务器上运行的远程Linux
生产数据库的第二个连接时,它返回tuples
之类的(b'1 ',b'2015-01-02 23:11:19',b'25.00')并且脚本无法正常运行,因为匹配条件和使用返回的元组的查询失败。
知道原因,以及如何让它返回tuples
,其列值没有“b”前缀?
答案 0 :(得分: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)
...
答案 1 :(得分: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()函数?如果有人知道,请发言,以帮助我进一步了解这一点。