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

使用python将文件数据插入sqlite数据库时出现问题,python,sqlite,blob,Python,Sqlite,Blob,我试图用python打开一个图像文件,并将该数据添加到sqlite表中。我使用以下方法创建了表: “创建表”images”(“id”整数主键自动递增不为NULL,“description”VARCHAR,“image”BLOB) 我正在尝试使用以下方法将图像添加到数据库: imageFile = open(imageName, 'rb') b = sqlite3.Binary(imageFile.read()) targetCursor.execute("INSERT INTO images (

我试图用python打开一个图像文件,并将该数据添加到sqlite表中。我使用以下方法创建了表: “创建表”images”(“id”整数主键自动递增不为NULL,“description”VARCHAR,“image”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`�
导入sqlite3 >>>conn=sqlite3.connect(“:内存:”) >>>targetCursor=conn.cursor() >>>imageName=“blue.png” >>>imageFile=open(imageName,'rb') >>>b=sqlite3.Binary(imageFile.read()) >>>打印b �巴布亚新几内亚 ▒ IHDR@% ��sRGB��� 物理学 ��▒时间� 0�\"▒'s�A.�:hVO\��8.�}^C��"]伊恩德�B`� >>>执行(“创建表映像(id整数主键,映像BLOB)”) >>>执行(“插入图像(图像)值(?),(b,) >>>执行(“从id=1的图像中选择图像”) >>>对于图像,在targetCursor中: …打印图像 ... �巴布亚新几内亚 ▒ IHDR@% ��sRGB��� 物理学 ��▒时间� 0�\"▒'s�A.�:hVO\��8.�}^C��"]伊恩德�B`�
是的,这很奇怪,当我用python查询数据库时,在插入二进制数据后,它向我显示数据已成功插入(它将二进制数据喷到屏幕上)。当我这样做时:sqlite3 database_file.sqlite“从图像中选择图像”“在命令行上,我看到了'??'。也许这就是“sqlite3”命令打印二进制数据的方式?这似乎不对。我使用的是python 2.6.1

您使用的是哪一版本的python?结果是sqlite3在命令行上如何表示二进制数据。