How do I store binary data in MySQL?
相关问题
- sqlyog export query result as csv
- NOT DISTINCT query in mySQL
- NOT DISTINCT query in mySQL
- MySQL: conduct a basic search
- Flush single app django 1.9
How do I store binary data in MySQL?
For a table like this:
Here is a PHP example:
The question also arises how to get the data into the BLOB. You can put the data in an INSERT statement, as the PHP example shows (although you should use mysql_real_escape_string instead of addslashes). If the file exists on the database server, you can also use MySQL's LOAD_FILE
It depends on the data you wish to store. The above example uses the
LONGBLOB
data type, but you should be aware that there are other binary data formats:TINYBLOB/BLOB/MEDIUMBLOB/LONGBLOB
VARBINARY
BINARY
Each has their use cases. If it is a known (short) length (e.g. packed data) often times
BINARY
orVARBINARY
will work. They have the added benefit of being able ton index on them.While it shouldn't be necessary, you could try
base64
encoding data in and decoding it out. That means the db will just have ascii characters. It will take a bit more space and time, but any issue to do with the binary data will be eliminated.While you haven't said what you're storing, and you may have a great reason for doing so, often the answer is 'as a filesystem reference' and the actual data is on the filesystem somewhere.
http://www.onlamp.com/pub/a/onlamp/2002/07/11/MySQLtips.html
I strongly recommend against storing binary data in a relational database. Relational databases are designed to work with fixed-size data; that's where their performance strength is: remember Joel's old article on why databases are so fast? because it takes exactly 1 pointer increment to move from a record to another record. If you add BLOB data of undefined and vastly varying size, you'll screw up performance.
Instead, store files in the file system, and store file names in your database.