将MySQL数据库中的Blob导出到仅包含SQL的文件

sui*_*ide 25 mysql sql blob export image

我有一个表,图像数据存储在MySQL数据库的blob字段中.有没有办法只使用SQL将这些图像导出到文件系统上的文件?图像应命名为{imageId} .jpg

我知道用Java或其他方法很容易做到这一点,但只用SQL脚本就可以了吗?

Sha*_*are 19

假设您INTO在要存储文件的位置具有写入权限,则可以执行以下操作:

SELECT id, blob INTO DUMPFILE '/tmp/path' FROM table;
Run Code Online (Sandbox Code Playgroud)

不幸的是,在MySQL中,无法将dumpfile指定为表达式/变量.但是,如果将其包装在存储过程中并使用变量,则可以实现此目的.

  • 似乎使用`dumpfile`而不是`outfile`有助于序列化Java对象。 (2认同)

ajr*_*eal 14

我不喜欢这个主意......

drop procedure if exists dump_image;
delimiter //
  create procedure dump_image()
  begin

    declare this_id int;
    declare cur1 cursor for select imageId from image;
    open cur1;
      read_loop: loop
        fetch cur1 into this_id;
        set @query = concat('select blob_field from image where imageId=', 
            this_id, ' into outfile "/tmp/xyz-', this_id,'.jpg"');
        prepare write_file from @query;
        execute write_file;
      end loop;
    close cur1;
  end //
delimiter ;
Run Code Online (Sandbox Code Playgroud)

尽管有错误

mysql> call dump_image();
ERROR 1329 (02000): No data - zero rows fetched, selected, or processed
ls -1 /tmp/xyz*

  • 同意不喜欢自己的想法,你需要非常小心重新安全等.但是elegent解决方案 - outfile反对dumpfile导致我的文件损坏 (3认同)
  • +1非常好的方式来做到这一点.正如Shaun已经评论过的,如果在使用此过程后图像未显示,请使用"dumpfile"而不是"outfile". (2认同)