我有一个
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”前缀?
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() 函数引入了字节文字?如果有人知道,请提出来帮助我进一步理解这一点。
我对 pymssql 库也有同样的问题...
执行应返回字符串的简单查询时:
SELECT SERVERPROPERTY('productversion') as version
,它返回一个字节数组(字节文字?)。我没有在 python 端转换它,而是更改了 sql 查询,并且库给了我一个可以使用的字符串:
SELECT cast(SERVERPROPERTY('productversion') as varchar) as version