how to store binary file data to a database blob
Benjamin Niemann
b.niemann at betternet.de
Thu May 27 11:23:50 EDT 2004
> I'd like to read the contents of a file into memory. The problem is
> that this file is binary. I then want to store the whole thing in
> memory to a database as a blob.
> I have no problem reading from a file: I did this:
>
> import os
> f = open('/bin/ls' , 'r+b')
> data = f.read()
> f.close()
>
> How do I place that in a blob? If I concatenate this to a sql string,
> how will the database sql parser know where my data string ends, knowing
> that my data string could contain lots of ' and " and other little
> things in it. ???
>
> storeString = "insert into mytable (filedata) values ( %s ) " % data
>
> Does that look right? I don't think it would execute correctly.
This probably won't work... Try this (assuming you are working with a
Python DB API compatible database class):
cursor.execute("insert into mytable (filedata) values ( %s ) ", data)
This will let the database class replace %s by your data, including all
required escaping stuff - in contrast to a 1:1 string replacment when
using the % operator. This works at least for arbitrary strings (and
that's the way to handle strings, if you don't like SQL injections ;)
But I never tried this with blobs - perhaps they need some special
treatment (thinking e.g. of laaarge files)...
More information about the Python-list
mailing list