How to store binary data in MySQL

Maria Jahan picture Maria Jahan · Jun 11, 2012 · Viewed 18.3k times · Source

How do I store binary data in a MySQL database?

Answer

Eugen Rieck picture Eugen Rieck · Jun 11, 2012

This question is not so straight forward to answer, as it sounds: There are lots of different binary data usage patterns out there, each with their own caveats and pros and cons. Let me try to summarize:

  • Short pieces of binary data, such as password hashes, work very well by simply base64-encoding them and storing the resulting string as a VARCHAR
  • "Not-quite-binary" data, such as document snipplets with the occasional non-printable can be escaped and sored as a string
  • The BLOB datatype allows you to store arbitrary chunks of binary data, but I strongly recommend against using it: Store the data in a file, then store the path to the file in a String type. You gain nothing from storing binary data, that the DB doesn't "understand" in the DB.