2010-04-25 31 views
1

我想在python中打開一個圖像文件並將該數據添加到sqlite表。我使用以下方式創建了表格: 「CREATE TABLE」images「(」id「INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,」description「VARCHAR,」image「BLOB);」使用python插入文件數據到sqlite數據庫的問題

我試圖使用圖像添加到數據庫:

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' 我得到'????'打印到控制檯。任何人都知道我在做什麼錯了?

+0

您使用的是什麼版本的Python? – dan04 2010-04-25 03:48:16

回答

2

它適用於我的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                 
▒                  
[email protected]%                 
     ��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 
▒ 
[email protected]% 
     ��sRGB��� pHYs 

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

呀它怪異的,當我在python查詢數據庫,將二進制數據後,它讓我看到的數據被成功地插入(它噴出的二進制數據到屏幕)。當我這樣做:sqlite3 database_file.sqlite「從圖像中選擇圖像」在命令行上,這就是當我看到'????'。也許這就是'sqlite3'命令如何打印二進制數據?這看起來不正確。我正在使用python 2.6.1

+0

原來,sqlite3是如何在命令行上表示二進制數據的。 – Tylerc230 2010-05-20 19:26:45