使用Python将文件数据插入SQLite数据库时遇到的问题
我正在尝试在Python中打开一个图片文件,并把这个数据添加到一个sqlite数据库表里。我是这样创建这个表的:
“CREATE TABLE "images" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT 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'的值时,它看起来像是二进制数据,但当我执行:'select image from images where id = 1'时,控制台上却显示'????'。有人知道我哪里出错了吗?
2 个回答
0
嗯,这确实有点奇怪。当我在Python中查询数据库,插入了二进制数据后,它告诉我数据成功插入(会把二进制数据打印到屏幕上)。但是当我在命令行输入:sqlite3 database_file.sqlite "SELECT image from images" 时,我看到的却是'????'。也许这就是'sqlite3'命令显示二进制数据的方式?这听起来不太对。我使用的是Python 2.6.1。
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
▒
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`�