在python中读取MySQL blob

时间:2015-08-13 11:20:35

标签: python mysql python-2.7 io blob

我从查询中获取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'异常。

我在这个问题上花了好几天,非常感谢任何帮助

1 个答案:

答案 0 :(得分:2)

看起来MySQL将BLOB字段类型转换为Python str

根据我们在评论中的对话,我相信您无意中在此列中存储了值为"<_io.BytesIO object at 0x01667810>"的字符串,而不是您希望存储的实际数据。您可以通过几种不同的方式测试是否是这种情况:

print icon[0]  # I'm betting it will be '<'
print type(icon)  # Likely 'str'

总之,看起来你有一个数据损坏问题,而不是类型的某种奇特的问题。