Вы находитесь на странице: 1из 3

4/26/2017 Storing BLOBs in a SQLite DB with Python/pysqlite - Eli Bendersky's website

Storing BLOBs in a SQLite DB with Python/pysqlite


(http://eli.thegreenplace.net/2009/05/29/storing-blobs-
in-a-sqlite-db-with-pythonpysqlite)
May 29, 2009 at 09:06 Tags Databases (http://eli.thegreenplace.net/tag/databases) , Python
(http://eli.thegreenplace.net/tag/python)

I must be looking in all the wrong places, but I haven't found many usable examples online of storing BLOBs in a SQLite
database using Python. At least, not something that works with current versions of Python (2.5), pysqlite(2.3.2) and
SQLite (the version that comes installed with Python 2.5). Overall, there doesn't seem to be much good examples of
pysqliteanywhere.

So here's an example I cooked up after consulting with several sources and experimenting a little:

http://eli.thegreenplace.net/2009/05/29/storing-blobs-in-a-sqlite-db-with-pythonpysqlite 1/3
4/26/2017 Storing BLOBs in a SQLite DB with Python/pysqlite - Eli Bendersky's website

import sqlite3 as sqlite

# Create a new in-memory DB and a cursor


#
con = sqlite.connect(':memory:')
cur = con.cursor()

# The table is named 'frames'


# The columns are: a running ID, and a data blob
#
cur.execute('''
create table frames (
id integer primary key,
data blob)''')

# Shove some data into the table. The data stored


# using the sqlite.Binary type, which means a BLOB.
#
cur.execute('''
insert into frames values (null, ?)''',
(sqlite.Binary('\0' * 10 + '\x12'),))
cur.execute('''
insert into frames values (null, ?)''',
(sqlite.Binary('\x01\x42\x55'),))

# Now read it back. When BLOBs are read, they're


# converted to Python buffers of type 'buffer'
#
for row in cur.execute("select * from frames"):
print row[0], str(row[1]).encode('hex')

cur.close()

http://eli.thegreenplace.net/2009/05/29/storing-blobs-in-a-sqlite-db-with-pythonpysqlite 2/3
4/26/2017 Storing BLOBs in a SQLite DB with Python/pysqlite - Eli Bendersky's website

con.close()

Comments
comments powered by Disqus (http://disqus.com)

2003-2017 Eli Bendersky Back to top

http://eli.thegreenplace.net/2009/05/29/storing-blobs-in-a-sqlite-db-with-pythonpysqlite 3/3

Вам также может понравиться