在Python中读取MySQL blob

2024-05-16 22:28:11 发布

您现在位置: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'异常。在

我为这个问题忙了好几天,任何帮助都将不胜感激


Tags: columnsinfordatacolumnconncursorrows
1条回答
网友
1楼 · 发布于 2024-05-16 22:28:11

看起来MySQL将BLOB字段类型转换为Pythonstr。在

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

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

总之,您似乎有数据损坏的问题,而不是类型的某种外来问题。在

相关问题 更多 >