在 python 中读取 MySQL 个 blob
Read MySQL blob in python
您好,我从查询中获取 blob 后遇到类型问题,这是代码
conn = MySQLdb.connect("mysqlblah", "user", "pass", "db")
cursor = conn.cursor()
data = []
queryString = "SELECT * FROM contentindex where tag LIKE '" + contentType + "%'"
cursor.execute(queryString)
rows = cursor.fetchall()
columns = [t[0] for t in cursor.description]
for row in rows:
jsonRow = {}
i = 0
for column in columns:
if column == "created":
jsonRow[column] = str(row[i])
elif column == "icon":
icon = row[i]
print icon
jsonRow[column] = "data:image/(jpg);base64," + base64.b64encode(icon.getvalue())
else:
jsonRow[column] = row[i]
i = i + 1
data.append(jsonRow)
这会打印 <_io.BytesIO object at 0x01667810>
然后抛出 'str' object has no attribute 'getvalue'
异常。
我为这个问题苦恼了好几天,非常感谢任何帮助
看起来 MySQL 将 BLOB
字段类型转换为 Python str
。
根据我们在评论中的对话,我相信您无意中在此列中存储了一个值为 "<_io.BytesIO object at 0x01667810>"
的字符串,而不是您希望存储的实际数据。您可以通过几种不同的方式测试是否属于这种情况:
print icon[0] # I'm betting it will be '<'
print type(icon) # Likely 'str'
总而言之,您遇到的似乎是数据损坏问题,而不是类型方面的某种特殊问题。
您好,我从查询中获取 blob 后遇到类型问题,这是代码
conn = MySQLdb.connect("mysqlblah", "user", "pass", "db")
cursor = conn.cursor()
data = []
queryString = "SELECT * FROM contentindex where tag LIKE '" + contentType + "%'"
cursor.execute(queryString)
rows = cursor.fetchall()
columns = [t[0] for t in cursor.description]
for row in rows:
jsonRow = {}
i = 0
for column in columns:
if column == "created":
jsonRow[column] = str(row[i])
elif column == "icon":
icon = row[i]
print icon
jsonRow[column] = "data:image/(jpg);base64," + base64.b64encode(icon.getvalue())
else:
jsonRow[column] = row[i]
i = i + 1
data.append(jsonRow)
这会打印 <_io.BytesIO object at 0x01667810>
然后抛出 'str' object has no attribute 'getvalue'
异常。
我为这个问题苦恼了好几天,非常感谢任何帮助
看起来 MySQL 将 BLOB
字段类型转换为 Python str
。
根据我们在评论中的对话,我相信您无意中在此列中存储了一个值为 "<_io.BytesIO object at 0x01667810>"
的字符串,而不是您希望存储的实际数据。您可以通过几种不同的方式测试是否属于这种情况:
print icon[0] # I'm betting it will be '<'
print type(icon) # Likely 'str'
总而言之,您遇到的似乎是数据损坏问题,而不是类型方面的某种特殊问题。