简体   繁体   中英

Why store binary data in MySQL?

I'm a little confused - what are the pros of storing binary data in DB? Is it for security reasons, or there are some more complicated motives i don't see?

Thanks for your time.

As opposed to what? Putting it in the filesystem?

The drawbacks to using the filesystem for binary file storage would be:

  • you don't get ACID compliance;

  • if you might be hosting the application on more than one server (eg load-balancing, failover), you have to work out some kind of shared file storage to avoid the backend getting out of sync;

  • having only one storage backend instead of two makes deployment simpler.

So with database-only storage, you don't have to worry about creating a folder with write access for the web user, the whole app can be read-only. If you need to move the application, you can just check it out of source control and point it to the database without having to copy more file data across. Your database backups can be covering everything instead of having to have a separate file backup step. And so on.

On the other hand the drawbacks to database BLOB storage:

  • unwieldy for very large files;

  • you don't get to use the web server to serve the files up efficiently for free.

The same advantages storing anything in a database gives you

  • You can index the data on another column or primary key providing fast retrieval of the data
  • Its accessible from one location and deals with row-level concurrency issues for you
  • It can appropriately cache commonly used data
  • You can fine tune the table engine used to store the data
  • You can model relationships between the binary data and rows in other tables (users/pages/whatever)

I don't see why it matters that the data is text or binary, a database gives you a ton of advantages.

I'll assume the other alternative is to store binary data in a file and storing the filename instead of data in the corresponding record of the DB. The problem with that approach is that it is not consistent: anything can happen to your file, it may become damaged or deleted, and the DBMS (MySQL in this case) can't do anything about it: it cannot ensure consistency because it does not know anything about your file. Another thing, the DBMS can optimize access to your data (it may store it in the memory and not read it from disk every time you have to access it) while with the file-based approach, you'd have to wait until the query is completed, then open the file and read the data from disk. It would reduce performance dramatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM