tags:

views:

39

answers:

1

I am trying to save a BLOB created from an integer array (that is, a packed array of integers) in an SQLite DB. The script shown below gives the following traceback. As far as I can see from the Python 2.7 sqlite3 documentation, it should be possible to insert a buffer object into a table, where it is supposed to be saved as a BLOB. However, I am unable to make this work. (FWIW, isinstance(b,buffer) prints True if inserted into the script, so I'm indeed creating a buffer object.)

Any suggestions?

Thanks, -P.

Traceback (most recent call last):
  File "example.py", line 13, in <module>
    conn.execute( 'insert into foo values (?)', (b,) ) # <=== line 14
ValueError: could not convert BLOB to buffer

import sqlite3
import sys
import array

ar = array.array( 'I' )
ar.extend( [1,0,3,11,43] )
b = buffer( ar )

conn = sqlite3.connect( ':memory:' )
conn.execute( 'create table foo( bar BLOB )' )
conn.commit()

conn.execute( 'insert into foo values (?)', (b,) ) # <=== line 14
conn.commit()
+1  A: 

Cristian Ciupitu's note about the bug is correct, but bytes(ar) will give you the __str__ representation instead of a serialized output. Therefore, use ar.tostring().

Use array.fromstring to unserialize the array again - you have to create an array object with the same type and then call .fromstring(...).

AndiDog
You're right. Using `bytes(ar)` in Python 2.x isn't correct in this case.
Cristian Ciupitu
Thanks. This works. In addition, I've found that the following also works, and is equivalent:buf = buffer( ar )b = bytearray( buf )blob = sqlite3.Binary( b )but "b = ar.tostring()", as you suggest, is a better way to get b, and has the nice characteristic that array.fromstring() provides symmetric way of decoding the data when reading the DB.Thank you again,-P.
Peter Shenkin
Calling `sqlite3.Binary` is the same as calling `buffer` (check out the source code from `sqlite3/dbapi2.py`).
Cristian Ciupitu