Pysqlite - how to save images

I need to save an image file to sqlite database in python. I could not find a solution. How can i do this?

Thanks in advance.

+6
python image blob sqlite3 pysqlite
source share
4 answers

write - cursor.execute('insert into File (id, name, bin) values (?,?,?)', (id, name, sqlite3.Binary(file.read())))

read - file = cursor.execute('select bin from File where id=?', (id,)).fetchone()

if you need to return data from a buffer in a web application - return cStringIO.StringIO(file['bin'])

+8
source share

Do you need to save an image in a database? I would write the image to the file system and save its path to the database. (You may not be able to do this, depending on your specific case.)

If you absolutely need to, look here .

+3
source share

I'm not sure if pysqlite is the same as sqlite3, which is used by default in the python standard library. But if you use sqlite3, you can save the image in the buffer object and save it in the blob field in sqlite. Remember the following:

  • Saving images in the database is not happy, some of them save files and the path to the database.
  • make sure you return the correct mime type
+2
source share

It is never recommended that raw types be written to databases. Could you just save the file to the file system and write the path to it in the database?

0
source share

All Articles