Import hex/binary data into mysql

泄露秘密 提交于 2020-01-10 09:03:51

问题


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.


回答1:


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)



回答2:


Couldn't find any alternative. It looks like the only way is the binary one (also, there is already a bug/feature-request on mysql regarding this).

Two things to consider:

  • text-file encoding when generating the input file;
  • character escaping (NEW-LINE, TAB, QUOTE, etc);


来源:https://stackoverflow.com/questions/12038814/import-hex-binary-data-into-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!