I am working with a database that has a series of csv files stored in blob fields.
I'd like to select the correct file (.csv) using a select with where clause, then insert records for each line in the .csv by splitting each comma separated column.
Normally, if the file were located on disk I'd use:
LOAD DATA INFILE 'file-path'
INTO TABLE some-table
FIELDS TERMINATED BY ','
IGNORE 1 ROWS;
or if inserting records from a select I'd use:
INSERT INTO target-table
SELECT * FROM source-table
WHERE condition;
I've also tried to pass as a variable the result of the select on the table containing the files to LOAD DATA INFILE as the file path without success.
Please advise. Thank you.
AFAIK, there is no way to use
LOAD DATA INFILEto load data directly from a CSV file stored in a blob.A quote from the MySQL docs:
Assuming a table
my_blobslike:"row1 col1","row1 col2","row 1 col3"
"row 2 col1","row 2 col2","row 2 col3"
...
A simple approach is to export all the CSV data from the table into a single file and then import it. This only works if the structure of the files in the blobs is the same and there are no (possibly limited) encoding differences.
If the data in your blobs has header rows, then the headers will get imported multiple times, but they can be removed after the import.
A more convoluted (but flexible) approach is to dump the contents of the column using
SELECT ... INTO DUMPFILEand then read the file back in to the target table usingLOAD DATA INFILE. This is more flexible as you can make changes to theLOAD DATA INFILEbased on meta data in themy_blobstable.You could use a query like this to write the dump/load script:
Which will create the file
/path/to/process_csv_files.sqlwith content like:Note (from MySQL docs):
Another quote from the docs: