Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a file in MySQL database?

I want to insert a file in MYSQL database residing on a remote webserver using a webservice.

My question is: What type of table column (e.g. varchar, etc.) will store a file? And will the insert statement be somewhat different in case of a file?

like image 978
meetpd Avatar asked May 11 '11 03:05

meetpd


People also ask

How do I add a file in MySQL?

Add File Uploads CREATE TABLE uploads (id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY, description CHAR(50), data LONGBLOB, filename CHAR(50), filesize CHAR(50), filetype CHAR(50) ); The first thing you should notice is a field called id that is set to AUTO_INCREMENT.

How do I insert a file into a database?

In Object Explorer, connect to an instance of the SQL Server Database Engine and then expand that instance. Expand Databases, right-click the database from which to add the files, and then click Properties. In the Database Properties dialog box, select the Files page. To add a data or transaction log file, click Add.

Can you store files in a MySQL database?

In general, the contents of a file are stored under Clob (TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT) datatype in MySQL database. JDBC provides support for the Clob datatype, to store the contents of a file in to a table in a database.

How do I insert data into a MySQL database from a text file?

mysql> LOAD DATA LOCAL INFILE '/path/pet. txt' INTO TABLE pet; If you created the file on Windows with an editor that uses \r\n as a line terminator, you should use this statement instead: mysql> LOAD DATA LOCAL INFILE '/path/pet.


2 Answers

The BLOB datatype is best for storing files.

  • See: How to store .pdf files into MySQL as BLOBs using PHP?
  • The MySQL BLOB reference manual has some interesting comments
like image 109
Brian Webster Avatar answered Oct 21 '22 01:10

Brian Webster


File size by MySQL type:

  • TINYBLOB 255 bytes = 0.000255 Mb
  • BLOB 65535 bytes = 0.0655 Mb
  • MEDIUMBLOB 16777215 bytes = 16.78 Mb
  • LONGBLOB 4294967295 bytes = 4294.97 Mb = 4.295 Gb

Yet, in most cases, I would NOT recommend storing big blobs of bytes in database, even if it supports it, because it will increase overall database size & may cause real performance issues. You can read more on topic here. Many databases that care about consistent performance won't even let you do such thing. Like e.g. AWS DynamoDB, which is known to perform extremely well at any scale, limits single item record to 400KB. MongoDB does allow 16MB, which is also already too much, imo. MySQL allows all 4GB if you wish. But again, think twice before doing that. The case where you may be OK to store big blob of data with these column types would be - you have small traffic database and you just want to save all the stuff in one place for faster development. Like internal system in a small company.

like image 26
Lukas Liesis Avatar answered Oct 21 '22 00:10

Lukas Liesis