Read binary data from MySQL database

Carsten Haese carsten at uniqsys.com
Thu May 10 10:32:29 EDT 2007


On Thu, 2007-05-10 at 07:19 -0700, Christoph Krammer wrote:
> Hello,
> 
> I try to write a python application with wx that shows images from a
> MySQL database. I use the following code to connect and get data when
> some event was triggered:
> 
> dbconn = MySQLdb.connect(host="localhost", user="...", passwd="...",
> db="images")
> dbcurs = dbconn.cursor()
> dbcurs.execute("""SELECT imgdata FROM images LIMIT 1""")
> imgstring = dbcurs.fetchone()[0]
> frame.showImage(imgstring)
> 
> Within my frame, the following method is defined:
> 
> def showImage(self, imgstring):
>   imgdata = StringIO.StringIO()
>   imgdata.write(imgstring)
>   print imgdata.getvalue()
>   wx.ImageFromStream(imgdata, wx.BITMAP_TYPE_GIF)
>   panel = wx.Panel(self, -1)
>   self.panel = panel
> 
> But this does not work. The converter says that the data is not valid
> GIF. When I print the content of imgstring after the database select
> statement, it contains something like this:
> 
> array('c', 'GIF89aL\x01=\x01\x85\x00\x00\x00\x00\x00\xff\xff\xff
> \x00\xff\xff\xff[...]\x00\x00;')

That means that imgstring is not a string, it's an array of characters.
Observe:

>>> import array
>>> a = array.array('c', 'Blahblahblah')
>>> print a
array('c', 'Blahblahblah')
>>> str(a)
"array('c', 'Blahblahblah')"
>>> a.tostring()
'Blahblahblah'

Calling write() with an object that's not a string will implicitly call
str() on that object and write the result of that call to the file. Try
imgdata.write(imgstring.tostring()) to extract the string data from the
array.

Hope this helps,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list