Exporting Blob from MySQL database to file with only SQL

suicide picture suicide · Jan 10, 2011 · Viewed 57.9k times · Source

I have a table with image data stored in a blob field in a MySQL database. Is there a way to export those images to files on the filesystem by using only SQL? The images should be named {imageId}.jpg

I know that it is easy to do this with Java or whatever but is it possible with just a SQL script?

Answer

Shaun Hare picture Shaun Hare · Jan 10, 2011

Using INTO, and assuming you have write permission as the mysql user in the location you wish to store the files, you can do:

SELECT id, blob INTO DUMPFILE '/tmp/path' FROM table;

Unfortunately, in MySQL it is not possible to specify the dumpfile as an expression/variable. However, you could achieve this if you wrapped it in a stored procedure and use variables.