gpt4 book ai didi

python - 使用python将文件数据插入sqlite数据库时出现问题

转载 作者:行者123 更新时间:2023-12-01 06:17:07 31 4
gpt4 key购买 nike

我正在尝试在 python 中打开图像文件并将该数据添加到 sqlite 表中。我使用以下方法创建了该表:“创建表“图像”(“id”整数主键自动增量不为空,“描述”VARCHAR,“图像”BLOB);“

我正在尝试使用以下方法将图像添加到数据库:

imageFile = open(imageName, 'rb')
b = sqlite3.Binary(imageFile.read())
targetCursor.execute("INSERT INTO images (image) values(?)", (b,))
targetCursor.execute("SELECT id from images")
for id in targetCursor:
imageid= id[0]

targetCursor.execute("INSERT INTO %s (questionID,imageID) values(?,?)" % table, (questionId, imageid))

当我打印“b”的值时,它看起来像二进制数据,但是当我调用时:'从 id = 1 的图像中选择图像'我得到'????'打印到控制台。有人知道我做错了什么吗?

最佳答案

它适用于 Python 2.6.4、pysqlite (sqlite3.version) 2.4.1 和 png 测试图像。您必须解压元组。

>>> import sqlite3                                                    
>>> conn = sqlite3.connect(":memory:")
>>> targetCursor = conn.cursor()
>>> imageName = "blue.png"
>>> imageFile = open(imageName, 'rb')
>>> b = sqlite3.Binary(imageFile.read())
>>> print b
�PNG

IHDR@%
��sRGB��� pHYs

��▒tIME�
0�\"▒'S�A�:hVO\��8�}^c��"]IEND�B`�
>>> targetCursor.execute("create table images (id integer primary key, image BLOB)")
<sqlite3.Cursor object at 0xb7688e00>
>>> targetCursor.execute("insert into images (image) values(?)", (b,))
<sqlite3.Cursor object at 0xb7688e00>
>>> targetCursor.execute("SELECT image from images where id = 1")
<sqlite3.Cursor object at 0xb7688e00>
>>> for image, in targetCursor:
... print image
...
�PNG

IHDR@%
��sRGB��� pHYs

��▒tIME�
0�\"▒'S�A�:hVO\��8�}^c��"]IEND�B`�

关于python - 使用python将文件数据插入sqlite数据库时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2707070/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com