Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import hex/binary data into mysql

Tags:

import

mysql

blob

I need to import into a mysql server (5.5) a set of large data having one field as a blob. Following the samples of SELECT INTO OUTFILE and LOAD DATA INFILE, it works [almost] fine. However, I have a problem: the generated data in the file for the BLOB has its actually binary representation. The generated file looks like this (3rd column represents the BLOB one):

1,1,"4Vÿ"
2,1,"ª»Ì"
3,1,"Ýîÿ"
4,1,"\"3"

and the import works fine for this case with the following sql statement:

LOAD DATA INFILE 'C:/temp/mysql/mysqldump.1.txt'
INTO TABLE `test_table`
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'
;

My problem is that the text is generated by chance like this. If quotes occur, or new-line, or whatever, I will need to do the escaping manually (i.e. replace them with backslash-char) and I would like to skip this step.

So, my question is: is there any way I can import a text file with the following format (BLOB stored as hexa):

1, 1, 0x123456FF
2, 1, 0xaabbcc
3, 1, 0xddeeff
4, 1, 0x112233

with one single mysql statement?

Update: Forgot to mention - tried to import the text file with desired format directly with the LOAD DATA INFILE statement, and the result was actually storing the text '0x123456FF' in the BLOB file of the table.

like image 831
dcg Avatar asked Aug 20 '12 13:08

dcg


1 Answers

You can use the SET part of LOAD DATA INFILE, and you don't need the 0x escaping stuff:

1, 1, 123456FF
2, 1, aabbcc
3, 1, ddeeff

And then you assign the column to a variable, and then set the column to the UNHEXed version of that variable:

LOAD DATA INFILE 'file' INTO TABLE `table` (column1, column2, @var1)
SET column3 = UNHEX(@var1)
like image 53
Roland Avatar answered Sep 21 '22 21:09

Roland