How can I write image to MySQL database?



I have a database, such as: Database schema

In Mathematica, the final code is:


I tried SQLInsert[conn,"mathematica",{"image"},{img1}];

but the MySQL result is:

Example with just image name inserted

How can I write the image to MySQL database?

Darren Lee

Posted 2013-02-25T06:00:36.350

Reputation: 557

Try SQLBinary as described in

– Sjoerd C. de Vries – 2013-02-25T08:20:39.403

@user5990: Export returns the full path to the file it wrote and that's what you are inserting into your database. If, as I guess, you want to write the file content instead of the filename you could e.g. use ExportString and ToCharacterCode to get a binary representation of the file content to insert into your database... – Albert Retey – 2013-02-25T08:53:16.260


Yes, there is an example in the docs that does this exactly

– Ajasja – 2013-02-25T09:28:27.463

@Ajasja how's that different than what I pointed to above? – Sjoerd C. de Vries – 2013-02-25T18:00:09.080

@SjoerdC.deVries Not at all, I just did not scroll far enough to see it. no more late night for me:) – Ajasja – 2013-02-25T21:03:19.123

Good reference for Database Link, thanks a lot !! – Darren Lee – 2013-02-26T05:45:15.760



Export returns the filename to which your data was exported. Your code does insert that filename into your database, and you see that this actually does work. What you most probably want is to insert the file content, not the filename, into the database. For that you need a combination of ExportString, ToCharacterCode and SQLBinary. This is described, as Ajasja has mentioned, in the documentation for SQLBinary. Here is how it would look like for your example:

filecontent = ToCharacterCode[ExportString[resultimg1,"JPEG"]];

Depending on how you are going to read the data you might need to take care of the correct encoding, if you read and write both from the same machine with Mathematica I believe the defaults should work alright.

Albert Retey

Posted 2013-02-25T06:00:36.350

Reputation: 22 455

Thanks for your good solution :) – Darren Lee – 2013-02-26T05:45:42.093